// JavaScript Document

var xhr = false;
var menuInterval;

window.addEvent("domready", function() {
	def.init();
	//cl.checkURL();
	//ms.init();
	//ad.init();
});
window.onload = function(){
	if(location.hash == "#contact"){
		//menuInterval = setInterval(openContact, 10);
	}
}
window.onunload = function() {};

// default functions
def={
	init:function(){
		if($('mainNav')){ mn.init(); }
		//if($('projectnav')){ pn.init(); }
		//if($('wallwrap')){ wall.init(); }
		//if($('fbgwrap')){ fbg.init(); }
		//if($('contentlinks')){ pj.init(); }
	}
}

// main nav
mn={
	init:function(){
		mn.setLinks();
		mn.setToggle();
		mn.reveal();
		mn.checkURL();
	},
	setLinks:function(){
		$('mainNav').getElements('a').each(function(element){
			element.addEvent('click',function(){
				var href = this.get('href');
				if(href.indexOf('#') > -1){
					if(href.split('#')[1].length == 0){
						return false;
					}else if(href.split('#')[1].length > 0){
						//alert('internal');
						//var file = href.split('#')[1]+"content.php";
						var url = "";
						if(href.split('#')[1].indexOf('id') > -1){
							url = 'projectcontent.php?'+href.split('#')[1];
						}else{
							url = href.split('#')[1]+'content.php';
						}
						//alert(url);
						mn.setCurrent(href.split('#')[1]);
						rq.request($('pageContent'),url);
					}
				}
			});
		});
	},
	setToggle:function(){
		mn.accordion = new Accordion('a.t1', 'ul.subNav', {
			start:'all-closed',
			opacity: false,
			duration: 300, /* default 500 */
			transition: Fx.Transitions.Quint.easeOut,
			alwaysHide: true,
			onActive: function(togglers, stretchers){
				/*togglers.setStyle('background-color', '#B8252E');*/
				/*togglers.setStyle('margin-bottom', '7px');*/
			},
			onComplete: function(){
				$$('ul.subNavProjects').setStyle('height','0'); //This closes all sub-accordions.
			},
			onBackground: function(togglers, stretchers){
				/*togglers.setStyle('background-color', '#333');*/
				/*togglers.setStyle('background-color', '#6699cc');*/
				stretchers.setStyle('height', stretchers.offsetHeight);
			}
		}, $('mainNav'));
		mn.accordion1 = new Accordion('a.t2', 'ul.subNavProjects', {
			start:'all-closed',
			opacity: false,
			duration: 300,
			transition: Fx.Transitions.Quint.easeOut,
			alwaysHide: true,
			onActive: function(togglers, stretchers){
				togglers.getParent().getParent().setStyle("height", "auto");
			},
			onBackground: function(togglers, stretchers){
				stretchers.setStyle('height',stretchers.offsetHeight);
			}
		}, $('mainNav'));
	},
	reveal:function(){
		$('mainNav').getElements('ul').each(function(element){
			if(element.hasClass('hideMe')){
				element.removeClass('hideMe');
			}
		});
	},
	checkURL:function(){
		// is hash already set?
		var curURL = window.location.hash;
		if(curURL.indexOf('#') > -1){
			// set menu
			mn.setCurrent(curURL.split('#')[1]);
			// load content
			var url = "";
			if(curURL.split('#')[1].indexOf('id') > -1){
				url = 'projectcontent.php?'+curURL.split('#')[1];
			}else{
				url = curURL.split('#')[1]+'content.php';
			}
			//alert(url);
			if(curURL.split('#')[1] == "contact"){
				mn.accordion.display(4);
			}
			rq.request($('pageContent'),url);
		}else{
			rq.request($('pageContent'),'indexcontent.php');
		}
	},
	setCurrent:function(hashVar){
		//alert(hashVar);
		$$('.t1').each(function(element){
			if(element.hasClass('currentNav')){
				element.removeClass('currentNav');
			}
		});
		if(hashVar.indexOf('=') > -1){
			hashVar = hashVar.split('=')[0];
		}else if(hashVar.indexOf('about_') > -1){
			hashVar = 'about';
		}
		switch(hashVar){
			case 'id':
			case 'showreel':
				$('navWork').addClass('currentNav');
				break;
			case 'about':
				$('navAbout').addClass('currentNav');
				break;
			case 'news':
				$('navNews').addClass('currentNav');
				break;
			case 'press':
				$('navPress').addClass('currentNav');
				break;
			case 'contact':
				$('navContact').addClass('currentNav');
				break;
			default:
				break;
		}
	}
}

// content load
cl={
	init:function(){
		if($('showcaseList')) cl.setShowcase();
		if($('pressGalList')) cl.setPress();
		if($('projectInfo')) cl.setProjectInfo();
		if($('newsSlider')) cl.setNewsSlider();
		if($('showreel')) cl.setShowreelMovie();
		if($('people')) cl.setPeopleReveal();
		cl.initContentLinks();
	},
	setShowcase:function(){
		cl.showcaseList = $('showcaseList');
		cl.showcaseImages = cl.showcaseList.getElements("li");
		cl.showcaseCount = cl.showcaseImages.length;
		cl.showcaserLink = $('homeImage');
		cl.showcaserImg = $('homeImage').getElements("img")[0];
		//checkMe(cl.showcaseImages.length);
		cl.counter = 0;
		cl.showcaseInterval = setInterval(cl.showcaseChange, 4000);
		
	},
	showcaseChange:function(){
		cl.counter++;
		if(!cl.showcaseImages[cl.counter]){
			cl.counter=0;
		}
		cl.showcaseImg = cl.showcaseImages[cl.counter].getElements('img')[0];
		cl.showcaseSpan = cl.showcaseImages[cl.counter].getElements('span')[0];
		//cl.newSrc = cl.showcaseImg.get('src');
		cl.newSrc = cl.showcaseImages[cl.counter].getElement('.src').get('text');
		//cl.newId = cl.showcaseSpan.firstChild.nodeValue;
		cl.newId = cl.showcaseImages[cl.counter].getElement('.idRef').get('text');
		cl.showcaserImg.set('src', cl.newSrc);
		cl.showcaserLink.set('href', ("#id="+cl.newId));
		
		// load next image
		var myImages = Asset.images(cl.showcaseImages[cl.counter+1].getElement('.src').get('text'), {
			properties: {
				//'class': 'myImage',
				//title: 'myImage'
			},
			onProgress: function(counter, index, source){ 
				//var curString = db.get();
				//curString += gv.galLinkImgs[index]+"<br/>";
				//db.display(curString);
			},
			onComplete: function(){
				//alert('All images loaded!');
			}
		});
	},
	setPress:function(){
		cl.pressList = $('pressGalList');
		cl.pressImages = cl.pressList.getElements('li');
		cl.pressCount = cl.pressImages.length;
		cl.pressImage = $('pressImage');
		//checkMe(cl.showcaseImages.length);
		cl.counter = 0;
		cl.pressInterval = setInterval(cl.pressChange, 6000);
	},
	pressChange:function(){
		cl.counter++;
		if(!cl.pressImages[cl.counter]){
			cl.counter=0;
		}
		cl.pressImg = cl.pressImages[cl.counter].getElements('img')[0];
		cl.newSrc = cl.pressImg.get('src');
		$('pressImage').set('src', cl.newSrc);
	},
	setProjectInfo:function(){
		cl.projInfoAccordion = new Accordion('a.infoBT', 'div.infoList', {
			start:'all-closed',
			opacity: false,
			duration: 300, /* default 500 */
			transition: Fx.Transitions.Quint.easeOut,
			alwaysHide: true,
			onActive: function(togglers, stretchers){
				/*togglers.setStyle('background-color', '#B8252E');*/
				/*togglers.setStyle('margin-bottom', '7px');*/
			},
			onComplete: function(){
				//This closes all sub-accordions.
			},
			onBackground: function(togglers, stretchers){
				/*togglers.setStyle('background-color', '#333');*/
				/*togglers.setStyle('background-color', '#6699cc');*/
				stretchers.setStyle('height', stretchers.offsetHeight);
			}
		},$('projectInfo'));
		$('infoBlock').removeClass('hideMe');
	},
	setNewsSlider:function(){
		cl.newsSliderBar = $('newsSlider');
		cl.newsFrame = $('newsBox');
		cl.newsBox = $('newsBox');
		cl.newsHeight = Number(cl.newsBox.offsetHeight);
		//checkMe("news = "+cl.newsHeight+"\nframe = 534");
		cl.slideAmount = cl.newsHeight - 534;
		cl.scrollAmount = cl.slideAmount / 50;
		if(cl.newsHeight <= (534+"px")){
			cl.newsSliderBar.setStyle('display','none');
			return false;
		};
		cl.newsSlider = new Slider($('slideArea'), $('slideHandle'), {	
			steps: cl.slideAmount,	
			mode: 'vertical',
			onChange: function(step){
				cl.newsBox.style.top = -step+"px";
			}
		}).set(0);
		$('downPage').addEvent('mousedown',function(){
			cl.slidePageDown();
			cl.scrollDown();
			return false;
		});
		$('upPage').addEvent('mousedown',function(){
			cl.slidePageUp();
			cl.scrollUp();
			return false;
		});
		document.addEvent('mouseup',function(){
			cl.stopScroll();
		});
	},
	scrollDown:function(){
		cl.movePageDown = setInterval(cl.slidePageDown, 10);
	},
	scrollUp:function(){
		cl.movePageUp = setInterval(cl.slidePageUp, 10);
	},
	slidePageDown:function(){
		cl.newsSlider.set(cl.newsSlider.step+cl.scrollAmount);
	},
	slidePageUp:function(){
		cl.newsSlider.set(cl.newsSlider.step-cl.scrollAmount);
	},
	stopScroll:function(){
		if(cl.movePageUp){
			clearInterval(cl.movePageUp);
			cl.movePageUp = null;
		}
		if(cl.movePageDown){
			clearInterval(cl.movePageDown);
			cl.movePageDown = null;
		}
	},
	setShowreelMovie:function(){
		cl.movieLink = $('showreel');
		cl.movieHref = cl.movieLink.get('href');
		cl.directoryIndex = cl.movieHref.lastIndexOf("/");
		cl.movieName = cl.movieHref.substring(cl.directoryIndex+1);
		mp.loadFlash(cl.movieName);
		mp.checkFlashLoaded();
	},
	setPeopleReveal:function(){
		$('people').getElements('.nametitle').each(function(element){
			
			var thisHeight = parseInt(element.getStyle('height'))+ 10;
			var thisTween = new Fx.Tween(element,{
				fps: 50,
				transition: 'sine:in:out',
				duration: 200,
				link:'chain'
			});
			thisTween.set('bottom','-'+thisHeight);
			element.getParent().addEvent('mouseenter',function(){
				thisTween.start('bottom','0');
			});
			element.getParent().addEvent('mouseleave',function(){
				thisTween.start('bottom','-'+thisHeight);
			});
			element.removeClass('invisible');
		});
	},
	initContentLinks:function(){
		// internal links
		$('pageContent').getElements('a').each(function(element){
			element.addEvent('click',function(){
				var href = this.get('href');
				if(href.indexOf('#') != -1){
					if(href.split('#')[1].length > 0){
					
						//alert('internal');
						//var file = href.split('#')[1]+"content.php";
						var url = "";
						if(href.split('#')[1].indexOf('id') > -1){
							url = 'projectcontent.php?'+href.split('#')[1];
						}else{
							url = href.split('#')[1]+'content.php';
						}
						//alert(url);
						mn.setCurrent(href.split('#')[1]);
						rq.request($('pageContent'),url);
					}else{
						return false;
					}
				}else if(this.get('id') == 'movieLink'){
					cl.movieHref = href;
					cl.directoryIndex = cl.movieHref.lastIndexOf("/");
					cl.movieName = cl.movieHref.substring(cl.directoryIndex+1);
					mp.loadFlash(cl.movieName);
					mp.checkFlashLoaded();
					return false;
				}
			});
			
		});
		// comments
		if($('comments')){
			var mySlide = new Fx.Slide($('commentContent'),{
				'wait' : false
			}).hide();
			var commentsState = 'closed';
			var origTitle = $('commentTitle').get('text');
			$('commentTitle').addEvent('click',function(){
				if(commentsState == 'closed'){
					if(origTitle != 'Leave A Comment'){
						$('commentTitle').set('text','Hide Comments');
					}
					commentsState = 'open';
					mySlide.slideIn();
				}else{
					$('commentTitle').set('text',origTitle);
					commentsState = 'closed';
					mySlide.slideOut();
				}
			});
			$('commentForm').addEvent('submit',function(evt){
				new Event(evt).stop();
				var formValid = true;
				if($('fName').value.length > 0){
					if($('fBody').value.length > 0){
						// check doesn't contain malicious code
						//
						//
						formValid = true
					}else{
						formValid = false;
						alert('Please enter a comment');
						$('fBody').getParent().getElement('.label').addClass('reqd');
					}
				}else{
					formValid = false;
					alert('Please enter a name');
					$('fName').getParent().getElement('.label').addClass('reqd');
				}
				if(formValid){
					var req = new Request({
						method: 'post',
						data: {
							'name' : $('fName').value,
							'body' : $('fBody').value,
							'project_id' : $('fProjId').value,
							'submitThis' : "submit"
						},
						url: this.get('action'),
						onRequest: function() {
							//alert('Request made. Please wait...');
						},
						onComplete: function(response) {
							$('commentFormWrap').set('html',response);
						}
					}).send();
				}
			});
		}
	}
}

// movie player
mp={
	loadFlash:function(movieName){
		var so = new SWFObject("assets/projects/movies/movieplayer.swf", "player", "640", "480", "9", "#000000");
		so.addVariable("movieName", movieName); //LOADS IN FLASH
		so.write("projectViewer");
	},
	checkFlashLoaded:function(){
		if($('movieLink')){
			// flash didn't load
			cl.flashUpdateString = "<h2>Flash required</h2>";
			cl.flashUpdateString += "\n<div id=\"flashWarning\">";
			cl.flashUpdateString += "<p>You need to <a href=\"update.html\">update your flash player</a> to view these movies</p>";
			cl.flashUpdateString += "<p>Alternatively, you can view a quicktime of the movie you were trying to watch in a <a href=\""+cl.movieHref +"\" target=\"_blank\">new window</a></p>";
			cl.flashUpdateString += "</div>";
			$('pageContent').innerHTML = cl.flashUpdateString;
		}else{
			// flash loaded	
		}
	}
}

rq={
	init:function(){
		
	},
	request:function(container,requestURL){
		var req = new Request({
			method: 'get',
			//data: { 'request' : '1' },
			url: requestURL,
			onRequest: function() {
				//alert('Request made. Please wait...');
			},
			onComplete: function(response) {
				container.set('html',response);
				cl.init();
			}
		}).send();
	}
}

// debug output
db={
	init:function(){
		var outputHolder = new Element('div',{
			id:'output',
			styles:{
				position:'absolute',
				top:'100px',
				left:'100px',
				background:'#444',
				color:'#FFF',
				'z-index':'300',
				padding:'10px'
			}
		});
		outputHolder.inject(document.body);
	},
	display:function(string){
		if(!$('output')){
			db.init();
		}
		if(string || string == 0){
			$('output').set('html',string);
		}else{
			$('output').set('text','no string set');
		}
	},
	remove:function(){
		if($('output')){
			$('output').dispose();
		}
	}
}
