

function init() {

  //var pathName = document.location.pathname.substr(1);
  window.currentModule = document.body.id;

  switch ( window.currentModule ) {

    case 'home':
      //$('homeLink').observe('click', function (event) { Event.stop(event) } );

      setTimeout(function () { $('homeTextLine1').fade({ duration: 0.5, to: 0.001 }) }, 2500);
      setTimeout(function () { $('homeTextLine2').fade({ duration: 0.5, to: 0.001 }) }, 2800);
      
      if ($('homeTextLine3'))
    	  setTimeout(function () { $('homeTextLine3').fade({ duration: 0.5, to: 0.001 }) }, 3100);
      if ($('homeTextLine4'))
    	  setTimeout(function () { $('homeTextLine4').fade({ duration: 0.5, to: 0.001 }) }, 3400);
      if ($('homeTextLine5'))
    	  setTimeout(function () { $('homeTextLine5').fade({ duration: 0.5, to: 0.001 }) }, 3700);
      
      if ($('overlay'))
          $('overlay').fade({duration: 0.2});
      break;

    case 'folio':
      $('portfolioLink').observe('click', function (event) { Event.stop(event) } );
      initializePortfolio();
      break;
      
    case 'review':
      $('reviewLink').observe('click', function (event) { Event.stop(event) } );
      initializeReviews();
      if ($('overlay'))
          $('overlay').fade({duration: 0.2});
      break;

    case 'contact':
      $('contactLink').observe('click', function (event) { Event.stop(event) } );
      if ($('overlay'))
          $('overlay').fade({duration: 0.2});
      
    default:
        if ($('overlay'))
            $('overlay').fade({duration: 0.2});
      break;
  }
  
}


function initializePortfolio() {
    
    window.currentProjectIndex = 0;
    window.currentProjectPicturesIndex = 0;
    window.projects = [];
    
    $$('#projectPictures ul').each( function (ul) {
    	window.projects.push(ul.childElements());
    });

    var first = true;
    $$('div.prizeBox').each( function (prizeBox) {
    	if (first) {
	    	var clone = prizeBox.cloneNode(true);
	    	clone.id = 'mainPrizeBox';
	    	clone.setStyle({display: 'none'});
	    	$('page').insert(clone, {position: 'bottom'})
	    	first = false;
    	} else {
    	    prizeBox.setStyle({display: 'none'});	
    	}
    });

    $('overlay').appear({duration: 0.2, afterFinish: function () { 
    	$('projectBoxWrapper').appear({duration: 0.2, afterFinish: function () {
    		var firstItemPrizeBox = $$('#projectNavItem_1 div.prizeBox div span').first();
    		if (firstItemPrizeBox) {
    			$$('#mainPrizeBox div span').first().innerHTML = firstItemPrizeBox.innerHTML;
    			$('mainPrizeBox').appear({duration: 0.3});
    		}
    	} }) } 
    });
        
    $$('#clientsBox ul#clients li a').each(function (link) { 
        Event.observe(link, 'click', function (event) {
          Event.stop(event);
          // enleve le portfolio part du url
          var cleanedPathname = this.pathname.substr(this.pathname.indexOf('/',1)+1);
          var client = cleanedPathname.split('/')[0];  
          if ( client != window.currentClient ) {
              $$('#clients li.current').each( function (li) {
                li.removeClassName('current');
              });
              $(link.parentNode).addClassName('current');
              new Ajax.Request('/portfolio?action=fetch_client&client='+client,
                       { onSuccess: function (transport) { changeClient(transport.responseJSON) } });
          }
        });
    });

	Event.observe(window, 'keydown', function (event) {
        var code = event.keyCode;

        if ( code == Event.KEY_RIGHT ) {
            scrollProjectPictures(1);
        
        } else if ( code == Event.KEY_LEFT ) {
              scrollProjectPictures(-1);
        }

    });

    var sideMaskLeft, sideMaskRight;
      
    if ( sideMaskLeft = $$('div.imageSideMask.left').first() ) {
        Event.observe(sideMaskLeft, 'click', function (event) {
            scrollProjectPictures(-1);
        });
    }

    if ( sideMaskRight = $$('div.imageSideMask.right').first() ) {
        Event.observe(sideMaskRight, 'click', function (event) {
            scrollProjectPictures(1);
        });
    }

    $$('li a.projectNavItem').each(function (li) {
    	Event.observe(li, 'click', function (event) {
    		Event.stop(event);
            scrollToProject(li.innerHTML);
    	});
    })

    setTimeout(function () { $('navDirections').fade({ duration: 0.5 }) }, 2500);
}


function scrollProjectPictures(dir) {

	window.currentProjectPicturesIndex += dir;
	
    if (window.currentProjectPicturesIndex < 0) { 
        
    	window.currentProjectIndex--;
        
    	if (window.currentProjectIndex < 0) {
            window.currentProjectIndex =  0;
            window.currentProjectPicturesIndex = 0;
        } else {
            window.currentProjectPicturesIndex = window.projects[window.currentProjectIndex].length-1;
        }
    }
    else if (window.currentProjectPicturesIndex >= window.projects[window.currentProjectIndex].length) {
        
    	window.currentProjectIndex++;
        
    	if (window.currentProjectIndex >= window.projects.length) {
            window.currentProjectIndex = window.projects.length-1;
            window.currentProjectPicturesIndex -= dir;
        } else {
        	window.currentProjectPicturesIndex = 0;	
        }
    }

    moveProjectPictures();
}


function scrollToProject(index) {
	
	window.currentProjectIndex = index-1;
	window.currentProjectPicturesIndex = 0;

    moveProjectPictures();
}


function moveProjectPictures() {
	
    var imageWidth = $$('#projectPictures img').first().getWidth();
    
    var nbPicturesBefore = 0;
    
    for (var i=window.currentProjectIndex-1; i>=0; i--) {
    	nbPicturesBefore += window.projects[i].length;
    }

    var xPos = (nbPicturesBefore + window.currentProjectPicturesIndex) * imageWidth;
    
    $('projectDescription').innerHTML = $('project_' + (window.currentProjectIndex+1)).innerHTML;
    $$('#projectNav li.current').first().removeClassName('current');
    $('projectNavItem_' + (window.currentProjectIndex+1)).addClassName('current');
    
    var prize = $$('#projectNavItem_' + (window.currentProjectIndex+1) + ' div.prizeBox div span').first();
    if (prize) {
    	$$('#mainPrizeBox div span').first().innerHTML = prize.innerHTML;
    	$('mainPrizeBox').appear({duration: 0.2});
    } else {
    	$$('#mainPrizeBox div span').first().innerHTML = '';
        $('mainPrizeBox').fade({duration: 0.2});	
    }

    new Effect.Move($('projectPictures'), { x: -xPos, y: 0, mode: 'absolute', duration: 0.5, transition: Effect.Transitions.Cubic.easeOut });
    
    if ( ( window.currentProjectIndex == 0 ) && 
         ( window.currentProjectPicturesIndex == 0 ) ) {
    	$$('div.imageSideMask.left').first().hide();
    } else {
    	$$('div.imageSideMask.left').first().show();
    }

    if ( ( window.currentProjectIndex == window.projects.length-1 ) && 
         ( window.currentProjectPicturesIndex == window.projects[window.currentProjectIndex].length-1 ) ) {
       	$$('div.imageSideMask.right').first().hide();
    } else {
    	$$('div.imageSideMask.right').first().show();
    }
}



function changeClient( json ) {

    window.currentClient = json.clientLabel;

    window.currentProjectIndex = 0;
	window.currentProjectPicturesIndex = 0;

	Effect.Parallel([
		$('clientName').fade({duration: 0.3}),
		$('picturesList').fade({duration: 0.3}),
		$('projectDescription').fade({duration: 0.3}),
		$('mainPrizeBox').fade({duration: 0.3}),
		$('projectPictures').fade({duration: 0.3,
						       afterFinish: function () {
	
		                    	   new Effect.Move($('projectPictures'), { x: 0, y: 0, mode: 'absolute', duration: 0 });
	
		                    	   $('projectPictures').update(json.projectPictures);
		                    	   $('picturesList').update(json.projectsNav);
	                               $('clientName').update(json.client.name);
	
		                    	   /*
		                    	   $H(json.client.projects).each( function (project) {
		                    		   var imgSrc = json.clientLabel.toLowerCase() + '_' + project.key.toLowerCase();
		                    		   imgSrc = imgSrc.replace(/[^a-z0-9_]+/g, '_') + '.jpg';
		                    		   var img = new Element('img', {src: '/images/portfolio/'+imgSrc, width: 1010, height: 405, alt: json.client.name + ' - ' + project.value.name});
		                    		   $('projectPictures').appendChild(img)
		                    		   Event.observe(img, 'load', onProjectImageLoaded)
		                    	   })
		                    	   */
	
		                    	   $('projectPictures').setStyle({'width': (json.projectPicturesNumber*982) + 'px'});
		                    	   scrollToProject(1);
	
	                    	       window.projects = [];
		                    	    
		                    	   $$('#projectPictures ul').each( function (ul) {
		                    	   	  window.projects.push(ul.childElements());
		                    	   });
	
		                    	   Event.observe($$('#projectPictures ul li img').first(), 'load', function (event) {
			                    	   Effect.Parallel([
			                      	                   Effect.Appear($('clientName'), {duration: 0.3}),
			     		                    	       Effect.Appear($('picturesList'), {duration: 0.3,
			     		                    	    	                         afterFinish: function () {
				     				                           $$('li a.projectNavItem').each(function (li) {
				     					                           	Event.observe(li, 'click', function (event) {
				     					                           		Event.stop(event);
				     					                                   scrollToProject(li.innerHTML);
				     					                           	});
				     					                           })
			     		                    	       }
			     		                    	       }),
			     		                    	       Effect.Appear($('projectDescription'), {duration: 0.3}),
			     	           	                       Effect.Appear($('projectPictures'), { duration: 0.3 })
			     		                    	   ]);
		                    	   })
		                           
							   } })]
	);
}


function onProjectImageLoaded(event) {
	window.projectsLoaded++;
	if ( window.projectsLoaded == window.projectsNumber ) {
        $('projectPictures').appear({ duration: 0.3 });
	}
}



function initializeReviews() {
	
  $$('#years li a').each( function (yearLink) {
    Event.observe(yearLink, 'click', function (event) {
    	Event.stop(event);
        $$('#years li.current').each( function (li) {
            li.removeClassName('current');
        });
        yearLink.parentNode.addClassName('current');
    	new Ajax.Request('/review.php', 
    			         { parameters:'action=change_year&year=' + yearLink.innerHTML,
    	                   onComplete: function (transport) { changeReviewYear(transport.responseJSON) }
    	});
    });
  });

  $$('#months li a').each( function (monthLink) {
	    Event.observe(monthLink, 'click', changeBackground)
  });
}


function changeReviewYear(json) {
	$$('#months li.month').each(function (li) { li.remove() })
    $('months').update();
	var counter = 1;
	$A(json.months).each( function (month) {
	  var li = new Element('li', 
			               { id: 'month_' + month, 
		                     'class': 'month' + ((counter == $A(json.months).length) ? ' last ' : '') }
	                      ).update('<a name="' + json.year + '/' + month + '" href="/revue/' + json.year + '/' + month + '">' + month + '.</a>');
	  Event.observe(li.firstChild, 'click', changeBackground )
	  $('months').appendChild(li);
	  counter++;
	})
}


function changeBackground(event) {
  Event.stop(event);	
  $$('#months li.current').each( function (li) {
      li.removeClassName('current');
  });
  var currentMonthLink = Event.element(event);
  $(currentMonthLink.parentNode).addClassName('current');
  var yearMonthValues = currentMonthLink.name.split('/');
  var year = yearMonthValues[0];
  var month = yearMonthValues[1];
  new Ajax.Request('/review.php', 
	               { parameters:'action=change_background&year=' + year + '&month=' + month,
                     onComplete: function (transport) {
	  				   toggleContent(false);
	  				   var imageBox = $('backgroundImageBox');
					   imageBox.fade({ duration: 0.4,
					                   afterFinish: function () {
					                     if ($('description')) $('description').remove();
					                     var li = new Element('li', { id: 'description' }).update(transport.responseJSON);
    					             	 $('months').appendChild(li);

					                     var image = $$('#backgroundImageBox img')[0];
					                     image.src = '/assets/backgrounds/' + year + month + '/background.jpg';
   				                  	     Event.observe(image, 'click', function(event) { toggleContent(true) });
					                     resizeBackground(false, transport.responseJSON);
					   				   }});
                     }
  });
}


function toggleContent(state) {
	
	if (state) {
		$('wrapper').appear({ duration: 0.2 });
    	$('descriptionBox').fade({duration: 0.3});
    	$('closeBox').fade({duration: 0.3});
		
	} else {
		$('wrapper').fade({ duration: 0.3 });
	}
}


function resizeBackground(resizeOnly, description) {
    
  // Trouve la largeur et la hauteur de l'ecran;
  var windowHeight = getWindowHeight();
  var windowWidth = getWindowWidth();
  
  // Trouve la hauteur, la largeur et le ratio de l'image originalement
  var image = $$('#backgroundImageBox img')[0];
  var imageHeight = 1200;
  var imageWidth  = 1600;
  var imageRatio = imageHeight/imageWidth;
  
  // Resize et repositionne l'image en conséquence
  
  var imageBox = $('backgroundImageBox');

  if ( (windowWidth <= 1020) && (windowHeight<=690) ) {
    imageWidth = 1020;
    imageHeight = 1020*imageRatio;
    
  } else {
    
    if ( windowWidth > windowHeight ) {
      imageHeight = windowWidth*imageRatio;
      imageWidth = windowWidth;
      if (imageHeight < windowHeight) {
        imageHeight = windowHeight;
        imageWidth = windowHeight * (1/imageRatio);
      }
    
    } else {
      imageWidth = windowHeight * (1/imageRatio);
      imageHeight = windowHeight;
      if (imageWidth < windowWidth) {
        imageWidth = windowWidth;
        imageHeight = windowWidth * imageRatio;
      }
    }
    
  }

  image.setStyle({width: imageWidth+'px', height: imageHeight+'px'});
  image.parentNode.setStyle({width: imageWidth+'px', height: imageHeight+'px'});
  
  if ( ( currentYearMonth == '200812' ) || ( currentYearMonth == '200912' )) {
      imageBox.setStyle({top: '0', left: '50%',
          marginLeft: -(imageWidth/2)+'px',
          marginTop: '0px',
          visibility: 'visible'});
  
  } else {
      imageBox.setStyle({top: '50%', left: '50%',
                         marginLeft: -(imageWidth/2)+'px',
                         marginTop: -(imageHeight/2)+'px',
                         visibility: 'visible'});
  }

  if ( !resizeOnly ) {
    imageBox.setStyle({display: 'none'});
    Event.observe(image, 'load', function () { 
    	imageBox.appear({ duration: 0.4, 
                          beforeStart: function () { 
                                         document.body.className = document.body.className.substr(0,2) + ' ym_' + currentYearMonth; 
                                         if ( document.location.href.indexOf('credits') > 0 ) {
                                           $$('#localNavBox > div').each( function (box) { box.addClassName('closed'); });
                                           $('ym_' + currentYearMonth).removeClassName('closed');
                                         }
                                       } 
                         });

    	if (description != undefined) {
          if ( $('descriptionBox') ) { 
        	  $('descriptionBox').innerHTML = description;
          } else {
        	  var descBox = new Element('div', { id: 'descriptionBox', style: 'display: none' }).update(description);
      	      Element.insert(document.body, {bottom: descBox});
          }

          if ( !$('closeBox') ) {
			  var text = ($(document.body).hasClassName('fr') ? 'Cliquez l\'image pour revenir au menu.' : 'Click on the image to return to the menu.')
        	  var closeBox = new Element('div', { id: 'closeBox', style: 'display: none' }).update(text);
      	      Element.insert(document.body, {bottom: closeBox});
          }

          $('descriptionBox').appear({duration: 0.4});
          $('closeBox').appear({duration: 0.4});
    	}
    })
  }
}





/** *** TOOLS ***** */

function getWindowHeight() {

    var windowHeight = 0;

    if (typeof(window.innerHeight)=='number') {
        windowHeight = window.innerHeight;
    } else {
        if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
        } else {
            if (document.body && document.body.clientHeight) {
                windowHeight = document.body.clientHeight;
            }
        }
    }
    
    return windowHeight;
}

function getWindowWidth() {

    var windowWidth = 0;

    if (typeof(window.innerWidth)=='number') {
        windowWidth = window.innerWidth;
    } else {
        if (document.documentElement && document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            if (document.body && document.body.clientWidth) {
                windowWidth = document.body.clientWidth;
            }
        }
    }
    
    return windowWidth;
}
