/**********************************************************************
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright (c) 2001 Robert Penner
JavaScript version copyright (C) 2006 by Philippe Maegerman
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
   * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*****************************************/

function Delegate(){}Delegate.create=function(a,c){for(var d=[],e=arguments.length,f=2;f<e;f++)d[f-2]=arguments[f];return function(){var h=[].concat(arguments,d);c.apply(a,h)}};Tween=function(a,c,d,e,f,h,i){this.init(a,c,d,e,f,h,i)};var t=Tween.prototype;t.obj={};t.prop="";t.func=function(a,c,d,e){return d*a/e+c};t.begin=0;t.change=0;t.prevTime=0;t.prevPos=0;t.looping=false;t._duration=0;t._time=0;t._pos=0;t._position=0;t._startTime=0;t._finish=0;t.name="";t.suffixe="";t._listeners=[];
t.setTime=function(a){this.prevTime=this._time;if(a>this.getDuration())if(this.looping){this.rewind(a-this._duration);this.update();this.broadcastMessage("onMotionLooped",{target:this,type:"onMotionLooped"})}else{this._time=this._duration;this.update();this.stop();this.broadcastMessage("onMotionFinished",{target:this,type:"onMotionFinished"})}else{if(a<0)this.rewind();else this._time=a;this.update()}};t.getTime=function(){return this._time};
t.setDuration=function(a){this._duration=a==null||a<=0?1E5:a};t.getDuration=function(){return this._duration};t.setPosition=function(a){this.prevPos=this._pos;var c=this.suffixe!=""?this.suffixe:"";this.obj[this.prop]=Math.round(a)+c;this._pos=a;this.broadcastMessage("onMotionChanged",{target:this,type:"onMotionChanged"})};t.getPosition=function(a){if(a==undefined)a=this._time;return this.func(a,this.begin,this.change,this._duration)};t.setFinish=function(a){this.change=a-this.begin};
t.getFinish=function(){return this.begin+this.change};t.init=function(a,c,d,e,f,h,i){if(arguments.length){this._listeners=[];this.addListener(this);if(i)this.suffixe=i;this.obj=a;this.prop=c;this._pos=this.begin=e;this.setDuration(h);if(d!=null&&d!="")this.func=d;this.setFinish(f)}};t.start=function(){this.rewind();this.startEnterFrame();this.broadcastMessage("onMotionStarted",{target:this,type:"onMotionStarted"})};t.rewind=function(a){this.stop();this._time=a==undefined?0:a;this.fixTime();this.update()};
t.fforward=function(){this._time=this._duration;this.fixTime();this.update()};t.update=function(){this.setPosition(this.getPosition(this._time))};t.startEnterFrame=function(){this.stopEnterFrame();this.isPlaying=true;this.onEnterFrame()};t.onEnterFrame=function(){if(this.isPlaying){this.nextFrame();setTimeout(Delegate.create(this,this.onEnterFrame),0)}};t.nextFrame=function(){this.setTime((this.getTimer()-this._startTime)/1E3)};
t.stop=function(){this.stopEnterFrame();this.broadcastMessage("onMotionStopped",{target:this,type:"onMotionStopped"})};t.stopEnterFrame=function(){this.isPlaying=false};t.continueTo=function(a,c){this.begin=this._pos;this.setFinish(a);this._duration!=undefined&&this.setDuration(c);this.start()};t.resume=function(){this.fixTime();this.startEnterFrame();this.broadcastMessage("onMotionResumed",{target:this,type:"onMotionResumed"})};t.yoyo=function(){this.continueTo(this.begin,this._time)};
t.addListener=function(a){this.removeListener(a);return this._listeners.push(a)};t.removeListener=function(a){for(var c=this._listeners,d=c.length;d--;)if(c[d]==a){c.splice(d,1);return true}return false};t.broadcastMessage=function(){for(var a=[],c=0;c<arguments.length;c++)a.push(arguments[c]);var d=a.shift(),e=this._listeners,f=e.length;for(c=0;c<f;c++)e[c][d]&&e[c][d].apply(e[c],a)};t.fixTime=function(){this._startTime=this.getTimer()-this._time*1E3};
t.getTimer=function(){return(new Date).getTime()-this._time};Tween.backEaseIn=function(a,c,d,e){if(f==undefined)var f=1.70158;return d*(a/=e)*a*((f+1)*a-f)+c};Tween.backEaseOut=function(a,c,d,e){if(f==undefined)var f=1.70158;return d*((a=a/e-1)*a*((f+1)*a+f)+1)+c};Tween.backEaseInOut=function(a,c,d,e){if(f==undefined)var f=1.70158;if((a/=e/2)<1)return d/2*a*a*(((f*=1.525)+1)*a-f)+c;return d/2*((a-=2)*a*(((f*=1.525)+1)*a+f)+2)+c};
Tween.elasticEaseIn=function(a,c,d,e,f,h){if(a==0)return c;if((a/=e)==1)return c+d;h||(h=e*0.3);if(!f||f<Math.abs(d)){f=d;d=h/4}else d=h/(2*Math.PI)*Math.asin(d/f);return-(f*Math.pow(2,10*(a-=1))*Math.sin((a*e-d)*2*Math.PI/h))+c};Tween.elasticEaseOut=function(a,c,d,e,f,h){if(a==0)return c;if((a/=e)==1)return c+d;h||(h=e*0.3);if(!f||f<Math.abs(d)){f=d;var i=h/4}else i=h/(2*Math.PI)*Math.asin(d/f);return f*Math.pow(2,-10*a)*Math.sin((a*e-i)*2*Math.PI/h)+d+c};
Tween.elasticEaseInOut=function(a,c,d,e,f,h){if(a==0)return c;if((a/=e/2)==2)return c+d;h||(h=e*0.3*1.5);if(!f||f<Math.abs(d)){f=d;var i=h/4}else i=h/(2*Math.PI)*Math.asin(d/f);if(a<1)return-0.5*f*Math.pow(2,10*(a-=1))*Math.sin((a*e-i)*2*Math.PI/h)+c;return f*Math.pow(2,-10*(a-=1))*Math.sin((a*e-i)*2*Math.PI/h)*0.5+d+c};
Tween.bounceEaseOut=function(a,c,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+c:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+c:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+c:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+c};Tween.bounceEaseIn=function(a,c,d,e){return d-Tween.bounceEaseOut(e-a,0,d,e)+c};Tween.bounceEaseInOut=function(a,c,d,e){return a<e/2?Tween.bounceEaseIn(a*2,0,d,e)*0.5+c:Tween.bounceEaseOut(a*2-e,0,d,e)*0.5+d*0.5+c};Tween.strongEaseInOut=function(a,c,d,e){return d*(a/=e)*a*a*a*a+c};
Tween.regularEaseIn=function(a,c,d,e){return d*(a/=e)*a+c};Tween.regularEaseOut=function(a,c,d,e){return-d*(a/=e)*(a-2)+c};Tween.regularEaseInOut=function(a,c,d,e){if((a/=e/2)<1)return d/2*a*a+c;return-d/2*(--a*(a-2)-1)+c};Tween.strongEaseIn=function(a,c,d,e){return d*(a/=e)*a*a*a*a+c};Tween.strongEaseOut=function(a,c,d,e){return d*((a=a/e-1)*a*a*a*a+1)+c};Tween.strongEaseInOut=function(a,c,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+c;return d/2*((a-=2)*a*a*a*a+2)+c};function Delegate(){}
Delegate.create=function(a,c){for(var d=[],e=arguments.length,f=2;f<e;f++)d[f-2]=arguments[f];return function(){var h=[].concat(arguments,d);c.apply(a,h)}};function Sequence(){this.children=[];this.currentChildIndex=0;this._listeners=[];this.nextObject={};this.addListener(this)}var s=Sequence.prototype;s.addChild=function(a){this.children.push(a)};s.removeChild=function(a){for(var c=this.children,d=c.length;d--;)if(c[d]==a){c.splice(d,1);return true}return false};
s.start=function(){this.rewind();this.play();this.broadcastMessage("onMotionStarted",{target:this,type:"onMotionStarted"})};s.next=function(){this.children[this.currentChildIndex].removeListener(this.nextObject);if(this.currentChildIndex<this.children.length-1){this.currentChildIndex++;this.play()}else{this.stop();this.broadcastMessage("onMotionFinished",{target:this,type:"onMotionFinished"})}};
s.play=function(){this.nextObject={};this.nextObject.onMotionFinished=Delegate.create(this,this.next);this.children[this.currentChildIndex].addListener(this.nextObject);this.children[this.currentChildIndex].start()};s.stop=function(){this.children[this.currentChildIndex].stop();this.broadcastMessage("onMotionStopped",{target:this,type:"onMotionStopped"})};s.rewind=function(){this.children[this.currentChildIndex].removeListener(this.nextObject);for(var a=this.currentChildIndex=0;a<this.children.length;a++)this.children[a].rewind()};
s.fforward=function(){this.children[this.currentChildIndex].removeListener(this.nextObject);for(var a=0;a<this.children.length;a++)this.children[a].fforward();this.currentChildIndex=this.children.length-1};s.resume=function(){this.children[this.currentChildIndex].resume();this.broadcastMessage("onMotionResumed",{target:this,type:"onMotionStopped"})};s.addListener=function(a){this.removeListener(a);return this._listeners.push(a)};
s.removeListener=function(a){for(var c=this._listeners,d=c.length;d--;)if(c[d]==a){c.splice(d,1);return true}return false};s.broadcastMessage=function(){for(var a=[],c=0;c<arguments.length;c++)a.push(arguments[c]);var d=a.shift(),e=this._listeners,f=e.length;for(c=0;c<f;c++)e[c][d]&&e[c][d].apply(e[c],a)};function Delegate(){}Delegate.create=function(a,c){for(var d=[],e=arguments.length,f=2;f<e;f++)d[f-2]=arguments[f];return function(){var h=[].concat(arguments,d);c.apply(a,h)}};
function Parallel(){this.children=[];this.numChildren=0;this._listeners=[];this.addListener(this)}s=Parallel.prototype;s.endObject={};s.addChild=function(a){this.children.push(a);this.numChildren++};s.start=function(){this.play();this.broadcastMessage("onMotionStarted",{target:this,type:"onMotionStarted"})};s.play=function(){for(var a=0;a<this.numChildren;a++){if(a==this.numChildren-1){this.endObject={};this.endObject.onMotionFinished=Delegate.create(this,this.end);this.children[a].addListener(this.endObject)}this.children[a].start()}};
s.end=function(){this.children[this.numChildren-1].removeListener(this.endObject);this.broadcastMessage("onMotionFinished",{target:this,type:"onMotionFinished"})};s.stop=function(){this.enumAction("stop");this.broadcastMessage("onMotionStopped",{target:this,type:"onMotionStopped"})};s.rewind=function(){this.enumAction("rewind")};s.fforward=function(){this.enumAction("fforward")};s.resume=function(){this.enumAction("resume");this.broadcastMessage("onMotionResumed",{target:this,type:"onMotionResumed"})};
s.yoyo=function(){this.enumAction("yoyo")};s.enumAction=function(a){for(var c=0;c<this.numChildren;c++)this.children[c][a]()};s.addListener=function(a){this.removeListener(a);return this._listeners.push(a)};s.removeListener=function(a){for(var c=this._listeners,d=c.length;d--;)if(c[d]==a){c.splice(d,1);return true}return false};
s.broadcastMessage=function(){for(var a=[],c=0;c<arguments.length;c++)a.push(arguments[c]);var d=a.shift(),e=this._listeners,f=e.length;for(c=0;c<f;c++)e[c][d]&&e[c][d].apply(e[c],a)};ColorTween.prototype=new Tween;ColorTween.prototype.constructor=Tween;ColorTween.superclass=Tween.prototype;
function ColorTween(a,c,d,e,f,h){this.targetObject=a;this.targetProperty=c;this.fromColor=e;this.toColor=f;this.init({},"x",d,0,100,h);this.listenerObj={};this.listenerObj.onMotionChanged=Delegate.create(this,this.onColorChanged);this.addListener(this.listenerObj)}var o=ColorTween.prototype;o.targetObject={};o.targetProperty={};o.fromColor="";o.toColor="";o.currentColor="";o.listenerObj={};
o.onColorChanged=function(){this.currentColor=this.getColor(this.fromColor,this.toColor,this._pos);this.targetObject[this.targetProperty]=this.currentColor};o.getColor=function(a,c,d){var e=this.hex2dec(a.slice(0,2)),f=this.hex2dec(a.slice(2,4));a=this.hex2dec(a.slice(4,6));var h=this.hex2dec(c.slice(0,2)),i=this.hex2dec(c.slice(2,4));c=this.hex2dec(c.slice(4,6));d=d/100;r=Math.floor(e+d*(h-e)+0.5);g=Math.floor(f+d*(i-f)+0.5);b=Math.floor(a+d*(c-a)+0.5);return"#"+this.dec2hex(r)+this.dec2hex(g)+this.dec2hex(b)};
o.dec2hex=function(a){return this.hexDigit[a>>4]+this.hexDigit[a&15]};o.hexDigit=Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");o.hex2dec=function(a){return parseInt(a,16)};OpacityTween.prototype=new Tween;OpacityTween.prototype.constructor=Tween;OpacityTween.superclass=Tween.prototype;function OpacityTween(a,c,d,e,f){this.targetObject=a;this.init({},"x",c,d,e,f)}o=OpacityTween.prototype;o.targetObject={};
o.onMotionChanged=function(a){a=a.target._pos;var c=this.targetObject;c.style.opacity=a/100;c.style["-moz-opacity"]=a/100;if(c.filters)c.filters.alpha.opacity=a};TextTween.prototype=new Tween;TextTween.prototype.constructor=Tween;TextTween.superclass=Tween.prototype;function TextTween(a,c,d,e,f){this.targetObject=a;this.targetProperty=c;this.txt=d;if(e!=null&&e!="")this.func=e;this.init({},"x",e,0,d.length,f)}o=TextTween.prototype;o.targetObject={};o.targetProperty={};o.fromColor="";o.toColor="";
o.currentColor="";o.onMotionChanged=function(a){this.targetObject[this.targetProperty]=this.txt.substr(0,a.target._pos)};

/**
 * @author ellier
 */
window.onload = init;

/***************** GLOBAL VARS *****************/
var isIE8;	// set with conditional comments in the head of the html

var portfolioXML = null;
var scBox = null;
var scContent = null;
var cellW = null;
var cellW2 = null;
var cellH = null;
var headerH = null;
var footerHeight = null;
var padMarLR = 4; // Padding and Margin on the left and right of each cell from the css

var categories = [];

var backDrop = null;	// Div that covers the background when showing work
var contDiv = null;		// Div that sits on top of the backDrop and takes the work

var thumbIndex = null;
var albumIndex = 0;		// This is zero bc the first album will load automatically

var aboutPg = null;
var contactPg = null;
var linksPg = null;
var pgHolder = null;

var menuClicked = null;

/***************** INIT FUNCTIONS *****************/

function init() {
	scBox = document.getElementById('scrollBox');
	scContent = document.getElementById('scrollContent');
	footerHeight = document.getElementById('footer').offsetHeight;
	
	setOpacity(scContent, 1);
	
	(document.all) ? window.attachEvent('onresize', windowResize) : window.addEventListener('resize', windowResize, false);

	getContent();
}

function getContent() {
	var aboutReq = new AJAX('about.html', 'responseText', null);
	aboutReq.uponReceived = function() {
		aboutPg = aboutReq.xmldata;
	
		getGallery('portfolio.xml?EI=' + new Date().getTime());
	};
	aboutReq.getData();
}

function getGallery(xml) {
	var Req = new AJAX(xml, 'responseXML', null);	// pass url to xml or hml file plus the kind of response	
	Req.uponReceived = function() {
		portfolioXML = Req.xmldata;
		var xml = portfolioXML.getElementsByTagName('category');
		generateContent(xml[0]);
	}; // Anononymous function to run after you get data
	Req.getData();		// initialize the request
}

/***************** INITIALIZE SCROLLING FUNCTION *****************/

function scrolling() {
	scBox.style.height = document.documentElement.clientHeight - scBox.offsetTop - footerHeight + 'px';
	Drag.init(scContent);
}

/***************** WINDOW RESIZE FUNCTION *****************/

function windowResize() {
	scBox.style.height = document.documentElement.clientHeight - scBox.offsetTop - footerHeight + 'px';
	var windowW =  document.documentElement.clientWidth;
	var w = parseInt(cellW) + padMarLR;
	var numCells = Math.floor(windowW / w);
	cellW2 = (windowW / numCells) - padMarLR;

	for(var i=0; i<Thumbs.thumbs.length; i++) {
		Thumbs.thumbs[i].style.width = cellW2 + 'px';
		//document.getElementById('trace').innerHTML = 'Debug: {' + i + " : " + cellW2 + " : " + windowW + ' : ' + numCells + '}';
	}
}

/***************** MENU FUNCTIONS *****************/

function workFn() {
	showSlide('work', 150);
}

function aboutFn() {
	showSlide('about', 350, aboutPg);
}

function contactFn() {
	showSlide('contact', 250, contactPg);
}

function linksFn() {
	showSlide('links', 100, linksPg);
}

/***************** REMOVE CONTENT FUNCTIONS *****************/

function removeAllContent(obj) {
	while(obj.childNodes.length > 0) {
		obj.removeChild(obj.firstChild);
	}
}

/***************** CHANGE GALLERY CONTENT ******************/
function gall(num) {
	hidePage(); // If there's a page present, get rid of it first
	if(albumIndex != num) {
		albumIndex = num;
		generateContent(portfolioXML.getElementsByTagName('category')[num]);
	}
}

function showPage(pg) {
	if(!document.getElementById('pgHolder')) {
		Drag.stopTimer();
		pgHolder = document.createElement('div');
		pgHolder.setAttribute('id', 'pgHolder');
		pgHolder.innerHTML = pg;
		document.getElementsByTagName('body')[0].appendChild(pgHolder);
		//pg.zIndex = '99';
		var scnt = document.getElementById('scrollContent');
		var t = new OpacityTween(scnt, Tween.easeOut,100,0,0.5);
		t.onMotionFinished = function() {
			scnt.style.display = 'none';
		};
		t.start();
	} else {
		hidePage();
	}
}

function hidePage() {
	if(pgHolder) {
		Drag.initTimer();
		var scnt = document.getElementById('scrollContent');
		var t = new OpacityTween(scnt, Tween.easeOut,0,100,0.5);
		t.onMotionStarted = function() {
			scnt.style.display = 'block';
			pgHolder.parentNode.removeChild(pgHolder);
			pgHolder = null;
		};
		t.start();
	}
}


/********************** SEND MAIL *************************/
function processForm() {
	var mform = document.forms[0];
	var from = mform.elements['from'].value;
	var email = mform.elements['email'].value;
	var mess = mform.elements['message'].value
	var param = 'from='+from+'&email='+email+'&message='+mess;
	var ajxCall = new AJAX('mail.php', 'responseText', param);
	ajxCall.uponReceived = function() {
		if(ajxCall.xmldata == 1) {
			mFeedBack('Thank you. Your message was sent successfully.', true);
			var mform = document.forms[0];
			mform.reset();
		} else if(ajxCall.xmldata == 0) {
			mFeedBack('There was a problem sending your email. Please, use the email links on the right.', false);
		} else {
			mFeedBack(ajxCall.xmldata, true);
		}
	};
	ajxCall.getData();
	
	mform.style.display = 'none';
	mFeedBack('Sending Email Message. Please wait.', false);
}

function mFeedBack(m,bol) {
	if(document.getElementById('feedback')) {
		var ms = document.getElementById('feedback');
		ms.parentNode.removeChild(ms);
	}
	var mesg = document.createElement('h4');
	mesg.setAttribute('id', 'feedback');
	var txt = document.createTextNode(m);
	mesg.appendChild(txt);
	document.getElementById('emailform').appendChild(mesg);
	
	if(bol) {
		var mform = document.forms[0];
		var btn = document.createElement('a');
		var btxt = document.createTextNode('Back');
		btn.setAttribute('id','mailBackBtn');
		btn.appendChild(btxt);
		document.getElementById('emailform').appendChild(btn);
		btn.onclick = function() {
			mform.style.display = 'block';
			var ms = document.getElementById('feedback');
			ms.parentNode.removeChild(ms);
			btn.parentNode.removeChild(btn);
		};
	}
}

function AJAX(url,resType,params){var ajaxRequest;var that=this;this.xmldata;this.uponReceived=function(){};this.method;if(params==''||params==null){this.method='get'}else{this.method='post'}this.getData=function(){responseType=resType;this.createRequest();ajaxRequest.onreadystatechange=this.myFunction;if(document.all){if(this.method=='post'){params=params+"&blah="+(new Date()).getTime()}}if(this.method=='post'){ajaxRequest.open("POST",url,true);ajaxRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');ajaxRequest.send(params)}else{ajaxRequest.open("GET",url,true);ajaxRequest.send(null)}};this.createRequest=function(){try{ajaxRequest=new XMLHttpRequest()}catch(e){try{ajaxRequest=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{ajaxRequest=new ActiveXObject("Microsoft.XMLHTTP")}catch(e){alert("Your browser doesn't support XML requests. In other words, you need a modern browser");return false}}}};this.myFunction=function(){if(ajaxRequest.readyState==4){(resType=='responseText')?that.xmldata=ajaxRequest.responseText:that.xmldata=ajaxRequest.responseXML;that.uponReceived()}}}
var Drag={x:null,y:null,obj:null,offset:null,speed:null,timer:null,counter:null,init:function(o){Drag.obj=o;Drag.speed=40;Drag.counter=0;Drag.offset={_x:Drag.obj.parentNode.offsetLeft,_y:Drag.obj.parentNode.offsetTop};if(Drag.obj.offsetHeight>=Drag.obj.parentNode.offsetHeight){if(document.attachEvent){document.attachEvent('onmousemove',Drag.getCoords);document.attachEvent('onmousemove',Drag.initTimer)}else{document.addEventListener('mousemove',Drag.getCoords,false);document.addEventListener('mousemove',Drag.initTimer,false)}}else{(document.all)?document.detachEvent('onmousemove',Drag.initTimer):document.removeEventListener('mousemove',Drag.initTimer,false);Drag.stopTimer()}},onStart:function(e){},initTimer:function(){(!Drag.timer)?Drag.timer=setInterval('Drag.onScroll()',20):null},stopTimer:function(){if(Drag.timer){clearInterval(Drag.timer);Drag.timer=null}},startTimer:function(){Drag.timer=null},onScroll:function(){var ydist=Drag.y-Drag.obj.parentNode.offsetHeight/2;ydist=ydist-Drag.offset._y;Drag.obj.style.top=Drag.obj.offsetTop-(ydist/Drag.speed)+'px';var topC=parseFloat(Drag.obj.style['top']);if(Drag.obj.offsetTop>0){Drag.obj.style.top=0;Drag.stopTimer()}else if(Drag.obj.offsetTop<(Drag.obj.parentNode.offsetHeight-Drag.obj.offsetHeight)){Drag.obj.style.top=(Drag.obj.parentNode.offsetHeight-Drag.obj.offsetHeight)+'px';Drag.stopTimer()}document.getElementById('trace').innerHTML=Drag.offset._y},onEnd:function(){if(document.attachEvent){document.detachEvent('onmousemove',Drag.getCoords);document.detachEvent('onmouseup',Drag.onEnd)}else{document.removeEventListener('mousemove',Drag.getCoords,false);document.removeEventListener('mouseup',Drag.onEnd,false)}},getCoords:function(e){(!e)?e=window.event:null;var posx=0;var posy=0;if(e.pageX||e.pageY){posx=e.pageX;posy=e.pageY}else if(e.clientX||e.clientY){posx=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;posy=e.clientY+document.body.scrollTop+document.documentElement.scrollTop}Drag.x=posx;Drag.y=posy}};

/*
 * @author ellier
 */

 /***************** BACKGROUND FOR WORK FUNCTIONS *****************/

function showWork() {
/* DELETE
	var sld = document.getElementById('slide');
	(sld) ? hideSlide() : null;
*/	
	Drag.stopTimer();
	backDrop = document.createElement('div');
	contDiv = document.createElement('div');

	
	backDrop.setAttribute('id', 'backDrop');
	contDiv.setAttribute('id', 'contentDiv');
	
	if(isIE8)
		setOpacity(backDrop,0);
	
	document.getElementsByTagName('body')[0].appendChild(backDrop);
	document.getElementsByTagName('body')[0].appendChild(contDiv);

	var p1 = new OpacityTween(backDrop,Tween.regularEaseIn, 0, 85, 0.5);
		
	var bkgTween = new Parallel();
	bkgTween.addChild(p1);
		
	bkgTween.onMotionStarted = function() {
		if(document.attachEvent) {
			document.detachEvent('onmousemove', Drag.initTimer);
			Drag.stopTimer();
		} else {
			document.removeEventListener('mousemove', Drag.initTimer, false);
			Drag.stopTimer();
		}
	};
		
	bkgTween.onMotionFinished = function() {
		htmlHolder();
	};
	
	bkgTween.start();
}



function removeWork() {
/* DELETE
	var sld = document.getElementById('slide');
	(sld) ? hideSlide() : null;
*/
	if(isIE8) {
		setOpacity(backDrop, 0.85);
		setOpacity(contDiv, 0.85);
	}
		
	var bkgParallel = new Parallel();
	var bkgTween = new OpacityTween(backDrop,Tween.strongEaseIn,85, 0, 0.5);
	var contDivTween = new OpacityTween(contDiv,Tween.strongEaseIn,85, 0, 0.5);
	
	bkgParallel.onMotionFinished = function(){
		backDrop.parentNode.removeChild(backDrop);
		contDiv.parentNode.removeChild(contDiv);

		backDrop = null;
		contDiv = null;
		
		if(document.attachEvent) {
			document.attachEvent('onmousemove', Drag.initTimer);
		} else {
			document.addEventListener('mousemove', Drag.initTimer, false);
		}
	};
	
	var pgTween = new OpacityTween(document.getElementById('scrollBox'),Tween.strongEaseOut,50, 100, 0.5);
	//pgTween.start();
	Drag.startTimer();
	bkgParallel.addChild(contDivTween);
	bkgParallel.addChild(bkgTween);

	bkgParallel.start();
}

/********** DISPLAY WORK **********/

function htmlHolder() {
	var holder = document.createElement('div');
	holder.setAttribute('id', 'htmlHolder');
	setOpacity(holder, 0.5);


	contDiv.appendChild(holder);
	
	var workSeq = new Sequence();
	var opacTween = new OpacityTween(holder, Tween.strongEaseIn, 0.3, 100, 0.3);
		
	var workParallel = new Parallel();
	
	var widthTween = new Tween(holder.style, 'width', Tween.strongEaseInOut, 200, 860, 0.75, 'px');
	var heightTween = new Tween(holder.style, 'height', Tween.strongEaseInOut, 100, 550, 0.75, 'px');
	var posxTween = new Tween(holder.style, 'marginLeft', Tween.strongEaseInOut, -100, -430, 0.75, 'px');
	var posyTween = new Tween(holder.style, 'marginTop', Tween.strongEaseInOut, -50, -265, 0.75, 'px');
	
	workParallel.addChild(opacTween);
	workParallel.addChild(widthTween);
	workParallel.addChild(heightTween);

	workParallel.addChild(posxTween);
	workParallel.addChild(posyTween);
	
	workParallel.onMotionFinished = function() {
		displayButtons();
		loadExtWork();	// Load external content
	};
	workParallel.start();
	
}

/********** DISPLAY BUTTONS **********/

function displayButtons() {
	var holder = document.getElementById('htmlHolder');


		var br = document.createElement('div');
		var bl = document.createElement('div');
		
		var nextBtn = document.createElement('div');
		nextBtn.setAttribute(document.all ? 'className' : 'class' , 'nextButton');
		nextBtn.appendChild(br);
		setOpacity(nextBtn,0.25);
		nextBtn.onclick = workNext;
		nextBtn.onmouseover = function() {
			setOpacity(this,0.85);
		};
		nextBtn.onmouseout = function() {
			setOpacity(this,0.25);
		};
		
		holder.appendChild(nextBtn);
		
		var prevBtn = document.createElement('div');
		prevBtn.setAttribute(document.all ? 'className' : 'class' , 'prevButton');
		
		if(isIE8) {
			nextBtn.setAttribute('class' , 'nextButton');
			prevBtn.setAttribute('class' , 'prevButton');
		}

		prevBtn.appendChild(bl);
		setOpacity(prevBtn,0.25);
		prevBtn.onclick = workPrev;
		prevBtn.onmouseover = function() {
			setOpacity(this,0.85);
		};
		prevBtn.onmouseout = function() {
			setOpacity(this,0.25);
		};
		
		holder.appendChild(prevBtn);
		
		var close = document.createElement('a');
		close.href = '#';
		var closeTxt = document.createTextNode('CLOSE');
		close.appendChild(closeTxt);
		close.setAttribute('id', 'closeBtn');
		close.onclick = removeWork;

		holder.appendChild(close);
	
}

/********** FUNCTION TO SET OPACITY **********/

function setOpacity(obj,n) {
	if (typeof obj == 'string')
      obj = document.getElementById(obj);

	if(typeof document.createElement("div").style.filter != 'undefined') {
		obj.style.zoom = 1;
		obj.style.filter = "alpha(opacity=" + n * 100 + ")";
	} else {
		obj.style.opacity = n;
	}
}

/********** SHOW / HIDE CAPTION *********/

function showCaption() {
	var cpt = document.getElementById('workCaption');
	if(cpt) {
		var cptT = new Tween(cpt.style, 'height', Tween.strongEaseInOut, 0, 30, 0.5, 'px');
		cptT.start();
	}
}

function hideCaption() {
	var cpt = document.getElementById('workCaption');
	if(cpt) {
		var cptT = new Tween(cpt.style, 'height', Tween.strongEaseOut, 30, 0, 0.5, 'px');
		cptT.start();
	}
}

/********** LOAD THE WORK **********/

function loadExtWork() {
	var holder = document.getElementById('htmlHolder');
	var obj = document.getElementById('htmlContent');
	var obj2 = document.getElementById('workCaption');

	//(document.all && obj != null) ? holder.style.filter = 'alpha(opacity=' + 100 + ')' : holder.style.opacity = 1; 
	setOpacity(holder, 1);
	
	if(obj) {		// if there's content, we need to remove it.
		var remPar = new Parallel();
		var remTween = new OpacityTween(obj, Tween.regularEaseIn, 100, 0 , 0.5);
		remTween.onMotionStarted = function() {obj.setAttribute('id', '');};
		remTween.onMotionFinished = function() {obj.parentNode.removeChild(obj);};

		if(obj2) {	// if there's a caption, we need to remove it
			var remTween2 = new OpacityTween(obj2, Tween.regularEaseIn, 100, 0 , 0.5);
			remTween2.onMotionStarted = function() {obj2.setAttribute('id', '');};
			remTween2.onMotionFinished = function() {obj2.parentNode.removeChild(obj2);};
			remPar.addChild(remTween);
			remPar.addChild(remTween2);
			remPar.start();
		} else {
			remTween.start();
		}
		
//		remTween.start();
	}
	
	var type = portfolioXML.getElementsByTagName('category')[albumIndex].getElementsByTagName('piece')[thumbIndex].getAttribute('type');
	var src = portfolioXML.getElementsByTagName('category')[albumIndex].getElementsByTagName('piece')[thumbIndex].getAttribute('src');
//	var caption = portfolioXML.getElementsByTagName('category')[albumIndex].getElementsByTagName('piece')[thumbIndex].childNodes[0];
	var caption = portfolioXML.getElementsByTagName('category')[albumIndex].getElementsByTagName('piece')[thumbIndex].childNodes;
	
	if(type == 'html') { // If the content to load is html, do an http request for the page
		var workReq = new AJAX(src, 'responseText', null);
		workReq.uponReceived = function() {
			var cont =  document.createElement('div');
			cont.setAttribute('id', 'htmlContent');
			cont.style.width = '100%';
			cont.style.height = '100%';
			cont.innerHTML = workReq.xmldata;
			holder.appendChild(cont);
			setOpacity(cont,0);
			var opT = new OpacityTween(cont, Tween.regularEaseIn, 0, 100, 0.5);
			opT.start();
		};
		workReq.getData();
	} else {
		var contPict =  document.createElement('div');
		contPict.setAttribute('id', 'htmlContent');
		contPict.style.width = '100%';
		contPict.style.height = '100%';

		var _img = new Image();
				
		holder.appendChild(contPict);
		contPict.appendChild(_img);
		setOpacity(_img,0);
		
		var loadMsg = document.createElement('p');
		var loagMsgTxt = document.createTextNode('Loading picture. Please wait.');
		loadMsg.appendChild(loagMsgTxt);
		loadMsg.setAttribute('id','loadMsg');
		contPict.appendChild(loadMsg);
		
		_img.onload = function() {
			contPict.removeChild(loadMsg);
			
			_img.style.position = 'absolute';
			_img.style.left = '50%';

			_img.removeAttribute('width');
			_img.removeAttribute('height');
			
			var imgW = _img.clientWidth;
			
			_img.style.marginLeft = imgW/2 * -1 + 'px';
			
			var imgT = new OpacityTween(_img, Tween.regularEaseIn, 0, 100, 0.75);
			imgT.start();
		};
			
		_img.src = '';
		_img.src = src;
		
		setOpacity(contPict,0);
		var opT = new OpacityTween(contPict, Tween.regularEaseIn, 0, 100, 0.5);
		opT.start();
				
		if(caption.length > 1) {
			var captionHolder = document.createElement('p');
			captionHolder.setAttribute('id','workCaption');
			(document.all) ? captionHolder.style.filter = 'alpha(opacity=' + 0 + ')' : captionHolder.style.opacity = 0; 
//			var txNode = document.createTextNode(caption.nodeValue);
			
			var lnk = document.createElement('a');
			if(document.all) {
				var txNode = document.createTextNode(caption[0].firstChild.nodeValue);
				var lnkTxt = document.createTextNode(caption[1].firstChild.nodeValue);
				lnk.setAttribute('href', caption[1].getAttribute('href'));
			} else {
				var txNode = document.createTextNode(caption[1].firstChild.nodeValue);
				var lnkTxt = document.createTextNode(caption[3].firstChild.nodeValue);
				lnk.setAttribute('href', caption[3].getAttribute('href'));
			}

			lnk.target = '_blank';			
			lnk.appendChild(lnkTxt);
			
			captionHolder.appendChild(txNode);
			captionHolder.appendChild(lnk);

			holder.appendChild(captionHolder);
			var cptTween = new OpacityTween(captionHolder, Tween.regularEaseIn, 0, 100, 0.5);
			cptTween.start();
		
		}
		
	}
}


function workNext() {
	var ts = portfolioXML.getElementsByTagName('category')[albumIndex].getElementsByTagName('piece');
	var numTs = ts.length;
	if(parseFloat(thumbIndex) >= numTs - 1) {
		thumbIndex = 0;
	} else {
		thumbIndex = parseFloat(thumbIndex) + 1;
	}
	loadExtWork();
}

function workPrev() {
	var ts = portfolioXML.getElementsByTagName('category')[albumIndex].getElementsByTagName('piece');
	var numTs = ts.length;
	if(parseFloat(thumbIndex) <= 0) {
		thumbIndex = numTs - 1;
	} else {
		thumbIndex = parseFloat(thumbIndex) - 1;
	}
	loadExtWork();
}

/**
 * @author ellier
 */

var Thumbs = {
	XML: null,
	thumbs: [],
	thumbW: null,
	thumbH: null,
	container: null,
	
	onclickFn: function() {
		thumbIndex = this.getAttribute('id');
		showWork();
	},
	
	onmouseOverFn: function() {
		this.setAttribute((document.all ? 'className':'class'), 'cellHover');
		var op = null;
		if(typeof document.createElement("div").style.filter != 'undefined') {
			op = this.filters.item('alpha').opacity;
		} else {
			op = this.style.opacity * 100;
		}
		var ct = new OpacityTween(this,Tween.regularEaseOut,op,70,0.1);
		ct.start();
	},
	
	onmouseOutFn: function() {
		this.setAttribute((document.all ? 'className':'class'), 'cell');
		(isIE8) ? this.setAttribute('class', 'cell') : '';
		
		var ct = new OpacityTween(this,Tween.regularEaseOut,70,100,0.1)
		ct.start();
	},
	
	init: function(xml,cont,w,h) {
		this.XML = xml;
		this.container = cont;
		
		Thumbs.thumbW = w;
		Thumbs.thumbH = h;
	},
	
	populate: function() {
		//cellW = XML.getElementsByTagName('portfolio')[0].getAttribute('cellW');
		//cellH = XML.getElementsByTagName('portfolio')[0].getAttribute('cellH');
		
		var thumbsXML = this.XML.getElementsByTagName('piece');
		for(var i=0; i<thumbsXML.length; i++ ) {
			var t = Thumbs.makecell(thumbsXML[i]);
			t.setAttribute('id', i);
			Thumbs.container.appendChild(t);
			Thumbs.thumbs.push(t);
		}
	},
	
	makecell: function(node) {
		var cell = document.createElement('div');
		
		var img = new Image();
		var url = null;
		url = node.getAttribute('tn');
		img.onload = function() {
			cell.style.background = 'url("' + url+ '") no-repeat 0px 0px';
		}
		img.src = url;
		
		cell.setAttribute((document.all ? 'className':'class'), 'cell');
		(isIE8) ? cell.setAttribute('class','cell') : '';
		cell.style.width = Thumbs.thumbW + 'px';
		cell.style.height = Thumbs.thumbH + 'px';
		cell.style.cursor = 'pointer';
		cell.style.overflow = 'hidden';
		//cell.style['float'] = 'left';
		
		cell.onclick = Thumbs.onclickFn;
		cell.onmouseover = Thumbs.onmouseOverFn;
		cell.onmouseout = Thumbs.onmouseOutFn;
		
		//cell.appendChild(img);
		
		return cell;
	}
};

function generateContent(xml) {
	cellW = xml.getAttribute('cellW');
	cellH = xml.getAttribute('cellH');
	var windowW =  document.documentElement.clientWidth;
	var w = parseInt(cellW) + padMarLR;
	var numCells = Math.floor(windowW / w);
	cellW2 = ((windowW / numCells) - padMarLR);
	
	removeAllContent(scContent);
	
	Thumbs.init(xml, scContent, cellW2, cellH);	
	Thumbs.populate();
	
	var allThumbs = scContent.getElementsByTagName('div');
	var thumbSeq = new Sequence();
	for(var i = 0; i < allThumbs.length; i++) {
		setOpacity(allThumbs[i], 0);
		thumbSeq.addChild(new OpacityTween(allThumbs[i],Tween.regularEaseOut,0,100,0.1));
	}
	
	thumbSeq.start();
	scrolling();
}
