/* Author:  Louis-André Labadie for Ockam
            www.ock.am
*/

$( function() {

  var displayedPageName = "",
  		currentPage = "#accueil",
  		currentServicesPage = false,
  		contactIsOpen = false,
  		currentProject = false,
      theDuration = 800,
      theEasing = {easing:'easeInOutQuad'},
      carouselWidth = 0,
      loadedProjectImages = 0,
      smallImageHeight = 200,
      bigImageHeight = 500,
      sc = document.getElementById('portfolio-container'),
      co = document.getElementById('carousel'),
      timerSet = false;

  /*
  	Giving the right width to carouselWidth
  	& storing it for the sliding script
  */

  $(window).load(
    function() {
    		$('#carousel li img').each( function() {
  					carouselWidth += this.width + 10;
  					});
        $('#portfolio #carousel').css("width", carouselWidth + 'px');
    	}
		);

  /*
  	Binding the IDs to rel tags to avoid fustercluck
  	Also, assigning behaviors to page change links
  */

  function relPlz(){
  	for (var i=0;i<arguments.length;i++) {
  		$(arguments[i].toString()).each(function() {
  			$(this).attr('rel', $(this).attr('href')).removeAttr('href');
  		})
  	};
  };

  relPlz('a.page-link', 'a.tab-link', 'a.contactToggle', 'a.project-link');


  /*
  	Assigning the main nav's links
  */


	$('a.page-link').each(function() {
		$(this).bind("click", function() {
			changePage($(this).attr('rel'))
			})
	});

	$('#profil-francedrolet').bind( "click", function() {
		toggleFrance()
	});

	$('#services a.tab-link').bind( "click", function() {
		toggleServices($(this).attr('rel'))
	});

	$('a.contactToggle').bind( "click", function() {
		toggleContactInfo()
	});

	$('a.project-link').each(function() {
		$(this).bind("click", function() {
			showProject($(this).attr('rel'))
			})
	});
	$('#navinfo a.portfolio-toggle').live("click", function() {
		changePage('#portfolio');
	});
	$('#navinfo a.page-retour').live("click", function() {
		closeTabs(currentPage);
	});



	// For .page-link buttons

	function changePage(pagetoGo){
		if(pagetoGo != currentPage) {
			if(currentPage!="#accueil"){
					$(currentPage).stop().animate({ top: "-545px" }, 600)
				};
			if(pagetoGo!="#accueil"){
					$(pagetoGo).stop().animate({ top: "0px" }, 600)
				};
			if(pagetoGo!="#portfolio"){
					$('#accueil').fadeIn();
					$('#page-projet').html('').fadeOut();
					currentProject = false;
				};
			currentPage = pagetoGo;
			}
		else if( currentProject && pagetoGo=="#accueil" ) {
				$('#accueil').fadeIn();
				$('#page-projet').html('').fadeOut();
				currentProject = false;
		}

		else {
			if(currentProject){
				nameActivePage('<a class="portfolio-toggle">Portfolio</a>&emsp;<strong>' + currentProject + '</strong>');
				currentPage = "#portfolio";
			}
			if(currentPage!="#accueil"){
				$(currentPage).stop().animate({ top: "-545px" }, 600);
			}
			currentPage = "#accueil";
			};
		if(contactIsOpen){toggleContactInfo()};
		if(!currentProject){nameActivePage('<a class="page-retour">' +currentPage.substr(1) + '</a>')};
		$('nav a.page-link').removeClass('active');
		$('nav a.page-link[rel="' + currentPage + '"]').addClass('active');
	};

	// Closing the tabs when the user clicks a page's title (profil, services)

	function closeTabs(pageName) {
		switch(pageName){
			case '#profil' :
				if($('#profil-francedrolet').is('.toggled')) {toggleFrance() };
				break;
			case '#services' :
				toggleServices(currentServicesPage);
				break;
		}
	}

	// To change the active page in the navinfo, "accueil" changes to whitespace automatically

  function nameActivePage(newName){
  	newName = (newName=='<a class="page-retour">accueil</a>'? "&nbsp;" : newName);
  	$('#page-name').stop(1,1).fadeOut(200, function(){
  		$('#page-name').html(newName).fadeTo(200, 1);
  	})
  };

  // For .tab-link buttons

  function toggleFrance(){
		var hasToOpen = $('#profil-francedrolet').is('.toggled') ? false : true;

		// Assigning the "toggled" class
		if(hasToOpen){ $('#profil-francedrolet').addClass('toggled') } else { $('#profil-francedrolet').removeClass('toggled') };

		//Animation
  	$('#profil-francedrolet').stop().animate( {
  		left : ( hasToOpen ? "0px" : "820px" ),
  		backgroundPositionX : ( hasToOpen ? "0px" : "-200px" ) } , 600);
  	$('#profil-francedrolet a.tab-link').stop().animate( { left : ( hasToOpen ? "875px" : "80px" ) } , 600);
  };

  // The Services page, deciding which tabs has to be large by using an index

  function toggleServices(clickedPage){
  	var positionsToChange = Array();

  	if(clickedPage==currentServicesPage){
  		positionsToChange=0;
  		currentServicesPage = false ;
  		}
  	else{
  		switch(clickedPage){
  			case"#services-commercial":
  				positionsToChange=1;
  				break;
  			case"#services-corporatif":
  				positionsToChange=2;
  				break;
  			case"#services-restauration":
  				positionsToChange=3;
  				break;
  			}
  			currentServicesPage = clickedPage;
  		}
  	$('#services-commercial').stop().animate({
  		left : ( positionsToChange >0 ? "0px" : "825px"),
  		backgroundPositionX : ( positionsToChange >0 ? "45px" : "-825px")
  		}, 600);
  	$('#services-corporatif').stop().animate({
  		left : ( positionsToChange >1 ? "45px" : "870px"),
  		backgroundPositionX : ( positionsToChange >1 ? "45px" : "-825px")
  		}, 600);
  	$('#services-restauration').stop().animate({
  		left : ( positionsToChange >2 ? "90px" : "915px"),
  		backgroundPositionX : ( positionsToChange >2 ? "45px" : "-825px")
  	}, 600);
  }

  //Toggling Contact

  function toggleContactInfo() {
  	$('#navinfo-wrap').stop().animate({height : (contactIsOpen?"50px":"182px")}, 300);
  	$('#navinfo #contactinfo').stop().animate({marginTop : (contactIsOpen?"50px":"0px")}, 300);
  	if(!contactIsOpen){changePage(currentPage)};
  	contactIsOpen = !contactIsOpen;
  	$('nav a[rel="#contact"]').toggleClass('active');
  };

  // -------------------- Shiny new JS animation & handling all that happens in the portfolio ----------------------------- //

	$('.carousel-image a').each(function() {
		$(this).mouseover(function() {
			highlightClient(this);
			$(this).addClass("hovered");
		})		
		$('#carousel, .left-fade, .right-fade').hover(function() {
				moveCarousel();
			},
			function() {
				timerSet = false;
				window.clearInterval(carouselMoveTimer);
			}
		);
	});
	
	sc.onmouseover = function(){
  		if(!timerSet) {
  			window.carouselMoveTimer = setInterval("carouselMoveCycle()",20);
  			timerSet = true;
  			
  			sc.onmousemove = function(e){
  			
  					if(!e){var e = window.event};
  			  					
  					if (e.pageX) 	{
  						posx = e.pageX;
  					}
  					
  					else if (e.clientX || e.clientY) 	{
  						posx = e.clientX + document.body.scrollLeft
  							+ document.documentElement.scrollLeft;
  					}
  					
  					// posx and posy contain the mouse position relative to the document
  					
  					window.cMouseX = posx - this.offsetLeft;
  			};
  		};
 	};
  	
	sc.onmouseout = function() {
  		timerSet = false;
  		window.clearInterval(carouselMoveTimer);
  		sc.onmousemove = null;
  };
    
  //Really needs this, sorry:
  document.getElementById('ugly-nonsemantic-container').onmouseover = sc.onmouseover;

	window.carouselMoveCycle = function () {
  		var currentLeft = co.offsetLeft,
  		    maxLeft = sc.offsetWidth - co.offsetWidth,
  				mX = window.cMouseX;
  		  		  		  		
  		var xD = Math.floor((mX - (sc.offsetWidth/2)) / (sc.offsetWidth * 0.05) );
  		  		
  		if( xD > 0 ) { xD-- } else if ( xD < 0 ) { xD++ };
  		  		  				
  		var newLeft = currentLeft - xD;
  		
  		if (newLeft > 0) { newLeft = 0 };
  		if (newLeft < maxLeft) { newLeft = maxLeft };
  		  		
  		co.style.left = newLeft + "px";
  };
	
  // -------------------- Done with the portfolio's sliding pictures ----------------------------- //

	
  /*
function moveCarousel(event){
  	//if(carouselMoveAllowed){
  	//var carouselMoveTimer = setTimeout("carouselMoveAllowed = true",100);
  	//carouselMoveAllowed = false;

  	var posX = event.pageX - $('#portfolio h3').offset().left - 120;
  	var totalWidth = carouselWidth - 840;

  	var leftAttr = totalWidth * (posX / 840);

  	leftAttr = leftAttr < 0 ? 0 : leftAttr;
  	leftAttr = leftAttr > totalWidth ? totalWidth : leftAttr;

  	//$('#carousel').stop().animate({"left": -leftAttr}, { "duration": 2200, "easing": "easeOutQuad" });
  	$('#carousel').css({"left": -leftAttr});
  	};
 //	};
*/

 	function highlightClient(thePicture) {
 		$('.liste-clients a').removeClass('hovered');
 		$('.liste-clients a[rel="' + $(thePicture).attr('rel') + '"]').addClass('hovered');
 	}

// Handling the project page change

	function showProject(projectID){
		$('#accueil').fadeOut();
		changePage('#portfolio');
		nameActivePage('<a class="portfolio-toggle">Portfolio</a>&emsp;<strong>' + projectID + '</strong>');
		currentProject = projectID;

		var images = storedProjects[projectID];
		var numberOf = images.length;
    $('#page-projet').show().html('').append('<div class="page"><ul id="project-viewer"></ul></div>');
		var viewerWidth = 0;
		var firstImage = true;

		loadImage(0);

		function loadImage(i){
			var theImage = images[i].substr(0, images[i].lastIndexOf('.')) + '_lg' + images[i].substring(images[i].lastIndexOf('.'));
			$('#page-projet #project-viewer').append('<li><img src="" /></li>');

			//On each loaded image, add its width to the viewer and load the next one


			$('#page-projet #project-viewer li:last-child img').load(function() {
					viewerWidth += (this.width + 15);

					$('#project-viewer').width(viewerWidth);

					if(i>0) {
							smallen(this)
						};

					if(i+1 < numberOf) { // load the next if there is one
							loadImage(i+1);
						};

			}).attr('src', ('/medias/img/gallery/' + theImage));

			$('#project-viewer img').live('click', function() {
					smallen($('#project-viewer img'));
					biggen(this);
			})
		};
	};

	function smallen() {
		for (var i=0;i<arguments.length;i++) {
  		$(arguments[i]).each( function() {
  			$(this).stop().animate({"height" : smallImageHeight}, 100 ).addClass('small');
  		});
  	};
	};

	function biggen() {
		for (var i=0;i<arguments.length;i++) {
  		$(arguments[i]).each( function() {
  			$(this).stop().animate({"height" : bigImageHeight}, 100,
  				function() {
						var neededOffset = $(this).offset().left - $(this).offsetParent().offset().left;
						$('#project-viewer').stop().animate({"left": -neededOffset + 'px'}, 300);
  				}
  			 ).removeClass('small');
  		});
  	};
	};

});




