var p = {

	util : {

		configEvents : function() {
		     if (document.addEventListener) {
		          this.addEvent = function(el, type, func, capture) {
		            el.addEventListener(type, func, capture);  
		          };
		          this.stopBubble = function(evt) { evt.stopPropagation(); };
		          this.stopDefault = function(evt) { evt.preventDefault(); };
		          this.findTarget = function(evt, targetNode, container) {
		            var currentNode = evt.target;
		            while (currentNode && currentNode !== container) {
		              if (currentNode.nodeName.toLowerCase() === targetNode) {
		                  return currentNode; break;
		              }
		              else { currentNode = currentNode.parentNode; }
		            };
		            return false;
		          };
		      }
		      else if (document.attachEvent) {
		          this.addEvent = function(el, type, func) {
		            el["e" + type + func] = func;
		            el[type + func] = function() { el["e" + type + func] (window.event); };
		            el.attachEvent("on" + type, el[type + func]);
		          };
		          this.stopBubble = function(evt) { evt.cancelBubble = true; };
		          this.stopDefault = function(evt) { evt.returnValue = false; };
		          this.findTarget = function(evt, targetNode, container) {
		            var currentNode = evt.srcElement;
		            while (currentNode && currentNode !== container) {
		              if (currentNode.nodeName.toLowerCase() === targetNode) {
		                  return currentNode; break;
		              }
		              else { currentNode = currentNode.parentNode; }
		            };
		            return false;
		          };
			}
			if (document.addEventListener) {
				this.removeEvent = function(el, type, func, capture) {
					el.removeEventListener(type, func, capture);
				};
			}
			else if (document.attachEvent) {
				this.removeEvent = function(el, type, func) {
					el["e" + type + func] = null;
					el[type + func] = null;
					el.detachEvent("on" + type, el[type + func]);
				};
			}
		},
    
		createCookie : function(name,value,expiration,path,domain,secure) {
		      var data = name + "=" + escape(value);
		      if (expiration) { 
		          var expiresAt = new Date();
		          expiresAt.setTime(expiration);
		          data += "; expires=" + expiresAt.toGMTString();
		      }
		      if (path) { data += "; path=" + path; }
		      if (domain) { data += "; domain=" + domain; }
		      if (secure) { data += "; secure"; }
		      document.cookie = data;
		},    

		findCookie : function(name) {  
		      var query = name + "=";
		      var queryLength = query.length;
		      var cookieLength = document.cookie.length;
		      var i=0;
		      while (i<cookieLength) {
		        var position = i + queryLength;
		        if (document.cookie.substring(i,position) === query) {
		           return this.findCookieValue(position);
		        }
		        i = document.cookie.indexOf(" ", i) + 1;
		        if (i == 0) { break; }  
		      }
		      return null;  
		},

		findCookieValue : function(position) {
		      var endsAt = document.cookie.indexOf(";", position);
		      if (endsAt == -1) { endsAt = document.cookie.length; }
		      return unescape(document.cookie.substring(position,endsAt));
		},
 
		eraseCookie : function(name) {
			if(this.findCookie(name)) {
				var data = name + "=";
				data += "; expires=Thu, 01-Jan-70 00:00:01 GMT";
				document.cookie = data;
			}
		}
		
	},//end of util
		    
	init : function() {
		
		//object detection
		if(!document.getElementById || !document.getElementsByTagName || !document.createElement || !document.createTextNode) {return;}
		
		this.util.configEvents();  
		
		//photo numbering starts at 1
		this.pCtr = 1;
		this.allPhotos = 10;
		this.slideCtr = 1;
		
		//javascript functions for all pages
		//open external links in new pages
		this.theBody = document.getElementsByTagName('body')[0];
		//p.util.addEvent(this.theBody,'click',p.entireSite.openExternalLinks,false);
		
		//identify divs for specific pages
		//the home page
		this.thePDiv = document.getElementById('homeTopPhoto');
		//the history page
		this.theTimelineList = document.getElementById('timelineList');
		//the membership page
		this.theMemForm = document.getElementById('membershipForm');
		//the news pages
		this.articleList = document.getElementById('articleList');
		
		//calculate current Year
		this.thisYear = new Date().getFullYear();
					
		//create global nav
		this.entireSite.createGNav();
		//create contact and copyright info in footer of all pages except for home page (in case JS is not enabled)
		this.entireSite.createFooterDivs();
		//style top divs in leftSide and rightSide divs
		this.entireSite.styleTopDivs();
		//add the text "in [current year]" to text
		this.entireSite.getCurrentYear();
		
		
		//start the fade on the home page
		if(this.thePDiv) {
			//pinpoint existing photo (the first photo to be faded out
			this.oldP = p.thePDiv.getElementsByTagName('img')[0];
			var timer = setTimeout(p.homePageFade.crossFade, 4000);
		}
		
		//print membership form
		if(this.theMemForm) {
			this.memForm.addMemTypeClass();
			this.memForm.addLabelClass();
			this.thePrintCell = document.getElementById('printForm');
			this.thePrintB = this.thePrintCell.getElementsByTagName('input')[0];
			//this.util.addEvent(this.theMemForm,'click',this.memForm.printBlankForm,false);
			this.util.addEvent(this.thePrintB,'click',this.memForm.printForm,false);
		}
		
		//news article pages
		if(this.articleList) {			
			//this.newsArticles = p.newsItems.getElementsByTagName('div');
			//this.allArticles = this.newsArticles.length;
			this.newsPage.createNewsNav();
		}
		
		/*if(this.theNewsletterList) {
			this.colExp.collapseList();
			this.util.addEvent(this.theNewsletterList,'click',this.colExp.expandCollapse,false);
		}*/
		
		//open new smaller winbdow for some images
		this.util.addEvent(this.theBody,'click',this.entireSite.openSmallWindow,false);
		//open separate tab for some links
		this.util.addEvent(this.theBody,'click',this.entireSite.openNewTab,false);
	},
	
	entireSite :  {
	
		createGNav : function() {
		
			//determine current page via path name
			var currentPath = location.pathname;			
			var startName = currentPath.lastIndexOf("/") + 1;
			var thePage = currentPath.substring(startName);
			var pageStart = thePage.substring(0,7);
			//alert(thePage);
		
			var gNavLabels = ['Home','History','News','About Us','Membership','Resources'];
			var gNavLinks = ['index','history','news','about','membership','resources']
			var gNavLength = gNavLabels.length;
			var gNav = document.getElementById('global_nav');
			
			
			for(var n=0; n<gNavLength; n++) {
				//create the li
				var navLi = document.createElement('li');
				//alert('the link is ' + (gNavLinks[n] + '.html'));
				//alert('thePage is ' + thePage);
					
				//if the corresponding link does not match the current page create a link
				if((gNavLinks[n] + '.html') !== thePage) {
					var navA = document.createElement('a');
					navA.href = gNavLinks[n] + '.html';
					navA.appendChild(document.createTextNode(gNavLabels[n]));
					navLi.appendChild(navA);
				}
				
				//if the label does match create the current page label
				else {
					navLi.className = 'current';
					navLi.appendChild(document.createTextNode(gNavLabels[n]));
				}
				gNav.appendChild(navLi);
			}
		
		},
		
		styleTopDivs : function() {
			//identify divs at the top of leftSide and rightSide columns
			var leftSide = document.getElementById('leftSide');
			if(!leftSide) {return;}
			var rightSide = document.getElementById('rightSide');
			var topLeftDiv = leftSide.getElementsByTagName('div')[0];
			var topRightDiv = rightSide.getElementsByTagName('div')[0];
			topLeftDiv.className = topRightDiv.className = 'topOfSide';
			
			/*for(var a=1; a<p.allArticles; a++) {
				p.newsArticles[a].className = ' notFirst';
			}
			//add Back to Top link
			for(var a=0; a<p.allArticles; a++) {
				var topLink = document.createElement('a');
				topLink.href = '#outerContent';
				topLink.appendChild(document.createTextNode('Back to Top'));
				var topLinkP = document.createElement('p');
				topLinkP.className = 'jumpLinks';
				topLinkP.appendChild(topLink);
				p.newsArticles[a].appendChild(topLinkP);
			}*/
		},
	
		openExternalLinks : function(evt) {
			var aLink = p.util.findTarget(evt,'a',this);
			if(!aLink) {return;}
			
			var theHref = aLink.href;
			var linkTo = theHref.substr(0,4);
			if(linkTo === 'http') {
				p.util.stopDefault(evt);
				window.open(aLink,'_blank');
			}
		},
		
		openNewTab : function(evt) {
			var aLink = p.util.findTarget(evt,'a',this);
			if(!aLink) {return;}
						
			if(aLink.className === 'openNewTab') {
				window.open(aLink,'_blank');
			}
		
		},
		
		openSmallWindow : function(evt) {
			var thisLink = p.util.findTarget(evt,'a',this);
			if(!thisLink) {return;}
			
			if(thisLink.className === 'newTab') {
				if(thisLink.parentNode.id === 'largePhotoLink') {
					window.open(thisLink,'_blank','width=1200,height=1400,scrollbars=1');
				}
				if(thisLink.id === 'newsSlides') {
					window.open(thisLink,'_blank','width=1000,height=600,scrollbars=1');
				}
				p.util.stopDefault(evt);
			}
		},
		
		createFooterDivs : function() {
			//home page has all footer info hard-coded so if it exists, stop now
			var bottom_contact = document.getElementById('bottom_contact');
			if(bottom_contact) {return;}
		
			//locate footer
			var footer = document.getElementById('footer');
			
			//create first div
			var div1 = document.createElement('div');
			//array of div1 text
			var div1Contents = ['The North Baltimore, Ohio Area Historical Society, Inc.','229 North Main Street, P.O. Box 174','North Baltimore, Ohio, 45872','(419) 257-2266','Send us an email'];
			//create 5 ps for div 1
			for(var d=0; d<5; d++) {
				var div1P = document.createElement('p');
				if(d === 0){
					var aStrong = document.createElement('strong');
					aStrong.appendChild(document.createTextNode(div1Contents[d]));
					div1P.appendChild(aStrong);
				}
				else if((d>0) && (d<4)) {
					div1P.appendChild(document.createTextNode(div1Contents[d]));
				}
				else{
					div1P.appendChild(document.createTextNode('Email: nbahs@wcnet.org' + ' '));
					var emailLink=document.createElement('a');
					emailLink.href="mailto:nbahs@wcnet.org";
					emailLink.appendChild(document.createTextNode(div1Contents[d]));
					div1P.appendChild(emailLink);
				}
				div1.appendChild(div1P);			
			}
			
			//create second div
			var div2 = document.createElement('div');
			//array of div1 text
			var div2Contents = ['Copyright @',' The North Baltimore, Ohio Area Historical Society, Inc. All Rights Reserved.','Site designed by ','.'];
			//create ps and append
			for(var d=0; d<2; d++) {
				var div2P = document.createElement('p');
				if(d === 0){
					div2P.appendChild(document.createTextNode(div2Contents[0]));
					div2P.appendChild(document.createTextNode(p.thisYear));
					div2P.appendChild(document.createTextNode(div2Contents[1]));
				}
				if(d === 1) {
					div2P.appendChild(document.createTextNode(div2Contents[2]));
					var designerLink = document.createElement('a');
					designerLink.href = 'mailto:cboltz@comcast.net';
					designerLink.appendChild(document.createTextNode('Christine Boltz'));
					div2P.appendChild(designerLink);
					div2P.appendChild(document.createTextNode(div2Contents[3]));					
				}
				div2.appendChild(div2P);
			}
			
			footer.appendChild(div1);	
			footer.appendChild(div2);
		//in first div, insert 5 ps
		//append text to each p
		//in second div, insert 2 ps
		//append texzt to each p
		//use date object to get year
		
		},
		
		getCurrentYear : function() {
		
			var pageSpans = document.getElementsByTagName('span');
			for(var s=0,allSpans=pageSpans.length; s<allSpans; s++) {
				if(pageSpans[s].className === 'thisYear') {	
					pageSpans[s].appendChild(document.createTextNode(' in ' + p.thisYear));
				}
			}
		}
	},
	
	homePageFade : {
		crossFade : function() {
			p.oldCtr = 20;		//opacity counter for photo fading out
			p.newCtr = 0;		//opacity counter for photo fading in
		
			//insert next photo
			p.pCtr++;
			p.newP = document.createElement('img');
			p.newP.id = 'pNum' + p.pCtr;
			p.newP.className = 'op0';
			p.newP.src = 'images/topPhoto' + p.pCtr + '.jpg';
			p.thePDiv.appendChild(p.newP);
			
			//start fade
			p.fadeTimer = setInterval(p.homePageFade.fadeInOut, 50);
		},
	
		fadeInOut : function() {
		
			if(p.oldCtr > 0){
				//fade out old
				var oldOldOp = p.oldCtr;
				var newOldOp = p.oldCtr - 1;
				p.oldP.className = p.oldP.className.replace(oldOldOp,newOldOp);
				p.oldCtr--;
				//fade in new
				var oldNewOp = p.newCtr;
				var newNewOp = p.newCtr + 1;
				p.newP.className = p.newP.className.replace(oldNewOp,newNewOp);
				p.newCtr++;
			}
			else {
				clearInterval(p.fadeTimer);
				p.thePDiv.removeChild(p.thePDiv.getElementsByTagName('img')[0]);
				//start again if there are more photos
				if(p.pCtr < p.allPhotos) {
					var timer = setTimeout(p.homePageFade.crossFade, 4000);
				}
			}
		}
	},
	
	history : {
	
		hideEventDivs : function() {
			for(var x=0,allDivs=p.eachEventDivs.length; x<allDivs; x++) {
				if(p.eachEventDivs[x].id !== 'tlMarker1Events') {
					p.eachEventDivs[x].className = 'hide';
				}
			}
		},
	
		showTimePeriod : function(evt) {
			var theMarker = p.util.findTarget(evt,'a',this);
			if(!theMarker) {return;}
			
			p.util.stopDefault(evt);
			
			//hide any divs previously clicked on
			for(var x=0,allDivs=p.eachEventDivs.length; x<allDivs; x++) {
				if(p.eachEventDivs[x].className === 'show') {
					p.eachEventDivs[x].className = 'hide';
				}
			}
			
			//show this events div
			var thisEventsDiv = document.getElementById(theMarker.id + 'Events');
			thisEventsDiv.className = 'show';
		},
	
		showSlideshow : function(evt) {
			var slideshowLink = p.util.findTarget(evt,'a',this);
			p.util.stopDefault(evt);
			var theSlide = slideshowLink.href;
			window.open(theSlide,'_blank','height=400,width=600,left=200,top=100,menubar=1,toolbar=1');
			//p.history.showSlide();
		},
		
		hideDivs : function() {
			var thePhotoDivs = p.slideshowPhoto.getElementsByTagName('div');
			for(var p=0,allDivs=thePhotoDivs.length; p<allDivs; p++) {
				thePhotoDivs[p].className = 'hide';
			}
		}
	},
	
	colExp : {
	
		collapseList : function() {
			var theLinks = p.theNewsletterList.getElementsByTagName('a');
			for(var v=0,allLinks=theLinks.length; v<allLinks; v++) {
				var theLI = theLinks[v].parentNode;
				theLI.className = 'collapsed';
				var theTopicList = theLI.getElementsByTagName('ul')[0];
				theTopicList.className = 'hide';
			}
		},
	
		expandCollapse : function(evt) {
			var theItem = p.util.findTarget(evt,'li',this);
			if(!theItem) {return;}
			if(theItem.parentNode === p.theNewsletterList) {
				var theTopicList = theItem.getElementsByTagName('ul')[0];
				if(theItem.className === 'collapsed') {
					theItem.className = 'expanded';
					theTopicList.className = '';
				}
				else {
					theItem.className = 'collapsed';
					theTopicList.className = 'hide';
				}
				theItem.stopBubble(evt);
			}
		}
	},
	
	memForm : {
	
		addMemTypeClass : function() {
			var theMemTypes = document.getElementById('memDues');
			var theCells = theMemTypes.getElementsByTagName('td');
			for(var q=0,allCells=theCells.length; q<allCells; q=(q + 2)) {
				theCells[q].className = 'memType';
			}
		},
		
		addLabelClass : function() {		
			var theCells = p.theMemForm.getElementsByTagName('td');
			for(var q=0,allCells=theCells.length; q<allCells; q=(q + 2)) {
				theCells[q].className = 'labelCell';
			}
		},
		
		printBlankForm : function(evt) {
			var printBlank = this.util.findTarget(evt,'a',this);
			if(!printBlank) {return;}
			alert(printBlank.href);	
			p.util.stopDefault(evt);	
		},
		
		printForm : function() {
			//p.memForm.completeTypeField();
			//p.memForm.completePrefField();
			print();
		},
		
		completeTypeField : function() {
			//pinpoint what has been selected on mem type dropdown menu
			var theTypesScreen = document.getElementById('memTypeScreen');
			var theTypesPrint = document.getElementById('memTypePrint');
			var theScreenChoices = theTypesScreen.getElementsByTagName('input');
			var thePrintChoices = theTypesPrint.getElementsByTagName('input');
			for(var x=0,allScreenChoices=theScreenChoices.length; x<allScreenChoices; x++) {
				if(theScreenChoices[x].selected === 'true') {
					thePrintChoices[x].checked = 'true';
				}
			}
		},
		
		completePrefField : function() {
			//pinpoint what has been selected on mem type dropdown menu
			var theNLPref = document.getElementById('memNLPrefScreen');
			var thePrefChoices = theNLPref.getElementsByTagName('input');
			for(var s=0,allPrefs=thePrefChoices.length; s<allPrefs; s++) {
					
				if(thePrefChoices[s].checked === true) {
					p.thePrefChosen = thePrefChoices[s].value;
					//alert(thePrefChoices[s].value);
					//alert(p.thePrefChosen);
				}
			}
			
			//apply to the corresponding checkboxes on print form
			var thePrefsPrint = document.getElementById('memNLPrefPrint');
			var thePrefChoices = thePrefsPrint.getElementsByTagName('input');
			for(var t=0,allPrefChoices=thePrefChoices.length; t<allPrefChoices; t++) {
				if(thePrefChoices[t].value === p.thePrefChosen) {
					thePrefChoices[t].checked = 'checked';
				}
				else {
					thePrefChoices[t].checked = '';
				}
			}
		}
		
		
	},
	
	newsPage : {
	
		createNewsNav : function() {
		
			//create div to insert article list into		
			var newsNavDiv = document.createElement('div');
			//create h3
			var artListHdr = document.createElement('h3');
			artListHdr.appendChild(document.createTextNode('News Articles'));		
			//identify article on current page so it is not linked in list		
			var theArticle = document.getElementById('article');
			var theArtH3 = theArticle.getElementsByTagName('h3')[0];
			var theTitle = theArtH3.firstChild.nodeValue;
			//create list		
			var newsNav = document.createElement('ul');
			newsNav.id = 'newsNav';
			var articleTitles = ['Historical Center Decorates for Christmas','Vanished North Baltimore','Help Save Historical Photographs From Destruction'];
			var allArts = articleTitles.length - 1;			
			for(var a=allArts; a>-1; a--) {
				var artLi = document.createElement('li');
				if(articleTitles[a] !== theTitle) {
					var artLink = document.createElement('a');
					artLink.href = 'article' + (a+1) + '.html';
					artLink.appendChild(document.createTextNode(articleTitles[a]));
					artLi.appendChild(artLink);
				}
				else {
					artLi.appendChild(document.createTextNode(articleTitles[a]));
				}
				newsNav.appendChild(artLi);
			}
			//append list to div and div to div
			newsNavDiv.appendChild(artListHdr);
			newsNavDiv.appendChild(newsNav);
			p.articleList.appendChild(newsNavDiv);
			
			//create got news? div
			//create div
			var haveNews = document.createElement('div');
			//create h3
			var haveNewsHdr = document.createElement('h3');
			haveNewsHdr.appendChild(document.createTextNode('Have Some News?'));		
			//create p
			var haveNewsP = document.createElement('p');
			//create email link
			var emailLink = document.createElement('a');
			emailLink.href = 'mailto:nbahs@wcnet.org';
			emailLink.appendChild(document.createTextNode('email us'));
			//append email link to p
			haveNewsP.appendChild(document.createTextNode('If you have any history-related news or announcements, '));
			haveNewsP.appendChild(emailLink);
			haveNewsP.appendChild(document.createTextNode(' at nbahs@wcnet.org or call (419) 257-2266.'));
			//append to div
			haveNews.appendChild(haveNewsHdr);
			haveNews.appendChild(haveNewsP);
			p.articleList.appendChild(haveNews);
			
		}
	}
	
			
}; //end of meta

p.init();