﻿//------------------------------------------------------------------------------------
// Atelier Pixel City
// Page developed by Ara Yazedjian
// -----------------------------------------------------------------------------------
// Additional methods for Element
var MyUtils = {
    getLmargin: function(element){
    	try {
    	    element = $(element);
    	}
    	catch(e) {
    	    return;
    	};
    	//var lMargin = parseFloat(element.getStyle('margin')) || 0;
		//if (lMargin == 0){
			var lMargin = parseFloat(element.getStyle('marginLeft')) || 0;
	//	}
		return 	lMargin;
    },
    getRmargin: function(element){
    	try {
    	    element = $(element);
    	}
    	catch(e) {
    	    return;
    	};
       var rMargin = parseFloat(element.getStyle('marginRight')) || 0;
		//if (rMargin == 0){
		//	rMargin = parseFloat(element.getStyle('marginRight'));
		//}
		return 	rMargin;
    },
    getHmargins: function(element){
    	try {
    	    element = $(element);
    	}
    	catch(e) {
    	    return;
    	};
      // var hMargin = (parseFloat(element.getStyle('margin'))*2) || 0;
		//if (hMargin == 0){ //If code not necesary because explorer places seperatly declared margins in the main margins style
			var hMargin = parseFloat(element.getStyle('marginLeft')) || 0
			hMargin = hMargin + (parseFloat(element.getStyle('marginRight')) || 0);
		//}
		return 	hMargin;
    }
};
Element.addMethods(MyUtils);

Object.extend(Effect, {
//new addition for centering a div on a page
	centre: function(element) {
	    try {
    	    element = $(element);
    	}
    	catch(e) {
    	    return;
    	}
 	   	var my_width  = document.viewport.getWidth();
	    var my_height = document.viewport.getHeight();
	    element.style.position = 'absolute';
    	//element.style.display  = 'block';
    	//element.style.zIndex   = 99;
		var scrollY = document.viewport.getScrollOffsets().top
		var elementDimensions = Element.getDimensions(element);
		var setX = ( my_width  - elementDimensions.width  ) / 2;
		var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;
		setX = ( setX < 0 ) ? 0 : setX;
		setY = ( setY < 0 ) ? 0 : setY;
		element.style.left = setX + "px";
		element.style.top  = setY + "px";
	}
});

/*--------------------------------------------------------------------------*/
//IE stuff !!!!!!!
/*--------------------------------------------------------------------------*/

//Function to remove default scroll bar from page on IE
function noIEScrollbar()
{
	var IE = (navigator.userAgent.indexOf('MSIE') != -1);
	if(!IE)
		return;
	var root = document.all[1]; // IE >= 4

	if(root.style.overflow != 'hidden')
		root.style.overflow = 'hidden';
	document.body.style.width = root.clientWidth + 'px';
};

//A function to get max_height to work in ie 6. Note: for dynamic resizing, attach to the window onresize event
function setMaxHeight(elementId, height){
	if(typeof document.body.style.maxHeight === "undefined")
	{
		var container = $(elementId);
		container.style.height = (container.scrollHeight > (height - 1)) ? height + "px" : "auto";
	};
};

/*--------------------------------------------------------------------------*/
//jump to another language code
/*--------------------------------------------------------------------------*/
function switchLang( event, langExt ) {
	event.stop();
	switch(langExt){
		case 'eng' :
			location.replace( document.location.href.substring(0,document.location.href.lastIndexOf('/')) + '/index_eng.html' + document.location.hash)
			break;
		case 'esp' :
			location.replace( document.location.href.substring(0,document.location.href.lastIndexOf('/')) + '/index_esp.html' + document.location.hash)
			break;
		default :
			location.replace( document.location.href.substring(0,document.location.href.lastIndexOf('/')) + '/index_fr.html' + document.location.hash)
			break;
	}
}
function InitLang( item, lang ) {
	ProjectsOptions = Object.extend({
		textSection1: '',
		textSection2: '',
		textSection3: '',
		textSection4: '',
		project: '',
		preposition: '',
		lang: '',
		activeNavClass: 'activeNav',
		navBox: 'projets',
		pauseProjectNav: false
	}, window.ProjectsOptions || {});
	switch(lang){
		case 'eng' :
			ProjectsOptions.textSection1 = 'Mandate'
			ProjectsOptions.textSection2 = 'Description'
			ProjectsOptions.project = 'Project '
			ProjectsOptions.preposition = ' of '
			ProjectsOptions.lang = 'eng'
			break;
		case 'esp' :
			ProjectsOptions.textSection1 = 'Mandato'
			ProjectsOptions.textSection2 = 'Descripción'
			ProjectsOptions.project = 'Proyectos '
			ProjectsOptions.preposition = ' de '
			ProjectsOptions.lang = 'esp'
			break;
		default :
			ProjectsOptions.textSection1 = 'Mandat'
			ProjectsOptions.textSection2 = 'Description'
			ProjectsOptions.project = ' Projet '
			ProjectsOptions.preposition = ' de '
			ProjectsOptions.lang = 'fr'
			break;
	}
	var links = $(item).select('a')
	links.each(function(item, index) {
 		item.observe('click', function(event) {
 				event.stop();
				var lang = this.href.split("#")[1]
				switchLang(event, lang)
			} )
 	});
}
/*--------------------------------------------------------------------------*/
//Check to see if within delay, if so kill else toggle appearance
function toggleLoading(laodingId){
	var tQueue = Effect.Queues.get('loading');
	var qMarker = false
	tQueue.each(function(effect) {qMarker=true; effect.cancel(); });
    if (!qMarker) {
		new Effect.toggle(laodingId, 'appear',
		{
        	delay: 0.1,
        	duration: 0,
  			queue: {
  				position: 'front',
				scope: 'loading',
				limit: 1}
		});
	};
};

/*--------------------------------------------------------------------------*/
//Universal mouse over code
//Just add class="mouseover" to any image tag on page
//General variable declaration
var oversuffix = '_over';
var mouseOvers = new Array();
var mouseOuts = new Array();
//the functions
function mouseGoesOver(el) {
	el.src = mouseOvers[el.number].src;
};
function mouseGoesOut(el) {
	el.src = mouseOuts[el.number].src;
};

function setMouseOvers() {
	//Find all images on page
	var allimages = document.getElementsByTagName('img');
	allimages = $(allimages)
	//Extract mouse over images and set swap images
	var imouseovers = 0;
	for (i=0;i<allimages.length;i++){
		if (allimages[i].className == 'mouseover') {
			//get image type from extension
			var imagetype = allimages[i].src.substring(allimages[i].src.lastIndexOf('.'));
			mouseOuts[imouseovers] = new Image();
			mouseOuts[imouseovers].src = allimages[i].src;
			mouseOvers[imouseovers] = new Image();
			mouseOvers[imouseovers].src = allimages[i].src.substring(0,allimages[i].src.lastIndexOf('.')) + oversuffix + imagetype;
			allimages[i].number = imouseovers;
			//Set mouse enter and mouse leave events
			Event.observe(allimages[i], 'mouseover', function(event) {
				mouseGoesOver(this)
			});
			Event.observe(allimages[i], 'mouseout', function(event) {
				mouseGoesOut(this)
			});
			imouseovers++
		 };
	};
};

// Project slideShow navigation
/*--------------------------------------------------------------------------*/
function setProjectControls( controlsId, currentProjectHash ) {
	var controlBox = $(controlsId)
	var prevLink = controlBox.select('a')[0]
	var nextLink = controlBox.select('a')[1]
	var prevProjectHash
	var nextProjectHash
	//var statusBox = controlBox.select('span')[0]
	var statusText = ProjectsOptions.project + xmlProjects.indexOf(currentProjectHash) + ProjectsOptions.preposition + (xmlProjects.length - 1)
	controlBox.select('span')[0].innerHTML = statusText
	prevLink.href = '#' + prevProjectHash
	nextLink.href = '#' + nextProjectHash
}
function initProjectControls(controlsId) {
	$(controlsId).observe('click', function(event){
		event.stop();
		var clickedLink = event.findElement('a') || 0;
		changeProject(clickedLink)
	})
}

// initProjectControls('projectCycle')

/*--------------------------------------------------------------------------*/
// Horizontal scroll code, used in background images and slide show strip
function turnOff( obj ) {
	if (obj != 0) obj.hide()
}
function turnOn( obj ) {
 if (obj != 0) obj.show()
}
// Code used on window resize to pin content to right edge of window
function pinRight( cropBoxId, contentBoxId ) {

}
function stopScroll(effectScope) {
	var queue = Effect.Queues.get(effectScope);
	queue.each(function(e) { e.cancel() });
};
// If butons are not declared they will not be disactivated
function scrollH(cropBoxId, contentBoxId, speed, effectScope, buttonL, buttonR) {
	buttonL = buttonL || 0;
	buttonR = buttonR || 0;
	var cropWidth = Element.getWidth(cropBoxId);
	var contentWidth = Element.getWidth(contentBoxId);
	var maxScroll = -(contentWidth - cropWidth);
	var xPos = $(contentBoxId).positionedOffset().left  || 0;
	var moveTo = maxScroll - xPos;
	if (speed<0){ //if going left
		speed = Math.abs(xPos / speed);
		if (xPos != 0) {
			new Effect.Move (contentBoxId,
			{
				x: -xPos,
				y: 0,
				mode: 'relative',
				duration: speed,
				queue: {
					position: 'front',
					scope: effectScope,
					limit: 1
				},
				transition: Effect.Transitions.linear,
				afterSetup: function(effect) {turnOn.call(this, buttonR)},
				afterFinish: function(effect) {turnOff.call(this,buttonL)}

			});
		}

	} else { // if going right
		speed = Math.abs(moveTo / speed)
		if (xPos>maxScroll) {
			new Effect.Move (contentBoxId,
				{ x: moveTo,
				y: 0,
				mode: 'relative',
				duration: speed,
				queue: {
					position: 'front',
					scope: effectScope,
					limit: 1
				},
				transition: Effect.Transitions.linear,
				afterSetup: function(effect) {turnOn.call(this, buttonL)},
				afterFinish: function(effect) {turnOff.call(this,buttonR)}
				});
		};
	}
}
/*--------------------------------------------------------------------------*/
// Background images code
/*--------------------------------------------------------------------------*/
//Function to set Images box length adding up content length and return it
function SetImagesBoxSize(boxId) {
	var imagesBox = $(boxId);
	imagesBox.cleanWhitespace(); // remove extra whitespace between dom elements i.e. images
	var length = 0
	//get only images
	var imagesArray = imagesBox.select('img');
	imagesArray.each(function(item, index) {
		//item.setStyle( {top: 0, left: length +'px'});
		length = length + item.getWidth();
	});
	imagesBox.setStyle({width: length +'px'})
	return length
}
function initBackground(contentBox){
	//Resize content box
	SetImagesBoxSize(contentBox);
	//get scroll elements
	var zonePrev = $('HotSpotPrevious')
	var zoneNext = $('HotSpotNext')
	var buttonPrev = $('Previous').select('img')[0]
	var buttonNext = $('Next').select('img')[0]
	// set up mouse events for scroll
	zonePrev.observe('mouseover',  function(event) {$('Previous').setStyle({visibility: 'visible'})});
	zoneNext.observe('mouseover',  function(event) {$('Next').setStyle({visibility: 'visible'})});
	zonePrev.observe('mouseout',  function(event) {$('Previous').setStyle({visibility: 'hidden'})});
	zoneNext.observe('mouseout',  function(event) {$('Next').setStyle({visibility: 'hidden'})});
	buttonNext.observe('mouseover',  function(event) {scrollH("ImageBox", "Images", 300, 'backScroll')});
	buttonPrev.observe('mouseover',  function(event) {scrollH("ImageBox", "Images", -300, 'backScroll')});
	buttonPrev.observe('mouseout',  function(event) {stopScroll('backScroll')});
	buttonNext.observe('mouseout',  function(event) {stopScroll('backScroll')});
}
/*--------------------------------------------------------------------------*/
// Icon slide show code
/*--------------------------------------------------------------------------*/
function resizeIconBox(containerBox){
	var container = $(containerBox)
	var imagesBox = container.select('div');
	if (!imagesBox[0]) { //make sure slide show images exist
		return
	}
	else {
		container.down().cleanWhitespace(); // remove extra whitespace between dom elements i.e. images
		var buttonLeft = container.up().select('.iconBoxNavLeft')[0]
		var buttonRight = container.up().select('.iconBoxNavRight')[0]
		buttonLeft.hide()
		buttonRight.hide()
		var containerWidth = container.up().getWidth() - container.getHmargins()
		var imagesArray = container.select('img');
		var itemLength = (imagesArray[0].getWidth() + imagesArray[0].getHmargins()) || 0;
		//Set content box length
		imagesBox[0].setStyle({width: itemLength * imagesArray.length + 'px'})
		//alert( itemLength * imagesArray.length )
		//Check to see if icons fit on screen
		if (containerWidth <= itemLength * imagesArray.length) {
			buttonLeft.down().stopObserving()
			buttonRight.down().stopObserving()
			containerWidth = itemLength * Math.floor(containerWidth / (imagesArray[0].getWidth() + imagesArray[0].getHmargins()))
			buttonLeft.setStyle({left: container.up().getWidth() - containerWidth - container.getLmargin() +4 +'px'})
			//alert(container.getLmargin())
			var scrollPos = imagesBox[0].positionedOffset().left || 0;
			var maxScroll = -((itemLength * imagesArray.length) - containerWidth);
			if (scrollPos != 0) buttonLeft.show();
			if (scrollPos != maxScroll) {
				buttonRight.show()
			}
			if (scrollPos < maxScroll) {
				buttonRight.hide()
				//alert(scrollPos + ', '+ maxScroll)
				imagesBox[0].setStyle({left: maxScroll + 'px'})
			};
			buttonLeft.down().observe('mouseover',  function(event) {scrollH(container, imagesBox[0], -175, 'iconscroll', buttonLeft, buttonRight)});
			buttonLeft.down().observe('mouseout',  function(event) {stopScroll( 'iconscroll')});
			buttonRight.down().observe('mouseover',  function(event) {scrollH(container, imagesBox[0], 175, 'iconscroll', buttonLeft, buttonRight)});
			buttonRight.down().observe('mouseout',  function(event) {stopScroll( 'iconscroll')});
		} else {
			//keep content pined right
			imagesBox[0].setStyle({left: '', right: 0})
		}
		container.setStyle({width: containerWidth + 'px'})
	}
}
/*--------------------------------------------------------------------------*/
//Code for popup modol window info used for contact buton
function endModal(overlay) {
	var contentWindow =  $(overlay).next()
	new Effect.Fade(overlay, {
			duration: 1.5,
			delay: 0.5,
			afterFinish: function(effect) {effect.element.remove()}});
	new Effect.Fade( contentWindow, { duration: 1.0});
}
function showModalWindow(event, contentId) {
	event.stop();
	//Add overlay div before contentID element
	//alert(contentId)
	var contentObj = $(contentId);
	//Effect.centre(contentObj)
	contentObj.insert({before: Builder.node('div',{id:'modalOverlay'})});
	var overlayObj = $('modalOverlay')
	//hide overlay initially and set close on click action
	overlayObj.hide().observe('click', (function(event) { endModal('modalOverlay'); }));
	//Fit overlay to window
    var pageSize = document.viewport.getDimensions();
    overlayObj.setStyle({ width: pageSize.width + 'px', height: pageSize.height + 'px' });

	// Fade in overlay
    new Effect.Appear(overlayObj, { duration: 1.0, from: 0.0, to: 0.8 });
    //centre content box and show
	Effect.centre(contentObj)
    new Effect.Appear(contentObj, {duration: 1.5, delay: 0.5})
}
function initModalWindow(buttonId, contentId) {
	button = $(buttonId)
	modalLink = button.select('a')[0]
	modalLink.observe('click', (function(event) { showModalWindow(event, contentId)}))
}
/*--------------------------------------------------------------------------*/
//XML code
/*--------------------------------------------------------------------------*/
var xmlProjects
function loadXML(fileURL) {
	var xmlDoc = null;
	if (window.XMLHttpRequest)
	{
  		xhttp=new window.XMLHttpRequest();
  	}
  	else // Internet Explorer 5/6
  	{
  		xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
	xhttp.open("GET",fileURL,false);
	xhttp.send(null);
	xmlDoc=xhttp.responseXML;
	//alert(xmlDoc)
	xmlProjects = xmlDoc.getElementsByTagName("project");
	//return  xmlProjects;
}
function getXmlTextContent(sourceXML, id) {
var text=''
	if (sourceXML.getElementsByTagName(id)[0]){
		if (sourceXML.getElementsByTagName(id)[0].childNodes[0]){
			if (sourceXML.getElementsByTagName(id)[0].childNodes[0].nodeValue){
				text = sourceXML.getElementsByTagName(id)[0].childNodes[0].nodeValue;
			};
		};
	};
	return text;
};
function getXmlAttribute(sourceXML, id, attribute) {
var attributeText=''
	if (sourceXML.getElementsByTagName(id)[0]){
		if (sourceXML.getElementsByTagName(id)[0].childNodes[0]){
			if (sourceXML.getElementsByTagName(id)[0].childNodes[0].nodeValue){
				attributeText = sourceXML.getElementsByTagName(id)[0].getAttribute(attribute);
			};
		};
	};
	return attributeText;
};



function getProjectByHashId(id) {
	var currentSectionHash = $$('.'+ ProjectsOptions.activeNavClass)[0].href.split("#")[1] || 0;
	for (i=0;i<xmlProjects.length;i++){
		if (xmlProjects[i].getAttribute("hashId") == id) {
			document.location.hash=xmlProjects[i].getAttribute("hashId"); //set page hash
			return xmlProjects[i];
		} else if (currentSectionHash==xmlProjects[i].getAttribute("hashId")){
			var currentSection = i
		}
	};
	//If supplied id does not exist, get current section and set page hash
	document.location.hash = xmlProjects[currentSection].getAttribute("hashId") //set page hash
	return xmlProjects[currentSection];
};


 /*
Code for preloading images
*/
function initPics(picSrcArray, button, backgroundBox, textBox, slideshowBox, isFirstPass){
        var ImagePreLoader = Class.create({
                callback: null,
                imageCache: new Array,
                loaded: 0,
                processed: 0,
                noOfImages: 0,
                initialize: function(images, options) {
                        if (options) {
                                if (options.callback) this.callback = options.callback;
                        }
                        this.noOfImages = images.length;
                        for ( var i = 0; i < images.length; i++ )
                      this.preload(images[i]);
                },
                preload: function(imgSrc) {
                        var image = new Image;
                        this.imageCache.push(image);
                        Event.observe(image, 'load', this.onload.bindAsEventListener(this), false);
                        Event.observe(image, 'error', this.onerror.bindAsEventListener(this), false);
                        Event.observe(image, 'abort', this.onabort.bindAsEventListener (this), false);
                        image.preloader = this;
                        image.loaded = false;
                        image.src = imgSrc;
                },
                onComplete: function() {
                        this.processed++;
                        if (this.processed==this.noOfImages) {
                                this.callback(this.imageCache, this.loaded);
                        }
                },
                onload: function(e) {
                        this.loaded++;
                        this.onComplete();
                },
                onerror: function(e) {
                        this.onComplete();
                },
                onabort: function(e) {
                        this.onComplete();
                }
        });
        var imgPreloadCallback = function(imageCache, loaded) {
            // where:
            //     imageCache is an array of the loaded images
            //     loaded is an int of the number of images that loaded.
            //doSomethingAfterImagesAreLoaded();
                picsPreLoaded = true;
                if (!isFirstPass) {
                	fadeInNewProject(button, backgroundBox, textBox, slideshowBox);
                } else {

                	initBackground(backgroundBox);
                }
                toggleLoading('mainLoading');
		};
        var imgLoader = new ImagePreLoader(picSrcArray,
		{callback:imgPreloadCallback});
}

// set mouse events on navigation
function setNavActions(navId) {
	$(navId).observe('click', function(event) {
		event.stop();
		var clickedLink = event.findElement('a') || 0;
		if (clickedLink != 0) {  //make sure click was actually on a link element
			if (clickedLink.href.split("#")[0] != document.location.href.split("#")[0]){   // If link on different page
			window.location.assign(clickedLink.href); //then go to it, leave page
			} else
			if (!ProjectsOptions.pauseProjectNav)	{ // If not in the middle of a project swap
  				if ($$('.'+ ProjectsOptions.activeNavClass)[0].href.split("#")[1] != clickedLink.href.split("#")[1]) { // If not linking to current page
  					nextProjectId = clickedLink.href.split("#")[1];
  					if (nextProjectId)  {
  						ProjectsOptions.pauseProjectNav = true;
						changeProject(clickedLink);
					};
				};
			};
		};
	});
};

//Create poject navigation from xml doc, also determine default project and set page hash
function createProjectNav(sectionId, isActive){
	//Get navigation box
	var navBox = $(sectionId).select('.sections');
	var defaultProject = 0;
	var defaultButton = null;
	//Get current page hash
	var currentHash = document.location.hash.split("#")[1] || '0';
	var currentHashBoolean = false;
	var currentButton = null;
	//clear any existing content
	navBox[0].innerHTML = '';
	//Set link string according to language
	var pagePath = ''
	if (!isActive) {
		var lang = '_' + ProjectsOptions.lang
		pagePath = 'projects/index' + lang +'.html'
	}
	//retrieve project list from xml file and create menu dom
	for (i=0;i<xmlProjects.length;i++){
		var navHashId = xmlProjects[i].getAttribute("hashId");
		var navName = getXmlTextContent(xmlProjects[i], "menu_name");
		var navTitle = getXmlTextContent(xmlProjects[i], "title");
		navBox[0].insert({bottom:
			Builder.node('a',
				{href: pagePath + '#'+navHashId,
				title: navTitle },
				[navName]
			)}
		);
		navBox[0].insert({bottom:
			Builder.node('br')}
		);
		if (Boolean(xmlProjects[i].getAttribute("isdefault"))){
			//set as default section
			defaultProject = xmlProjects[i].getAttribute("hashId");
			defaultButton = navBox[0].select('a').last();
		};
		//check to see if document hash exists in xml file
		if (navHashId == currentHash){
			currentHashBoolean = true;
			currentButton = navBox[0].select('a').last();
		}
	}
	//if no default declared in xml then set default to first project in xml file
	if (defaultProject == 0 ) {
		defaultProject = xmlProjects[0].getAttribute("hashId");
		defaultButton = navBox[0].select('a')[0]
	}
	//check to see if hash exists, if not set to default
	if (!currentHashBoolean) {
		currentHash = defaultProject;
		currentButton = defaultButton;
	};
	if (isActive) {
	// set document hash and mark current project nav button
		document.location.hash = currentHash; // set page hash
		currentButton.addClassName(ProjectsOptions.activeNavClass);
	}
	initScrollButtons(sectionId, 'navUp', 'navDown', 'navSub', 'sections', '70');
	setNavActions(sectionId)
};



// Set up slideshow box
function initSlideshow(currentProject, slideshowBox, imgArray){
	var iconWidth = 80;
	var iconHeight = 45
	var iconSuffix = '_sm'
	//get the images.
	var slideshowImagesXML = currentProject.getElementsByTagName('slideshowImage');
	//Check to see if any exist first
	if (slideshowImagesXML[0]) {
		if (Boolean(slideshowImagesXML[0].getElementsByTagName('fileName')[0].childNodes[0])) {
			// create dom elements from xml
			var imgSource = null
			var iconSource = null
			//create container div to allow for scrolling
			slideshowBox.insert({top: Builder.node('div', {className: 'slidesContainer'})});
			for (i=0;i<slideshowImagesXML.length;i++){
				imgSource = currentProject.getAttribute("hashId") + '/' + slideshowImagesXML[i].getElementsByTagName('fileName')[0].childNodes[0].nodeValue
				iconSource = imgSource.substring(0,imgSource.lastIndexOf('.')) + iconSuffix + imgSource.substring(imgSource.lastIndexOf('.'));
				slideshowBox.down().insert(Builder.node('a',
									{href: imgSource,
									title: slideshowImagesXML[i].getElementsByTagName('description')[0].childNodes[0].nodeValue,
									rel:"lightbox[lb_slides]"},[
										Builder.node('img',
											{src: iconSource,
											width: iconWidth + ' px',
											height: iconHeight + ' px' })]
									)
				);
				// Mark image for preloading
				imgArray[i] = iconSource;
			};
		};
	};
	Lightbox.updateImageList;
	//Resize icon box
	resizeIconBox(slideshowBox)
};

function cleanUpSlides(link){
	//Clean up... remove old project and set new as current
	$("text").remove();
	$("text_next").id = "text"
	$("Images").remove();
	$("Images_next").id = "Images"
	$("iconBoxContent").remove();
	$("iconBoxContent_next").id = "iconBoxContent";
	// Re-activate navigation
	ProjectsOptions.pauseProjectNav = false;
};

function fadeInNewProject(button, backgroundContainer, textContainer, slideshowContainer){
		var fade;
		var appear;
		var move;
   		var p;
   		var backgroundCropBox = $(backgroundContainer).up()
		p = new Effect.Parallel(
			[
 			fade = new Effect.Fade($("Images"), { sync: true, from: 1, to: 0}),
			appear = new Effect.Appear(backgroundContainer, { sync: true, from: 0, to: 1}),
			fade = new Effect.Fade($("text"), { sync: true, from: 1, to: 0}),
			appear = new Effect.Appear(textContainer, { sync: true, from: 0, to: 1}),
			fade = new Effect.Fade($("iconBoxContent"), { sync: true, from: 1, to: 0}),
			appear = new Effect.Appear(slideshowContainer, { sync: true, from: 0, to: 1})
			],
			{
	  		duration: 3.0,
			queue: {position: 'back',
					scope: 'mainNav',
					limit: 1},
			afterSetup: function(effect) {setNewSubSection.call(this, button), SetImagesBoxSize.call(this, backgroundContainer)},
			afterFinish: function(effect) {cleanUpSlides.call(this)}
			})
		fade = null;
		appear = null;
		p = null;
		move = null;
};

function displayProject(projectXML, isFirstPass, button){
	//Check boolean isFirstPass to determin if we are dealing with a first load or a project swap
	//and select container boxes accordingly. HTML doc must contain elements with ids text, Images and iconBoxContent

	if (isFirstPass) {
		var textBox = $("text");
		var backgroundBox = $("Images");
		var slideshowBox = $("iconBoxContent");
	}
	else {
		var currentTextBox = $("text");
		var currentIconBox = $("iconBoxContent")
		//Create next project dom elements
		$("ImageBox").insert(Builder.node('div',
			{id:'Images_next', className: 'backgroundImages'}
			));
		var newTextDiv = currentTextBox.clone(false);
		newTextDiv.id = newTextDiv.id + '_next';
		currentTextBox.insert({after: newTextDiv});
		var newIconDiv = currentIconBox.clone(false);
		newIconDiv.id = newIconDiv.id + '_next';
		currentIconBox.insert({after: newIconDiv});

		// Set content box variables
		var backgroundBox = $("Images_next");
		backgroundBox.setOpacity(0); // If hidden safari can't get size of element for setting up icon box
		var textBox = $("text_next");
		textBox.hide();
		var slideshowBox = $("iconBoxContent_next");
		slideshowBox.setOpacity(0); // If hidden safari can't get size of element for setting up icon box

	};

	/*----------------------------------------------------------------------------------------------- */
	/* Set up content */
	var imagesXML = projectXML.getElementsByTagName('images');
	//Start with text section
	//clear any existing content
	textBox.innerHTML = "";
	// Set project title
	textBox.insert(Builder.node('h1', projectXML.getElementsByTagName('title')[0].childNodes[0].nodeValue));
	//Format main content structure
	textBox.insert(
		Builder.node('div',{className:'content'}, [
			Builder.node('h2', getXmlTextContent(projectXML, 'title2')),
			Builder.node('h2', getXmlTextContent(projectXML, 'short_description')),
			Builder.node('h4', [
				getXmlTextContent(projectXML, 'location'),
				', ',
				Builder.node('span', {className: 'date'}, getXmlTextContent(projectXML, 'year'))
			]),
			Builder.node('h5', ProjectsOptions.textSection1),
			Builder.node('span', {className:'mandate'},''),
			Builder.node('h5', ProjectsOptions.textSection2),
			Builder.node('span', {className:'projectDscpt'},'')
		]));
	//optional content
	if (getXmlTextContent(projectXML, 'producer') != 0){
		textBox.down(1).insert(
			Builder.node('h5', getXmlAttribute(projectXML, 'producer', 'title')));
		textBox.down(1).insert(
			Builder.node('span', getXmlTextContent(projectXML, 'producer'))
		);
	};
	if (getXmlTextContent(projectXML, 'director') != 0){
		textBox.down(1).insert(
			Builder.node('h5', getXmlAttribute(projectXML, 'director', 'title'))
		);
		textBox.down(1).insert(
			Builder.node('span', getXmlTextContent(projectXML, 'director'))
		);
	};
	//A little bit of space at the bottom
	textBox.down(1).insert(
		Builder.node('br')
	);
	textBox.down(1).insert(
		Builder.node('br')
	);
	//Extract, format and set mandate section
	var mandateXML = projectXML.getElementsByTagName('mandate');
	var mandateBox = textBox.select('.mandate');
	for (i=0;i<mandateXML.length;i++){
		if (getXmlTextContent(mandateXML[i], 'main_mandate')){
			mandateBox[0].insert(Builder.node('b', getXmlTextContent(mandateXML[i], 'main_mandate')));
			if (getXmlTextContent(mandateXML[i], 'sub_mandate')){
				mandateBox[0].insert(': ' +  getXmlTextContent(mandateXML[i], 'sub_mandate').replace(/,/g, " |"));
			}
			mandateBox[0].insert(Builder.node('br'));
		}
	};
	//Extract, format and set description section
	var descriptionXML = projectXML.getElementsByTagName('description');
	var paragraphsXML = descriptionXML[0].getElementsByTagName('paragraph');
	var descriptionBox = textBox.select('.projectDscpt');
	if (Boolean(paragraphsXML) && Boolean(descriptionBox)){
		for (i=0;i<paragraphsXML.length;i++){
			if (Boolean(paragraphsXML[i].childNodes[0])) {
				descriptionBox[0].insert(Builder.node('p', paragraphsXML[i].childNodes[0].nodeValue));
			};
		};
	};
	// Declare Array of images to preload
	var projectImgsSrc = new Array;
	// Set Slide show content
	initSlideshow(projectXML, slideshowBox, projectImgsSrc)
	//Set up for background images
	//clear any existing content
	backgroundBox.innerHTML = "";
	// get background images file names
	var backgroundXML = imagesXML[0].getElementsByTagName('background');
	if (!backgroundXML[0])  // make sure xml has content
	{
		alert('You must declare at least one background image for the project: ' + projectXML.getElementsByTagName('title')[0].childNodes[0].nodeValue + ' in the projects.xml file');
		return
	};
	backgroundXML = backgroundXML[0].getElementsByTagName('fileName')
	if (!Boolean(backgroundXML[0])){  // make sure xml has content
		alert('You must declare at least one background image for the project: ' + projectXML.getElementsByTagName('title')[0].childNodes[0].nodeValue + ' in the projects.xml file');
		return
	}
	imgsI = projectImgsSrc.length + 1
	// Set up dom images
	for (i=0;i<backgroundXML.length;i++){
		if (Boolean(backgroundXML[i].childNodes[0])) {
			projectImgsSrc[imgsI+i]= projectXML.getAttribute("hashId") + '/' + backgroundXML[i].childNodes[0].nodeValue;
			backgroundBox.insert(Builder.node('img', {src: projectXML.getAttribute("hashId") + '/' + backgroundXML[i].childNodes[0].nodeValue, width: '1024 px', height: '576 px'}));
		};
	};
		// If there is only one image, duplucate it for large screens
	if (backgroundXML.length == 1) {
		backgroundBox.insert(Builder.node('img', {src: projectXML.getAttribute("hashId") + '/' + backgroundXML[0].childNodes[0].nodeValue, width: '1024 px'}));
	};
	//Function to wait for images to load before continuing with setup. See callback function for details
	initPics(projectImgsSrc, button, backgroundBox, textBox, slideshowBox, isFirstPass);
};

function changeProject(button) {
	// If link on different page then go to it ..leave page
	if (button.href.split("#")[0] != document.location.href.split("#")[0]){
		window.location.assign(button.href)
	} else
		if (Boolean(button.href.split("#")[1])) {   // If link hash exists then continue
			// make sure not linking to current section
			if 	(button.href.split("#")[1] != $$('.'+ ProjectsOptions.activeNavClass)[0].href.split("#")[1]) {
				//Turn on new section
				toggleLoading('mainLoading');
				var nextProjectXML = getProjectByHashId(button.href.split("#")[1])
				displayProject(nextProjectXML, false, button)
			};
	};
};

function initProjects() {
	//We create project nav and set default page
	createProjectNav(ProjectsOptions.navBox, true)
	var docHash = document.location.hash
	//No comment needed
	displayProject(getProjectByHashId(docHash), true);
};




/*--------------------------------------------------------------------------*/
// Scroll code vertical
function initScrollButtons(section, upButton, downButton, container, content, scrollSpeed) {
	var sectionBox = $(section)
	var downlink_box =sectionBox.select('.'+downButton + ' a')[0];
	var uplink_box = sectionBox.select('.'+upButton + ' a')[0];
	var container_box = sectionBox.select('.'+container)[0];
	var content_box = sectionBox.select('.'+content)[0];
	container_box.minScroll = 0
	container_box.maxScroll = content_box.getHeight() - container_box.getHeight()
	scrollSpeed = parseFloat(scrollSpeed);
	Element.setStyle(content_box, {top: container_box.minScroll + 'px', left: '0px'})
	activateButton(downlink_box);
	Event.observe(uplink_box, 'click',  function(event) {navScroll(uplink_box, downlink_box, container_box, content_box, -scrollSpeed, 0)});
	Event.observe(downlink_box, 'click',  function(event) {navScroll(uplink_box, downlink_box, container_box, content_box, scrollSpeed, 0)});
	disActivateButton(uplink_box);
	// Check to see if the active project nav link is visible on page. If not scroll to it
	activeSection = sectionBox.select('.'+ ProjectsOptions.activeNavClass)[0] || 0;
	if (activeSection != 0){
		if (activeSection.positionedOffset().top >= container_box.getHeight()-2) {
			navScroll(uplink_box, downlink_box, container_box, content_box,  (activeSection.positionedOffset().top - (container_box.getHeight()/2)), 0)
		}
	}
};
function disActivateButton(button) {
	var buttonImage = button.select('img')[0];
	buttonImage.setOpacity('0.2');
	button.stopObserving('mouseover');
	button.stopObserving('mouseout');
	button.setStyle('cursor: default');
};
function activateButton(button) {
//alert(button.className)
	var buttonImage = button.select('img')[0];
	buttonImage.setOpacity('0.5');
	button.observe('mouseover', function(event) {buttonImage.setOpacity('1.0')});
	button.observe('mouseout',  function(event) {buttonImage.setOpacity('0.5')});
	button.setStyle('cursor: pointer');
};

// Projects menu scroll
function navScroll(buttonUp, buttonDown, cropBox, contentBox, vSpeed, hSpeed) {
//Calculate projected position and compare with min/max to set true absolute position
	var yPos = Math.abs(parseFloat(Element.getStyle(contentBox, 'top'))  || 0);
	var projectedPos = yPos + parseFloat(vSpeed);
	var vSroll = projectedPos;
	if (projectedPos > cropBox.maxScroll) {
		vSroll = cropBox.maxScroll;
	} else if (projectedPos < cropBox.minScroll) {
		vSroll = cropBox.minScroll;
	};
//take care of buttons
	switch(vSroll){
		case cropBox.minScroll :
			disActivateButton(buttonUp);
			activateButton(buttonDown);
			break;
		case cropBox.maxScroll :
			disActivateButton(buttonDown);
			activateButton(buttonUp);
			break;
		default :
			activateButton(buttonDown);
			activateButton(buttonUp);
			break;
	}
//make time proportional to movement
	var time = Math.abs((yPos-vSroll) / 100);
// Make move
	new Effect.Move (contentBox,{
			x: hSpeed,
			y: -vSroll,
			mode: 'absolute',
			duration: time,
			queue: {
				position: 'front',
				scope: 'textscroll',
				limit: 1},
			transition: Effect.Transitions.sinoidal});
};



/*--------------------------------------------------------------------------*/
//Functions to lower and raise text content box
function initSlideVertical(buttonId, boxId, downPos) {
	var scrollBox = $(boxId)
	$(buttonId).observe('click', function(event) {slideVertical(buttonId, scrollBox, downPos)});
};

function slideVertical(buttonId, scrollBox, downPos) {
	var button = $(buttonId);
	var imagePath = button.src.substring(0,button.src.lastIndexOf('/')+1);
	var currentPos = Math.abs(parseFloat(scrollBox.getStyle('top')));
	if (downPos == currentPos) {
		new Effect.Move (scrollBox,{ x: 0, y: 0, mode: 'absolute', duration: 1.25, queue: {position: 'front', scope: 'bottomPop', limit: 1}, transition: Effect.Transitions.sinoidal});
		button.src = imagePath + 'button_down.png';
		mouseOvers[button.number].src = imagePath + 'button_down_over.png';
		mouseOuts[button.number].src = imagePath + 'button_down.png';
	}
	else {
		new Effect.Move (scrollBox,{ x: 0, y: downPos, mode: 'absolute', duration: 1.25, queue: {position: 'front', scope: 'bottomPop', limit: 1}, transition: Effect.Transitions.sinoidal});
		button.src = imagePath + 'button_up.png';
		mouseOvers[button.number].src = imagePath + 'button_up_over.png';
		mouseOuts[button.number].src = imagePath + 'button_up.png';
	};
};

/*--------------------------------------------------------------------------*/
//code for swaping  about us section content
/*--------------------------------------------------------------------------*/
function setNewSubSection(link) {
	$$('.'+ ProjectsOptions.activeNavClass)[0].removeClassName(ProjectsOptions.activeNavClass);
	link.addClassName(ProjectsOptions.activeNavClass);
	document.location.hash=link.href.split("#")[1];
};
function changeSubSection(button) {
	if (Boolean(button.href.split("#")[1])){   // If link hash exists then continue
		var activeSection = $$('.'+ ProjectsOptions.activeNavClass)[0].href.split("#")[1]+'_texte'
		var newSection = button.href.split("#")[1]
		var newImage = $$('[sec="'+newSection+'"]')[0]
		var newSection = newSection +'_texte'
		if 	(activeSection != newSection) {    // make sure not linking to current section
		//Turn on new section
		//var xPos = (parseFloat(newImage.getStyle('left')) || 0);
		var xPos = (newImage.positionedOffset().left || 0);
		var fade;
		var appear;
		var move;
   		var p;
		p = new Effect.Parallel([
 			fade = new Effect.Fade(activeSection, { sync: true, from: 1, to: 0}),
			appear = new Effect.Appear(newSection, { sync: true, from: 0, to: 1}),
			move = new Effect.Move (newImage.up(),{ sync: true,  x: -xPos, y: 0, mode: 'absolute', transition: Effect.Transitions.linear}) ],
			{
	  		duration: 1.5,
			queue: {position: 'back',
					scope: 'mainNav',
					limit: 1},
			afterSetup: function(effect) {setNewSubSection.call(this, button)}
			})
		fade = null;
		appear = null;
		p = null;
		move = null;
		};
	};
};
function initSections(navId, defaultSectionId) {
	var currentHref = document.location.href.split("#")[0] || 0;
	var currentSectionId = document.location.href.split("#")[1] || 0;
	var navSubSections=$(navId).select('.sections');
	var allNavLinks = $(navId).select('.sections a')
//Check to see if document url has a hash and that it refers to a section. If not set to default section
	if (currentSectionId == 0) {
		document.location.hash=defaultSectionId;
		currentSectionId = defaultSectionId;
	} else if (!(Boolean($(currentSectionId+'_texte')))) {
		document.location.hash=defaultSectionId;
		currentSectionId = defaultSectionId;
	} else if (!($(currentSectionId+'_texte').hasClassName('textPopUp'))) {
		document.location.hash=defaultSectionId;
		currentSectionId = defaultSectionId;
	};

//Find and activate current section
	allNavLinks.each(function(item, index) {
		var buttonSectionId = item.href.split("#")[1]
		if (currentSectionId == buttonSectionId)  {
			$(buttonSectionId+'_texte').show();
			Element.addClassName(item, ProjectsOptions.activeNavClass);
			var newImage = $$('[sec="'+buttonSectionId+'"]')[0]
			var xPos = (newImage.positionedOffset().left || 0);
			new Effect.Move (newImage.up(), { x: -xPos, y: 0, mode: 'absolute', transition: Effect.Transitions.full})
		}
		else if ($(buttonSectionId+'_texte')){
			$(buttonSectionId+'_texte').hide();
			Element.removeClassName(item, ProjectsOptions.activeNavClass);
		}
	});

// set mouse events on navigation
	$(navId).observe('click', function(event) {
  		var clickedLink;
  		clickedLink = event.findElement('a');
  		if (clickedLink) {
  			event.stop();
			changeSubSection(clickedLink);
		};
	});
};

