var Questionnaire = new Class({
	// very basic questionnaire.
	// questions are shown in sequence.
	// answer one question right, and you get shown a 'success' message.
	/// answer all questions wrong, and you are shown a 'fail' message.
	
	Implements: [Options,Events, Chain],
	options: {
		// div containing questions
		'container':null,
		'successMsg':null,
		'failMsg':null,
		'actionLink':null
	},
	log: function(){
		if(console) console.log.apply(null, arguments);
	},
	// this function runs whenever a new instance of this class is made.
	initialize: function(options){ 
		this.setOptions(options);
		
		this.container = document.id(this.options.container);
		//this.log(this.container);
		
		
		this.successMsg = this.options.successMsg;
		this.failMsg = this.options.failMsg;
		this.actionLink = document.id(this.options.actionLink);
		
		//this.log(successDiv);
		
		// get all OL LIs as questions
		var questionList = this.container.getElements('ol li');
		// rem from DOM
		this.container.getElement('ol').dispose();
		
		//remove the existing action button
		if(this.actionLink) {
			this.actionLink.fade('hide');
			this.actionLink = this.actionLink.dispose();
		}
		
		// build separate panes
		this.questionElements = new Array();
		
		questionList.each(function(item, index, array){ 
			//create Yes and No buttons
			var navDiv = new Element('div' );
			var yesButton = new Element('a',{'html':'Yes','href':'javascript:;'});
			var noButton = new Element('a',{'html':'No','href':'javascript:;'});
			
			yesButton.grab(new Element('span'));
			noButton.grab(new Element('span'));
						
			navDiv.addClass('answers');
			yesButton.addClass('button');
			yesButton.addClass('yes');
			
			noButton.addClass('button');
			noButton.addClass('no');
			
			// add click handler
			yesButton.addEvent('click', this.SubmitAnswer.bindWithEvent(this, {'answer': 'yes','index':index}) );
			noButton.addEvent('click', this.SubmitAnswer.bindWithEvent(this, {'answer': 'no','index':index}) );
			
			navDiv.grab(yesButton);
			navDiv.grab(noButton);
			
			
			//create div
			var tempDiv = new Element('div' );
			tempDiv.addClass('question');
			if(index == 0){
				//tempDiv.addClass('active');
			}else{
				tempDiv.fade('hide');
			}
			// create p, with question inside
			var tempP = new Element('p',{'html':item.get('html')} );
			
			// a prologue is a text 'lead-in' to the question.
			// implement it by having a <span class="prologue"> at the start of the list item.
			var prologue = tempP.getElement('span.prologue');
			if(prologue){
				// remove it from the DOM 
				prologue = tempP.getElement('span.prologue').dispose();
				var prologueP = new Element('p',{'class':'prologue','html':prologue.get('html')})
				//this.log(prologue);
				tempDiv.grab(prologueP);
				
			}
			tempDiv.grab(tempP);
			tempDiv.grab(navDiv);
			
			this.questionElements.push( tempDiv  );
			//insert first one into container
			if(index == 0) this.container.grab(tempDiv);
			
		}, this);
		
		//build status 
		this.statusP = new Element('p' ,{'class':'status','html':'Question <strong>1</strong> of ' + this.questionElements.length});
		this.container.grab(this.statusP,'top');
		
		//build success msg
		this.successDiv = new Element('div' ,{'id':'survey-success','html':this.successMsg});
		this.successDiv.fade('hide');
		//this.container.grab(this.successDiv);
		
		
		//build fail msg
		this.failDiv = new Element('div' ,{'id':'survey-fail','html':this.failMsg});
		this.failDiv.fade('hide');
		//this.container.grab(this.failDiv);
		
		
		
		//re insert action link
		//this.container.grab(this.actionLink);
		//this.actionLink = this.container.getElementById(this.options.actionLink);
		
		// add hero img
		var heroImg = new Element('div' ,{'id':'survey-hero'});
		this.container.grab(heroImg);

	},
	
	SubmitAnswer:function(event,paramArray){
		// runs when you click an answer button
		//this.log(paramArray);
		
		if(paramArray['answer'] == 'no'){
			// move on to the next one
			this.ShowNextQuestion(paramArray);
		}else if (paramArray['answer'] == 'yes'){
			
			//fade out q
			if(this.questionElements[paramArray['index']]) this.questionElements[paramArray['index']].fade('out');
			// show msg
			this.UpdateStatus({'index':this.questionElements.length});
			this.ShowSuccessMessage();
		}
	},
	
	
	
	ShowNextQuestion:function(paramArray){
		// fades out current question, fades in next one
		if(this.questionElements[paramArray['index']]) {
			
			//use chain to link 
			this.chain(function(){this.questionElements[paramArray['index']].fade('out'); this.callChain(); }  );
			//rem current q
			this.chain(function(){this.questionElements[paramArray['index']].dispose(); this.callChain(); }  );
			
			//fade in next
			if(this.questionElements[paramArray['index']+1]){
				// insert next q
				this.chain(function(){this.container.grab(this.questionElements[paramArray['index']+1]); this.callChain();});
				//fade in
				this.chain(function(){this.questionElements[paramArray['index']+1].fade('in'); this.callChain(); }  );	
				
				this.UpdateStatus(paramArray);
						
			}else{
				// no more questions, show fail message
				this.UpdateStatus(paramArray);
				this.chain(function(){this.ShowFailMessage();});
			}
			//begin anim
			this.callChain();
					
		}
	},
	
	UpdateStatus:function(paramArray){
		if(paramArray['index']+2 <= this.questionElements.length){
		
			this.statusP.set({'html':'Question <strong>' + (paramArray['index']+2) + '</strong> of ' + this.questionElements.length});
		}else{
			this.statusP.set({'html':'Survey Complete'});
		}
	},
	
	ShowFailMessage:function(paramArray){
		//hide extraneous content
		//this.prologue = this.container.getElement('p.prologue').dispose();
		
		//close button
		this.closeButton = new Element('p');
		this.closeButton.grab(new Element('a',{'html':'Close Survey<span></span>','href':'javascript:;'}));

		//closeButton.grab(new Element('span'));
		this.closeButton.getElement('a').addClass('button');
		//this.log(closeButton);
		this.closeButton.addEvent('click', window.homeDialogue.fadeInOut.bindWithEvent(window.homeDialogue, {'fadeIn': 'out'}) );
		
		
		this.container.grab(this.failDiv);
		this.container.grab(this.closeButton);
		
		this.failDiv.fade('in');
		
	},
	
	ShowSuccessMessage:function(){
		//hide extraneous content
		//this.prologue = this.container.getElement('p.prologue').dispose();
		//rem current q
		if(this.container.getElement('div.question')) this.container.getElement('div.question').dispose();
		// insert action link
		this.container.grab(this.successDiv);
		this.successDiv.fade('in');
		
		this.container.grab(this.actionLink);
		this.actionLink.fade('in');
		
		//this.container.getElementById('survey-success').fade('in');
	},

	ResetQuestionnaire:function(){
		// resets the questions
		this.questionElements.each(function(item, index, array){
			if(index == 0){
				item.fade('show');
			}else{
				item.fade('hide');
			}
		});
		
		//status
		this.container.getElement('p.status').set({'html':'Question <strong>1</strong> of ' + this.questionElements.length});
		//rem existing q
		if(this.container.getElement('div.question')) this.container.getElement('div.question').dispose();
		
		//this.container.grab(this.prologue);
		
		//add q 1
		this.container.grab(this.questionElements[0]);
		
		
		
		//this.container.getElementById('survey-success').fade('hide');
		if(this.successDiv) this.successDiv=this.successDiv.dispose();
		if(this.failDiv) this.failDiv=this.failDiv.dispose();
		
		if(this.actionLink) this.actionLink = this.actionLink.dispose();
		// rem close button
		if(this.closeButton) this.closeButton = this.closeButton.dispose();
		
	}
	
});

var ModalDialogue = new Class({
	// tabs with content
	// cross fade transition
	Implements: [Options,Events, Chain], 						  
	
	 // menu options. don't put a comma after the last option!
	options: {
	 	// whether to enable the first item. This is generally only true for the home page.
			
			// array of tab elements
			'bg':null,
			// array of content pane elements
			'container':null,
			// button to show dialogue
			'trigger':null
			
		},
	log: function(){
		if(console) console.log.apply(null, arguments);
	}, 
	// this function runs whenever a new instance of this class is made.
	initialize: function(options){ 
		// use the options specified
		
		this.setOptions(options);
		
		this.bg = document.id(this.options.bg);
		
		this.container = document.id(this.options.container);
		this.trigger = document.id(this.options.trigger);
		
		
		
		
		//move bg and container above all other elements
		containerTemp = this.container.dispose();
		containerTemp.inject(document.getElement('div#main-wrap'),'after');
		bgTemp = this.bg.dispose();
		bgTemp.inject(document.getElement('div#main-wrap'),'after');
		
		// prepare appearance
		
		bgTemp.setStyles({
			'opacity':'0',
			'left':'0',
			'top':'0',
			'width': window.getSize().x ,
			'height': window.getSize().y 
			
		});

		
		
		

		containerTemp.setStyles({
			'opacity':'0',
			'left': (document.getSize().x - containerTemp.getSize().x)/2 
			
						
		});
		
		
		// store options for future use
		document.store('mdOptions', this.options);

		// when resizing window, resize bg
		window.addEvent('resize', function(){
			var mdOptions = document.retrieve('mdOptions');
			document.id(mdOptions.bg).setStyles({
				'width': window.getSize().x  ,
				'height': window.getSize().y 
			});
			
			
			document.id(mdOptions.container).setStyles({
				'left': (document.getSize().x - document.id(mdOptions.container).getSize().x)/2 
			});
		
			
		});
		
		
		this.bg = document.id(this.options.bg);
		this.container = document.id(this.options.container);
		
		// create close button. Watch that chain!
		this.container.grab(new Element('p').grab(new Element('a',{'html':'Close Survey','href':'javascript:;','id':'survey-close'})));
		this.closeButton = this.container.getElementById('survey-close');
		//this.log(this.closeButton);
		
		// add clicky event
		this.closeButton.addEvent('click', this.fadeInOut.bindWithEvent(this, {'fadeIn': 'out'}) );
		
		// add event to trigger
		this.trigger.addEvent('click', this.fadeInOut.bindWithEvent(this, {'fadeIn': 'in'}) );
		//this.trigger.addEvent('click',function(){alert('p')});
		
		//this.fadeInOut();
	},
	
	fadeInOut:function(event,paramArray){
		//fade in or out bg
		
		
		if(paramArray['fadeIn'] == 'in'){
			this.container.setStyles({'left': (document.getSize().x - containerTemp.getSize().x)/2});
			//turn off cover tab periodical
			
			if(window.homeCoverTabs) window.homeCoverTabs.StopPeriodical();
			// reset the questionnaire
			
			
		}else if(paramArray['fadeIn'] == 'out'){
			this.container.setStyles({'left':-10000});
			//turn on cover tab periodical
			if(window.homeCoverTabs) {
				window.homeCoverTabs.StartPeriodical(10000);
			}
			if(window.homeSurvey) {
				window.homeSurvey.ResetQuestionnaire();
			}
		}
		
		this.bg.fade(paramArray['fadeIn']);
		this.container.fade(paramArray['fadeIn']);
		
	}

});




var TabView = new Class({
	// tabs with content
	// cross fade transition
	Implements: [Options,Events, Chain], 						  
	
	 // menu options. don't put a comma after the last option!
	options: {
	 	// whether to enable the first item. This is generally only true for the home page.
			
			// array of tab elements
			'tabArray':null,
			// array of content pane elements
			'paneArray':null,
			// delay in ms
			'slideDelay': 3000
		}, 
	
	log: function(){
		if(console) console.log.apply(null, arguments);
	},
	// this function runs whenever a new instance of this class is made.
	initialize: function(options){ 
		// use the options specified
		
		this.setOptions(options);
		
		
		
		// Dynamically generate navigation links from promo links
		
		//get all img
		this.tabArray = this.options.tabArray;
		this.paneArray = this.options.paneArray;
		this.delayms = this.options.slideDelay;
		
		this.currentTab = 0;
		
		this.totalTabs =  this.tabArray.length;
		
		// load each tab with onclick function
		//add clicky event. http://mootools.net/docs/core/Native/Function/#Function:bindWithEvent
		// basically click a tab and it shows the corresponding content pane
		this.tabArray.each(function(item,index){item.addEvent('click', this.ShowTab.bindWithEvent(this, {
			'tabIndex': index,
			'clickIsFromUser': true
		}))}, this);
		
		
				
		if(this.totalTabs > 0){
			for(var i=0;i<this.totalTabs;i++){
				
				var pane = this.paneArray[i];
				
				if(i > 0){
					// make all except 1st img transparent
					pane.set('styles',{'display':'block'});
					pane.fade('hide');
					
				}else{
					pane.fade('show');
				}
			}
			
			this.StartPeriodical(this.delayms);
		}
		//$('article-viewport').getElement('div.articles').tween('left',0);
		
	},
	
	ShowTab:function(event,paramArray){
		
		// boolean isNext determines if moving forwards or back
		if(this.currentTab == tabIndex) return false;
		
		if(event) event.stop();
		
		var tabIndex = paramArray['tabIndex'];
		var clickIsFromUser = paramArray['clickIsFromUser'];
		 
		//clear timer
		if(clickIsFromUser) {
		
			$clear(this.periodID);
			
		}else{
			// auto scrolling
			
			tabIndex = this.currentTab+1;
			if(tabIndex > this.tabArray.length-1){
				tabIndex = 0;
			}
		}
		//start timer
		
		//fadeout current pane
		this.paneArray[this.currentTab].fade('out');
		//this.slides[this.currentTab].tween('width',300);
		//fadein next pane
		this.paneArray[tabIndex].fade('in');
		//this.slides[nextImg].tween('width',100);
		
		// deactivate current tab
		this.tabArray[this.currentTab].removeClass('active');
		// activate next tab
		this.tabArray[tabIndex].addClass('active');
		
		// track current tabIndex	
		this.currentTab = tabIndex;

		if(clickIsFromUser) {
			// set timer
			this.periodID = this.StartPeriodical.delay(this.delayms*1.5, this, this.delayms);
			
		}
		

		//return false;
	},
	
	StartPeriodical:function(delayms){
		this.periodID = this.ShowTab.bindWithEvent(this,{'tabIndex':0,'clickIsFromUser':false}).periodical(delayms);
		
	},
	
	StopPeriodical:function(){
		
		$clear(this.periodID);
		
	}
	
	
});

//Auto Gen Table Contents.
function createTOC() {

	//initial vars
	var finders = ['h1','h2','h3','h4','h5','h6'];
	var matches = [];
	var finalMatches=[];
	var backToTopArray = [];
	var anchorArray=[];
	matches = $('main-wrap').getElement('div.text-column').getElements('*');
	
	
	
	matches.each(function(el,i) {
		
		//do we want this? does not include first (H1) heading
		if(i > 0 && finders.contains(el.get('tag')))
		{
			
			finalMatches.include(el);
			
			//create anchor
			var anchor = new Element('a', {
				'class': el.get('tag'),
				'text': el.get('text'),
				'href': 'javascript:;'
			});

			//click event
			anchor.addEvent('click', function() {
				// scroll up to top
				
				
				var go = new Fx.Scroll(window).start(el.getPosition()['x'],el.getPosition()['y']-35);
				
				var backToTop = document.id('footer-wrap').getElement('p.back-to-top');
				//add back to top button
				if(!backToTop){
					var backToTop = new Element('p',{'class': 'back-to-top'}).grab(new Element('a', {
						'text': 'Back to Top',
						'href': 'javascript:;'
					}));
					
					//hide below horizon
					backToTop.setStyle('top',-35);
					//click event
					backToTop.addEvent('click', function() {
						var go = new Fx.Scroll(window).toElement($('main-wrap'));
						// slide up from bottom
						var myFx = new Fx.Tween(this);
						myFx.start('top',-35);
						
					});
					
					document.id('footer-wrap').grab(backToTop);
					
				}
					
				
				var myFx = new Fx.Tween(backToTop);
				// slide up from bottom
				myFx.start('top',0);
				
			});
			
			//add into our matches array
			anchorArray.include(anchor);
			
			
		}
		
		

	});
		
	//should we show the toc?
	if(anchorArray.length)
	{
		//create toc div, inject
		var toc = new Element('div', {
			'class': 'toc',
			'html': '<h6>Table of Contents</h6>'
		}).inject($('main-wrap').getElement('h1.pagetitle'),'before');

		//inject the matches
		anchorArray.each(function(el) {
			el.inject(toc);
		});
	}

}
