var PageLoader = new Class({
	initialize:function(){
		window.addEvents({
			domready:function(){this.createInterface();}.bind(this)
		});
	},
	createInterface:function() {
		if (document.id('portfolio')) {
			this.enabled = true;
			this.current = null;
			this.portfolio = document.id('portfolio');
			this.portfolioitem = new Array();
			this.createCaseStudies();
			this.bodyscroller = new Fx.Scroll(document.body,{wheelStops:false});
		}
		this.createmenueffect(document.id('portfolio') != null);
		this.createcontacteffect(document.id('footer'));
	},
	setEnabled:function(enabled){this.enabled = enabled;},
	getEnabled:function() {return this.enabled;},
	
	createCaseStudies:function(){
		this.caseStudies = new CaseStudies(this,{
			onHide:function(){
				if (this.current != null) this.current.getElement('img').tween('border-color','#fff');
				this.current = null;
			}.bind(this),
			onShow:function(old,current) {
				if (old != null) this.portfolioitem[old].getElement('img').tween('border-color','#fff');
				this.current = this.portfolioitem[current];
				this.current.getElement('img').tween('border-color','#f4e038');				
			}.bind(this)
		});
		document.id(this.caseStudies).inject(this.portfolio,'before');
		this.portfolioitem = this.portfolio.getElements('li li');
		this.portfolioitem.each(function(e,i){
			var mystring = e.getElement('img').get('src').replace('/thumb.jpg','');
			this.caseStudies.addCase(mystring.substr(mystring.indexOf('/portfolio/')),this.getData(e));
			e.set({
				styles:{cursor:'pointer'},
				events:{
					click:function(event){
						event.stop();
						if (this.getEnabled()) {
							this.setEnabled(false);
							this.bodyscroller.toTop();
							if (this.current != e && this.current != null) this.current.getElement('img').tween('border-color','#fff');
							this.current = e;
							this.current.getElement('img').tween('border-color','#f4e038');
							this.caseStudies.showCase(i);
						}
					}.bind(this),
					mouseenter:function(event){event.stop();if (this.getEnabled() && this.current != e) e.getElement('img').tween('border-color','#f4e038');}.bind(this),
					mouseleave:function(event){event.stop();if (this.current != e) e.getElement('img').tween('border-color','#fff');}.bind(this)
				}
			});
		}.bind(this));
	},
	getData:function(e) {
		var data = new Array();
		if (e.getElement('p.brand')) {
			data.push(e.getElement('p.brand').clone());
			e.getElement('p.brand').setStyle('cursor','pointer');
		}
		if (e.getElement('div')) data.push(e.getElement('div'));
		if (e.getElement('a') != null) {
			var myLink = e.getElement('a').clone().empty();
			data.push(myLink.set('text',myLink.get('href').substring(7)));
		}
		return data;
	},
	createmenueffect:function(portfolioPage){
		this.nav = document.id('nav').addEvent('click',function(event){
			event.stop();
			if (!this.mousein) return;
			if (this.nav.getElement('.current.portfolio')) location.href=this.nav.getElement('.profile a').get('href');
			if (this.nav.getElement('.current.profile')) location.href=this.nav.getElement('.portfolio a').get('href');
		}.bind(this));
		this.mousein = false;
		
		var myhover = new DHover(this.nav,{
			onMouseIn:function(){
				if (this.mousein) return;
				this.mousein = true;
				this.nav.setStyle('cursor','pointer');
				this.hovers.each(function(e){e[0].get('tween').pause();});
				portfolioPage ? this.hovers[0][0].tween('width',this.hovers[0][1].getStyle('width')) : 	this.hovers[0][0].tween('height',this.hovers[0][1].getStyle('height'));
			}.bind(this),
			onMouseOut:function(){
				if (!this.mousein) return;
				this.mousein = false;
				this.nav.setStyle('cursor','default');
				this.hovers.each(function(e){e[0].get('tween').pause();});
				portfolioPage ? this.hovers[2][0].tween('left',551) : this.hovers[1][0].tween('width',0);			
			}.bind(this)			
		});
		if (portfolioPage) {
			myhover.addConvexQuad({x:154,y:16},{x:135,y:0},{x:90,y:0},{x:113,y:21});
			myhover.addConvexQuad({x:205,y:47},{x:200,y:43},{x:148,y:49},{x:179,y:76});
			myhover.addConvexQuad({x:549,y:49},{x:204,y:48},{x:181,y:75},{x:435,y:108});
			myhover.addConvexQuad({x:549,y:49},{x:425,y:113},{x:424,y:161},{x:534,y:121});
		} else {
			myhover.addConvexQuad({x:63,y:0},{x:37,y:0},{x:2,y:48},{x:17,y:62});
			myhover.addConvexQuad({x:599,y:0},{x:278,y:0},{x:13,y:34},{x:16,y:62});
		}
		this.createHoverElements(portfolioPage);
		myhover.start();
	},
	createHoverElements:function(portfolioPage) {
		var myImage = 'transparent url(/img/hover.jpg) 0 0 no-repeat';
		var mydimensions = portfolioPage ?	[[90,0,114,80,'-369px -64px'],[181,48,368,61,'0 -64px'],[425,48,125,118,'-586px 0']]  : [[2,0,62,63,'-485px -64px'],[16,0,585,63,'0 0']];
		this.hovers = new Array();
		var max = portfolioPage ? 3 : 2;
		for (i=0;i<max;i++) {
			this.hovers[i] = new Array();
			for(j=0;j<2;j++) {
				this.hovers[i][j] = new Element('span',{
					styles:{position:'absolute',overflow:'hidden',background:j == 1 ? myImage : 'none',	'background-position': mydimensions[i][4],
						left:j == 0 ? mydimensions[i][0] : 0,
						top:j == 0 ? mydimensions[i][1] : 0,
						width:j == 0 ? 0 : mydimensions[i][2],
						height:!portfolioPage && i == 0 && j == 0 ? 0 : mydimensions[i][3]
					},
					tween:{duration:50,transition:Fx.Transitions.Linear}
				}).inject(j == 0 ? this.nav : this.hovers[i][0]);
			}
		}
		if (portfolioPage) {
			this.hovers[2][0].setStyles({left:550,width:'auto',right:52});
			this.hovers[2][1].setStyles({left:'auto',right:0});
		} else {
			this.hovers[0][0].setStyle('width',mydimensions[0][2]);
		}
		this.hovers.each(function(e,i){
			e[0].set('tween',{
				onComplete:function() {
					if (this.mousein) {
						if (portfolioPage) {							
							if (i == 0) this.hovers[1][0].tween('width',this.hovers[1][1].getStyle('width'));
							if (i == 1) this.hovers[2][0].tween('left',mydimensions[2][0]);				
						} else {
							if (i == 0) this.hovers[1][0].tween('width',this.hovers[1][1].getStyle('width'));							
						} 
					} else {
						if ((i == 2 || i == 1) && portfolioPage) this.hovers[i-1][0].tween('width',0);
						if (!portfolioPage && i == 1) this.hovers[0][0].tween('height',0);							
					}
				}.bind(this)}
			);
		}.bind(this));
	},
	createcontacteffect:function(footer) {
		footer.getElement('.contact a').set({
			styles:{'color':'#fff'},
			events:{
				mouseenter:function(){this.tween('color','#ecce38');},
				mouseleave:function(){this.tween('color','#fff');}
			}
		});
		footer.getElements('.copy a').each(function(e){
			e.addEvents({
				mouseenter:function() {this.tween('color','#d77355');},
				mouseleave:function() {this.tween('color','#76706a');}
			});
		});
	}
});

var CaseStudies = new Class({
	Implements:[Events,Options],
	options:{
		//onHide:$empty,
		//onShow:$empty,
		debug:false,
		nodisplay:true,
		baseclass:'casestudies'
	},
	cases:[],
	initialize:function(parent,options) {
		this.setOptions(options);
		if (this.options.debug && !this.validate(parent)) return;	
		this.parent = parent;
		this.current = null;
		this.old = null;
		this.size = null;
		this.height = null;
		this.createInterface();
		return this;
	},
	validate:function(parent){
		if (parent == null) {alert('CaseStudies: parent instance does not exists');return false;}
		return true;
	},
	createInterface:function() {
		this.base = new Element('div',{id:this.options.baseclass,tween:{onComplete:function(){this.completed();}.bind(this)}});
		if (this.options.nodisplay) this.base.setStyle('display','none');
		this.inner = new Element('div',{styles:{overflow:'hidden'}}).inject(this.base);
		this.list = new Element('ul').inject(this.inner);
		this.scroller = new Fx.Scroll(this.inner,{wheelStops:false});
		var controls = new Element('div',{'class':'casecontrols'}).inject(this.base);
		new Element('a',{'class':'next',href:'/nextcase',events:{
			click:function(event){event.stop();if (this.getEnabled()) this.nextCase();}.bind(this),
			mouseenter:function(){this.tween('background-color','#fee150');},
			mouseleave:function(){this.tween('background-color','#f6f6f5');}
		}}).setStyle('background-color','#f6f6f5').inject(controls);
		new Element('a',{'class':'prev',href:'/previouscase',events:{
			click:function(event){event.stop();if (this.getEnabled()) this.prevCase();}.bind(this),
			mouseenter:function(){this.tween('background-color','#fee150');},
			mouseleave:function(){this.tween('background-color','#f6f6f5');}
		}}).setStyle('background-color','#f6f6f5').inject(controls);
		var close = new Element('a',{'class':'close',href:'/close',events:{
			click:function(event){event.stop();if (this.getEnabled()) this.hide();}.bind(this)
		}}).inject(this.base,'top');
		var closespan = new Element('span',{styles:{opacity:0},events:{
			mouseenter:function(){this.tween('opacity',1);},
			mouseleave:function(){this.tween('opacity',0);}
		}}).inject(close);
		this.prevslide = new Element('a',{'class':'slideprev',href:'/previous slide',styles:{position:'absolute',opacity:0,'z-index':9999,cursor:'pointer'},events:{
			mouseenter:function(){this.tween('opacity',1);},
			mouseleave:function(){this.tween('opacity',0);},
			click:function(event){event.stop();if (this.current != null) this.cases[this.current].prevslide();}.bind(this)
		}});	
		this.nextslide = new Element('a',{'class':'slidenext',href:'/next slide',styles:{position:'absolute',opacity:0,'z-index':9999,cursor:'pointer'},events:{
			mouseenter:function(){this.tween('opacity',1);},
			mouseleave:function(){this.tween('opacity',0);},
			click:function(event){event.stop();if (this.current != null) this.cases[this.current].nextslide();}.bind(this)
		}});	
	},
	toElement:function() {return this.base;},
	setEnabled:function(enabled){this.parent.setEnabled(enabled);},
	getEnabled:function(){return this.parent.getEnabled();},
	completed:function() {
		if (this.base.getStyle('height').toInt() == 0) {
			this.base.setStyles({display:'none',height:this.height});
			this.setEnabled(true);
		} else {
			this.scroller.toElement(this.cases[this.current].show());
			this.fireEvent('onShow',[this.old, this.current]);
		}
	},
 	show:function() {
		if (this.base.getStyle('display') == 'none') {
			if (this.height == null) this.height  = this.base.measure(function(){return this.getSize().y;});
			this.base.setStyles({display:'block',height:0});
			this.base.tween('height',this.height);
		} else {
			this.scroller.toElement(this.cases[this.current].show());
			this.fireEvent('onShow',[this.old, this.current]);
		}
		return this;
	},
	hide:function() {
		this.setEnabled(false);
		if (this.current != null) this.cases[this.current].clean();
		this.current = null;
		this.base.tween('height',0);
		this.fireEvent('onHide');
	},
	getSize:function() {return this.inner.measure(function(){return this.getSize();});},
	addCase:function(directory,data) {
		var i = this.cases.length;
		this.cases[i] = new CaseStudy(this.parent,this.list,{onShow:function(){
			if (this.old != null) this.cases[this.old].clean();
			document.id(this.cases[this.current]).adopt([this.nextslide,this.prevslide]);
		}.bind(this)}).setSlideDirectory(directory);
		var mySize = this.getSize();
		document.id(this.cases[i]).setStyles({float:'left',width:mySize.x});
		this.list.setStyle('width',(i+1)*mySize.x);
		if (data != null && data.length > 0) data.each(function(e){this.cases[i].addData(e);}.bind(this));	
		return this;
	},
	nextCase:function() {
		this.setEnabled(false);
		return this.showCase(this.current == this.cases.length-1 ? 0 : this.current+1);
	},	
	prevCase:function() {
		this.setEnabled(false);
		return this.showCase(this.current == 0 ? this.cases.length-1 : this.current -1);
	},
	showCase:function(i) {
		if (this.current == i) {
			this.setEnabled(true);
		} else {
			this.setEnabled(false);
			this.old = this.current;
			this.current = i;
			this.show();
		}		
		return this;
	}
});

var CaseStudy = new Class({
	Implements:[Events,Options],
	
	options:{
		//onShow:$empty,
		debug:false,
		delay:4000,
		url:'/inc/slideshow.php'
	},	
	slides:[],
	initialize:function(owner,parent,options) {
		this.setOptions(options);
		if (this.options.debug && !this.validate(owner,parent)) return;
		this.parent = document.id(parent);
		this.owner = owner;
		this.request = new Request({url:this.options.url,async:false,noCache:true,onSuccess:function(res){if (res != '') this.slidelist = res.split(';');this.loadSlides();}.bind(this)});
		this.slidelist = new Array();
		this.control = new Array();
		this.directory = null;
		this.link = null;
		this.slideselected = -1;
		this.createInterface();
		return this;
	},
	validate:function(owner,parent) {
		var test1 = document.id(parent);
		if (test1 == null || !test1.match('ul')) {alert('CaseStudy: parent ul element does not exist');return false;}
		if (owner == null) {alert('CaseStudy: owner instance does not exists');return false;}
		return true;
	},
	createInterface:function() {
		this.base = new Element('li',{styles:{overflow:'hidden',float:'left',width:this.parent.getWidth()}}).inject(this.parent);
		this.slidebase = new Element('div',{'class':'slides'}).inject(this.base);
		this.slideSize = this.slidebase.measure(function(){return this.getSize();});
		this.slidesinner = new Element('ul',{styles:{height:this.slideSize.y,width:this.slideSize.x}}).inject(this.slidebase);
		this.slidescroller = new Fx.Scroll(this.slidebase,{wheelStops:false,onComplete:function(){this.scrollComplete();}.bind(this)});
		this.data = new Element('div',{'class':'data'}).inject(this.base);
		this.controls = new Element('ul',{'class':'controls'}).inject(this.data);
	},
	toElement:function() {return this.base;},
	setEnabled:function(enabled){this.owner.setEnabled(enabled);},
	addData:function(el) {
		if (this.options.debug && document.id(el) == null) {alert('CaseStudy: data element does not exists');return this;}
		if (el.match('a')) this.link = el.addClass('casestudylink').addEvent('click',function(event){event.stop();window.open(this.get('href'));});
		this.controls.grab(el,el.match('a') ? 'after' : 'before');
		return this;
	},
	setSlideDirectory:function(directory) {this.directory = directory;return this;},
	show:function() {
		this.setEnabled(false);
		this.slidelist.length == 0 && this.directory != null ?  this.request.send('directory='+this.directory) : this.loadSlides();
		return this;
	},	
	loadSlides:function() {
		if (this.slidelist.length > 0) {
			var list = new Asset.images(this.slidelist,{
				onComplete:function() {
					clearInterval(this.timer);
					this.slidesinner.setStyle('width',(list.length+2)*this.slideSize.x);
					this.slidescroller.set(this.slideSize.x);
					this.slideselected = 0;
					list.each(function(e,i){
						this.slides[i] = new Element('li',{styles:{float:'left',width:this.slideSize.x,height:this.slideSize.y}}).inject(this.slidesinner);
						e.inject(this.slides[i]);
						this.control[i] = new Element('li',{text:i+1,styles:{float:'left',cursor:'pointer'},events:{click:function(){
							this.slidebase.setStyle('opacity',0.99);/*to make chrome repaint properly*/
							this.showslide(i);
							this.slidebase.setStyle('opacity',1);/*to make chrome repaint properly*/
						}.bind(this)}}).inject(this.controls);
					}.bind(this));		
					this.slides[0].grab(this.slides[this.slides.length-1].clone(),'before');
					this.slides[this.slides.length-1].grab(this.slides[0].clone(),'after');
					this.slidescroller.toElement(this.slides[this.slideselected]);
					this.control[this.slideselected].addClass('selected');
					this.setEnabled(true);
					this.fireEvent('onShow');
				}.bind(this)
			});
		} else {
			this.setEnabled(true);
			this.fireEvent('onShow');
		}
		return this;
	},
	clean:function() {
		clearInterval(this.timer);
		this.slides.each(function(e){e.empty().destroy();});
		this.slidesinner.getElements('li').each(function(e){e.empty().destroy();});
		this.controls.getElements('li').each(function(e){e.empty().destroy();});
	},	
	showslide:function(i) {
		if (i == this.slideselected) return;
		var old = this.slideselected;
		this.slideselected = i;
		this.control[old].removeClass('selected');		
		this.control[this.slideselected].addClass('selected');
		if (old == this.slides.length-1 && this.slideselected == 0) {
			this.slidescroller.start((this.slides.length+1)*this.slidebase.getSize().x,0);
		} else if (old == 0 && this.slideselected == this.slides.length-1 && this.slides.length != 2) {
			this.slidescroller.start(0,0);
		} else {	
			this.slidescroller.toElement(this.slides[this.slideselected]);
		}
	},
	nextslide:function() {this.showslide(this.slideselected == this.slides.length-1 ? 0 : this.slideselected+1);},
	prevslide:function() {this.showslide(this.slideselected == 0 ? this.slides.length-1 : this.slideselected-1);},
	scrollComplete:function() {this.slidescroller.set((this.slideselected+1)*this.slidebase.getSize().x,0);}
});

var DHover = new Class({
	Implements:[Events,Options],
	
	options:{
		//onMouseIn:$empty,
		//onMouseOut:$empty
	},
	name:function() {return 'DHover';},
	initialize:function(element,options) {
		this.setOptions(options);
		this.element = document.id(element);
		this.listener = this.element;
		this.bound = {
				attach:this.attach.bind(this),
				detach:this.detach.bind(this),
				getCoord:this.getCoord.bind(this)
		};
		this.quads = new Array();
	},
	start:function() {
		this.listener.addEvents({
			mouseenter:this.bound.attach,
			mouseleave:this.bound.detach
		});
		this.attach();
		return this;
	},
	stop:function() {
		this.listener.removeEvents({
			mouseenter:this.bound.attach,
			mouseleave:this.bound.detach
		});
		this.detach();
		return this;
	},
	/* must put in top bounding as ab, bc */
	addConvexQuad:function(a,b,c,d) {
		var upper1 = function(x) {return ((b.y-a.y)/(b.x-a.x))*x + a.y - ((b.y-a.y)/(b.x-a.x))*a.x;};
		var upper2 = function(x) {return ((c.y-b.y)/(c.x-b.x))*x + b.y - ((c.y-b.y)/(c.x-b.x))*b.x;};
		var lower1 = function(x) {return ((d.y-c.y)/(d.x-c.x))*x + c.y - ((d.y-c.y)/(d.x-c.x))*c.x;};
		var lower2 = function(x) {return ((a.y-d.y)/(a.x-d.x))*x + d.y - ((a.y-d.y)/(a.x-d.x))*d.x;};		
		var inbounds = function(x,y) {return y >= Math.max(upper1(x),upper2(x)) && y <= Math.min(lower1(x),lower2(x));};
		this.quads.push({inbounds:inbounds});
	},
	attach:function() {
		this.coordbase = this.element.getPosition();
		this.coordsize = this.element.getSize();
		this.listener.addEvent('mousemove',this.bound.getCoord);
	},
	detach:function() {
		this.fireEvent('onMouseOut');
		this.listener.removeEvent('mousemove',this.bound.getCoord);
	},
	getCoord:function(event) {
		var testin = false;
		if (event.page.x < this.coordbase.x || event.page.x > this.coordbase.x+this.coordsize.x || event.page.y < this.coordbase.y || event.page.y > this.coordbase.y+this.coordsize.y) {this.detach();return;}
		this.quads.each(function(e){if (e.inbounds(event.page.x-this.coordbase.x,event.page.y-this.coordbase.y)) {testin = true;return;}}.bind(this));
		this.fireEvent(testin ? 'onMouseIn':'onMouseOut');
	}
});


