/**
 * @author LEC
 */
var PortfolioData = Class.create({
	contentArr: new $H({}),
	reelInfo:new $H(),
	webReelInfo:new $H(),
	MatchThis:"",
	outputNode: undefined,
	XmlUrl:"/xml/portfolio.xml?ts=" + new Date().getTime(),
	initialize:function(elementToAddTo){
		this.graftElement = graftElement = elementToAddTo;
		var address = document.location.toString();
		if(address.toQueryParams()['c']){
			var caseStudy = address.toQueryParams()['c'];
		}
		
		new Ajax.Request( this.XmlUrl,{
			method:'get',
			onSuccess: function(returned){
				slidelist.contentArr = new $H({});
				var categoryNodes = $A(returned.responseXML.getElementsByTagName('projectlist'));
				categoryNodes.each(
					function(h, p){ 
						try{
							var cat = String(h.getAttribute('category'));
							slidelist.contentArr.set(cat, new $A());
							var projects = $A(h.getElementsByTagName('project'));
							projects.each(
								function(r, i){
									try {
										var thumb = r.getAttribute('thumbnailsrc');
										var call = encodeURIComponent(r.getAttribute('title'));
										var slideNodes = $A(r.getElementsByTagName('slide'));
										var slides = $A();
										slideNodes.each(
											function (h, p){
												slides.push({
													src:h.getAttribute('src'), layout:h.getAttribute('layout')
												});
											}
										);
										var desc = r.getElementsByTagName('description')[0].childNodes[0].nodeType == 3 ? r.getElementsByTagName('description')[0].childNodes[1].nodeValue : r.getElementsByTagName('description')[0].childNodes[0].nodeValue;
									}
									catch(error){
										window.alert(error);
									}
									
									slidelist.contentArr.get(cat).push($H({
										p: call,
										t: thumb,
										d: desc,
										s: slides
									}));
								}
							);
						}
						catch(err){
							window.alert("list parsing: "+ err);
						}	
					}
				);
				try {
					var reelNode = returned.responseXML.getElementsByTagName('reel')[0];
					var call = encodeURIComponent(reelNode.getElementsByTagName('project')[0].getAttribute('title'));
					var reelsrc = reelNode.getElementsByTagName('slide')[0].getAttribute('src');
					var reellayout = reelNode.getElementsByTagName('slide')[0].getAttribute('layout');
					
					slidelist.reelInfo = $H({
						p: call,
						d:"",
						t:"",
						s: [{
							src: reelsrc,
							layout: reellayout
						}]
					});
					
					var webCall = encodeURIComponent(reelNode.getElementsByTagName('project')[1].getAttribute('title'));
          var webReelsrc = reelNode.getElementsByTagName('slide')[1].getAttribute('src');
          var webReellayout = reelNode.getElementsByTagName('slide')[1].getAttribute('layout');
					
					slidelist.webReelInfo = $H({
            p: webCall,
            d:"",
            t:"",
            s: [{
              src: webReelsrc,
              layout: reellayout
            }]
          });
				}
				catch(err){
					alert("reelNode: "  + err);
				}
				var params = String(window.location).toQueryParams();
				try {
					
					if (params['p'].empty() == false) {
						slideviewer = new SlideViewer(params['p']);
					}
				}
				catch(e){
					//alert(e);
				}
				if(window.location.href.indexOf("/portfolio/") != -1){
					 var portNav = new PortfolioMenu();
				}
			}
		});
	},
	findProject: function(projectToFind){
		this.MatchThis = encodeURIComponent(projectToFind);
		if(this.MatchThis == this.reelInfo.get('p')){
			return this.reelInfo;
		}else if(this.MatchThis == this.webReelInfo.get('p')){
      return this.webReelInfo;
    }else{
			this.contentArr.each(function(s){
				$A(s.value).each(function(q, l){
					if(this.outputNode != undefined){
					throw $break;
				}		
					if (q.get('p') == this.MatchThis) {
						this.outputNode = q;
						return;
					}
					
				}, this);
				if(this.outputNode != undefined){
					throw $break;
				}
			}, this);
			return this.outputNode;
		}
	}
});

var SlideViewer = Class.create({
	staticContent: null,
	dynamicContent: null,
	slideArea:null,
	slideNode:null,
	rtArrow:null,
	ltArrow:null,
	labelcell:null,
	paginationCell:null,
	currentImage:null,
	currentFlash:null,
	flashPlayer:null,
	currentSource:null,
	currentLayout:null,
	showEm:null,
	hideEm:null,
	obscureControls:null,
	stopOver:null,
	startOver:null,
	leftHideTween:null,
	rightHideTween:null, 
	setMouseMove:null,
	eventTimer:0,
	tweenUp:false,
	tweenDown:false,
	projectData: [],
	currentIndex:0,
	initialize: function(projectToFind){
		try {
			this.projectData = slidelist.findProject(projectToFind);
			this.staticContent = $$('.mainBody')[0].firstDescendant();
			//hide current content
			this.hideStatic();
			//create Elements
			this.buildSlide();
		}
		catch(err){
			//alert(err)
		}
	},
	hideStatic: function(event){
		document.body.className += document.body.className == "redPage" ? " redPageWork" : " work";
		this.staticContent.style.display = "none";
	},
	showStatic: function(event){
		
		if (document.body.className.indexOf('redPageWork') != -1) {
			document.body.className = document.body.className.gsub('redPageWork', '');
		}
		else if (document.body.className.indexOf('work') != -1) {
			document.body.className = document.body.className.gsub('work', '');
		}
		slideviewer.staticContent.style.display = "block";
		slideviewer.dynamicContent.update("");
		slideviewer.dynamicContent.style.display = "none";
		//window.location.hash = "";
		slideviewer.dynamicContent = null;
	},
	buildSlide: function(){
		if(this.dynamicContent == null){
			this.dynamicContent = new Element('div',{ 'class':'marginSet slidePanel' });
			var closeBtn = new Element('a', { 'href':'javascript:;', 'class':'closeSlide' }).update("Close");
			this.slideArea = new Element('div', { 'class':'slideWrapper' });
			this.rtArrow = new Element('div', { 'class':'rightArrow' });
			var rtTopBlock = new Element('div', { 'class':'top' });
			var rtMidBlock = new Element('div', { 'class':'middle' });
			var rtBottomBlock = new Element('div', { 'class':'bottom' });
			this.ltArrow = new Element('div', { 'class':'leftArrow' });
			var ltTopBlock = new Element('div', { 'class':'top' });
			var ltMidBlock = new Element('div', { 'class':'middle' });
			var ltBottomBlock = new Element('div', { 'class':'bottom' });
			this.slideNode = new Element('div', { 'class':'slide' });
			this.currentImage = new Element('img', {'src':'','style':'visibility:hidden;'});
			this.currentFlash = new Element('div', {'id':'flashSlide','style':'visibility:hidden;display:none'});
			this.labelcell = new Element('div', { 'class':'label' }).update(this.projectData.get('d'));
			this.paginationCell = new Element('div', { 'class':'pagination' });
			this.slideNode.update(this.currentImage);
			this.slideNode.appendChild(this.currentFlash);
			this.rtArrow.appendChild(rtTopBlock);
			this.rtArrow.appendChild(rtMidBlock);
			this.rtArrow.appendChild(rtBottomBlock);
			this.slideArea.appendChild( this.rtArrow);
			
			this.ltArrow.appendChild(ltTopBlock);
			this.ltArrow.appendChild(ltMidBlock);
			this.ltArrow.appendChild(ltBottomBlock);
			
			this.slideArea.appendChild(this.ltArrow);
			this.slideArea.appendChild(this.slideNode);
			this.dynamicContent.appendChild(this.slideArea);
			this.dynamicContent.appendChild(closeBtn);
			this.dynamicContent.appendChild(this.paginationCell);
			this.dynamicContent.appendChild(this.labelcell);
			$$('.mainBody')[0].appendChild(this.dynamicContent);
			
			this.ltArrow.hide();
			this.rtArrow.hide();
			this.makeControlsGoAway();
			
			this.showEm = this.determineVisibility.bindAsEventListener(this);
			this.hideEm = this.hideControls.bindAsEventListener(this);
			this.stopOver = this.stopEffect.bindAsEventListener(this);
			this.startOver = this.startEffect.bindAsEventListener(this);
			this.obscureControls = this.makeControlsGoAway.bindAsEventListener(this);
			
			Event.observe(closeBtn, 'click', this.showStatic);
			Event.observe(this.rtArrow, 'click', this.nextSlide);
			Event.observe(this.ltArrow, 'click', this.previousSlide);
			Event.observe(this.rtArrow, 'mousemove', this.stopOver);
			Event.observe(this.ltArrow, 'mousemove', this.stopOver);
			Event.observe(this.rtArrow, 'mouseout', this.startOver);
			Event.observe(this.ltArrow, 'mouseout', this.startOver);
			Event.observe(this.currentImage, 'load', this.fadeIn);
			Event.observe(document, 'mousemove', this.showEm);
			
		}else{
			this.labelcell.update(this.projectData.get('d'));
			this.paginationCell.update("");
		}
		this.projectData.get('s').each(
			function(h, i){
				var _src = $H(h).get('src');
				var _index = i;
				var _layout = this.determineLayout(h);
				var pageLink = new Element('a', { 'href':'javascript:slideviewer.showSlide("' + _src + '","' + _layout + '",' + _index + ');' }).update(i+1);
				
				this.paginationCell.appendChild(pageLink);
				
				var addon = i < this.projectData.get('s').length - 1 ? " / " : ""
				this.paginationCell.innerHTML += addon;
			},
			this
		);
		var lyt = this.determineLayout(this.projectData.get('s')[0]);
		var idx = this.currentIndex == null? 0 : this.currentIndex;
		this.showSlide($H(this.projectData.get('s')[0]).get('src'), lyt, idx);
		
	},
	determineLayout:function(hash){
		hash = $H(hash);
		var output = "";
		if (hash.get('layout') != null) {
			output = hash.get('layout');
		}
		else if (hash.get('src').toLowerCase().indexOf(".flv") != -1) {
			output = "slidevideo";
		}
		else {
			output = "slideimage";
		}
		return output;
	},
	showSlide: function(slidePath, layout, index){
		this.currentIndex = index;
		this.currentSource = slidePath;
		this.currentLayout = layout;
		this.obscureControls();
		if (this.currentImage.getAttribute('src') != "" || this.currentImage.style.display == "none") {
			  new Effect.Opacity(
			 	this.slideArea,
				{duration: 0.6, transition: Effect.Transitions.linear, from: 1.0, to: 0, afterFinish:this.swapAndFadeIn }
				
			);
		}else{
			new Effect.Opacity(this.slideArea,
				{duration: 0, transition: Effect.Transitions.linear, from: 1.0, to: 0 })
			this.swapAndFadeIn();
		}	
	},
	swapAndFadeIn: function(obj){
		
			if(this.currentSource != null){
				var scopeRoot = this;
			}else{
				var scopeRoot = slideviewer;
			}
		// reset layout class
		scopeRoot.dynamicContent.addClassName(scopeRoot.currentLayout);
		
		if(scopeRoot.currentLayout == "slideimage"){
			// remove flash elements and load new image
			scopeRoot.currentFlash.style.display = 'none';
			scopeRoot.currentFlash.update("");
			scopeRoot.currentImage.style.display = 'block';
			scopeRoot.currentImage.style.visibility = 'visible';
			scopeRoot.currentImage.setAttribute('src', scopeRoot.currentSource);
		}else{
			scopeRoot.currentFlash.style.display = 'block';
			scopeRoot.currentImage.style.display = 'none';
			scopeRoot.currentFlash.style.visibility = 'visible';
			scopeRoot.currentImage.style.visibility = 'hidden';
			//flash embed code here
			var SOSlide = new SWFObject(scopeRoot.currentSource, "slideVideoPlayer", "540", "360", "9", "#707070");
			SOSlide.addParam("allowScriptAccess", "always");
			SOSlide.addParam("wmode", "transparent");
		 	SOSlide.write("flashSlide");
			scopeRoot.flashPlayer = $("slideVideoPlayer");
			scopeRoot.fadeIn();
		}
		
		
		// highlight item based on currentIndex
		scopeRoot.highlightSlide();
		
		
		
	},
	fadeIn:function(event){
		if(this.currentSource != null){
			var scopeRoot = this;
		}else{
			var scopeRoot = slideviewer;
		}
		// fade in
		new Effect.Opacity( scopeRoot.slideArea, {
			duration: 0.5, 
			transition: Effect.Transitions.linear, 
			from: 0, 
			to: 1.0
			}
		);
	},
	nextSlide: function(_event){
		if(this.currentSource != null){
				var scopeRoot = this;
			}else{
				var scopeRoot = slideviewer;
			}
		if (scopeRoot.currentIndex < scopeRoot.projectData.get('s').length - 1) {
			scopeRoot.currentIndex ++;
			var curData = $H(scopeRoot.projectData.get('s')[scopeRoot.currentIndex])
			scopeRoot.showSlide(curData.get('src'), scopeRoot.determineLayout(curData), scopeRoot.currentIndex)
		}
	},
	previousSlide: function(_event){
		if(this.currentSource != null){
				var scopeRoot = this;
			}else{
				var scopeRoot = slideviewer;
			}
		if (scopeRoot.currentIndex > 0) {
			scopeRoot.currentIndex --;
			var curData = $H(scopeRoot.projectData.get('s')[scopeRoot.currentIndex])
			scopeRoot.showSlide(curData.get('src'), scopeRoot.determineLayout(curData), scopeRoot.currentIndex)
		}
	},
	highlightSlide: function(){
		var _links = $$('.pagination')[0].childElements();//this.paginationCell
		var targetLink = "";
		$A(_links).each(function(h, i){
			_links[i].className = null;
		}, this);
		_links[this.currentIndex].className = 'selected';
		//alert(this.currentIndex + ": " + _links[this.currentIndex].inspect())
	},
	showControls: function(_event){
		
		clearInterval(this.eventTimer);
		this.eventTimer = setInterval(this.hideEm, 1000);
		
		if(!this.tweenUp ){
			this.tweenUp = true;
			this.tweenDown = false;	
			if (this.currentIndex < this.projectData.get('s').length - 1) {
				this.rightHideTween.cancel();
				new Effect.Appear(this.rtArrow, {
					duration: 0.6
				});
			}
			if(this.currentIndex > 0){
				this.leftHideTween.cancel();
				new Effect.Appear(this.ltArrow,{
					duration: 0.6
				});
			}
		}
	},
	hideControls: function(_event){
		
		clearInterval(this.eventTimer);
		if (!this.tweenDown) {
			this.tweenUp = false;
			this.tweenDown = true;
			if (this.currentIndex < this.projectData.get('s').length - 1) {
				this.rightHideTween = new Effect.Fade(this.rtArrow, {
					duration: 0.6
				});
			}
			if (this.currentIndex > 0) {
				this.leftHideTween = new Effect.Fade(this.ltArrow, {
					duration: 0.6
				});
			}
		}
	},
	makeControlsGoAway: function(){
		this.tweenUp = false;
		this.tweenDown = true;
		 this.rightHideTween = new Effect.Fade(this.rtArrow,{
			duration: 0
			});
				
		this.leftHideTween = new Effect.Fade(this.ltArrow,{
			duration: 0
			});
					
	},
	stopEffect: function (_event){
		clearInterval(this.eventTimer);
	},
	startEffect: function (_event){
		clearInterval(this.eventTimer);
		this.eventTimer = setInterval(this.hideEm, 1000);
		Event.observe(this.dynamicContent, 'mousemove', this.showEm);
	},
	determineVisibility:function (_event){
		var mouseY = Event.pointerY(_event);
		var mouseX = Event.pointerX(_event);
		
		if(Position.within(this.slideArea, mouseX, mouseY)){
			//this.showEvent(mouseX + " | " + mouseY)
			this.showControls();
		}
	},
	showEvent:function(message){
		var box = $$('.label')[0];
		box.innerHTML += message+"<br>"
	}
	
});
var PortfolioMenu = Class.create({
	outterList:null,
	initialize:function(){
		var data = $H(slidelist.contentArr);
		var containerElement = $$(".marginSet")[0];
		containerElement.removeClassName("marginSet");
		
		this.outterList = new Element('ul', {'class':'portfolioGrid'});
		
		data.each(function(h, i){
			var rowHeader = new Element('h2').update(h.key)
			var outterListItem = new Element('li').update(rowHeader);			
			var innerList = new Element('ul');
			Event.observe(innerList, 'mouseout', this.listout);
			//alert(h.value.length);
			h.value.each(function(r, q){
				var innerListContent = new Element('span').update(decodeURIComponent(r.get('p')));
				var innerListItem = new Element('li', {'style':'background-image:URL('+ r.get('t') +');'}).update(innerListContent);
				innerListItem.query = r;
				Event.observe(innerListItem, 'mouseover', this.over);
				Event.observe(innerListItem, 'mouseout', this.out);
				Event.observe(innerListItem, 'click', launchWork);
				innerList.appendChild(innerListItem);
			}, this);
			outterListItem.appendChild(innerList);
			this.outterList.appendChild(outterListItem);
		}, this);//alert(containerElement);
		containerElement.update(this.outterList);
	},
	over:function(event){
		//alert(event.type);
		Event.element(event).addClassName("hoverElement");
		Event.element(event).parentNode.parentNode.parentNode.childElements().each(function(item, i){
			//alert(item.childElements()[0].inspect())
			item.childElements()[0].removeClassName("hoverCategory");
		})
		Event.element(event).parentNode.previous().addClassName("hoverCategory");
	},
	out:function(event){
		//alert(event.type);
		Event.element(event).removeClassName("hoverElement");
		//Event.element(event).parentNode.previous().removeClassName("hoverCategory");
	},
	listout:function(event){
		//this.clearRows();
		//Event.element(event).previous().removeClassName("hoverCategory");
	},
	clearRows:function(){
		alert("test")
		$A(this.outterList.childElements()).each(function(item, i){
			alert(item.tagName)
			item.select('h2').removeClassName("hoverCategory");
		})
	},
	release:function(event){
		//alert(event.type+" on: "+Event.element(event)._query);
		alert(launchWork)
		launchWork(Event.element(event)._query);
	}
});
				
