/* Author: GRAMM Développement 
   www.gramm.pro / 2011
*/

var isAccueil = false;

$(document).ready(function() {

	/*
	$("a.open").oneTime("3s", function() {
    	$('#nav-container').slideDown('slow');
		$(this).hide();
		$('h1.logo').animate({top:86}, 600);
	});	
	*/
	$.scrollTo( 0 );
	$('html').localScroll();
	
	$('#nav-container a.close').click(function(e){
		$('#nav-container').slideUp('slow', function(){
			$('a.open').show();		
		});

		$('h1.logo').animate({top:0}, 600);
		e.preventDefault();
	});

	$('a.open').click(function(e){
		$('#nav-container').slideDown('slow');
		$(this).hide();
		$('h1.logo').animate({top:86}, 600);
		e.preventDefault();
	});	

	/* Démarrage du diaporama */
	init_diaporama();
	/* Dernier article du Blog */
	init_feed();
	
	var viewport = $('#viewport');
	
	$('.nav a').live('click', function(e){
		e.preventDefault(); 
		
		if ($(this).hasClass('current')) return;
		$('.nav a').toggleClass('up','down');
		$('.nav a').removeClass('current');
		$(this).addClass('current');
		
		if($(this).attr('href') == '#!/contact')
			$('body').addClass('cat-contact');
		
		var content = $('#container');
		var direction = $(this).hasClass('up') ? 'up' : 'down';
		var exitFinished = false;
		var url = $(this).attr('href').replace(/#!/, '');
		
		var accueil = 'false';
		if($(this).hasClass('accueil')) { 
			isAccueil = true; 
			$('#nav-design').animate({top:455}, 600);
		}else
			$('#nav-design').animate({top:80}, 600);
		
		$('#diaporama').stopTime().slideUp('slow');
		$.ajax({
			url: 'http://www.studiolautrec.fr' + url + '?v1',
			dataType: 'html',
			success: function (text, status, request) {
			
				function insertNewPage() {
					if (!exitFinished) {
						return window.setTimeout(insertNewPage, 10);
					}
					viewport.html('');
					var newHeight = 1500;

					viewport.append(text);
					
					if ('down' == direction) {
						$('#container').css({top: viewport.height()});
					} else {
						$('#container').css({top: - newHeight});
					}
					
					$('#container').css({visibility: 'visible'}).animate({top: 0}, 600);

					viewport.animate({height: newHeight});

					init_pages();
					init_diaporama();
					
					if(isAccueil){
						init_feed();
						isAccueil = false;
					}
				}			
				insertNewPage();
				
				/* Stats Google */
				if (typeof(_gaq) != 'undefined')
					_gaq.push(['_trackPageview', url]);
			},
                error:function (xhr, ajaxOptions, thrownError){
                    //alert(xhr.status);
                    if(xhr.status == '404')
                    	$('.nav a[href=#!/home]').click();
                } 
		});// End AJAX

			var contentHeight = 2069;
			var targetHeight = 2069;
			viewport.height(contentHeight);
			content.css({position: 'relative', height: contentHeight});
			var targetTop;
			if ('down' == direction) {
				targetTop = 0 - contentHeight;
			} else {
				targetTop = targetHeight;
			}
			$('footer').hide();
			content.animate({top: targetTop}, 600, function () {
				$(this).hide().remove();
				exitFinished = true;
			});
			
			window.location.hash = '!' + url;	
					
	});
		
		if (window.location.hash && window.location.hash != '#') {
			var url = window.location.hash.match(/#!?(.*)/)[1];
			$('.nav a[href=#!'+url+']').click();
		}
		
});

function init_feed(){
/* Dernier article du Blog */
	jQuery.getFeed({
        url: 'proxy.php?url=http://www.studiolautrec.fr/blog/feed/',
        success: function(feed) {

            var html = '';
               var months = {'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04', 'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'};
               var item = feed.items[0];
               var date = item.updated.split(' ');
               var datePrint = date[1]+' / '+months[date[2]];
               html += '<h2>'+item.title+'</h2>'
			    + '<div class="text">'
			    + item.description
			    + '<span class="date"><small>Publié le</small><br/>'+datePrint+'</span>'
			    + '<a href="'+item.link+'" title="'+item.title+'" target="_blank">'
			    + '<img src="images/dans-le-blog.png" alt="Dans le blog Studio Lautrec" style="float:right;" /></a>'
			    + '<a href="http://www.studiolautrec.fr/blog/" title="Blog Studio Lautrec" target="_blank" class="ir link-blog">+ d\'information</a>'
				+ '</div>';
			
			$('#lastNewsfromBlog').empty();	
			$('#lastNewsfromBlog').prepend(html).fadeIn('slow');	
		}
	});
}

function init_pages(){

	$('footer').hide().delay(800).fadeIn();
	
	if($('body').hasClass('cat-contact')){
	  $("#contactForm").live('submit', function(event) {
	
	    // stop form from submitting normally
	    event.preventDefault(); 
	        
	    // get some values from elements on the page:
	    var $form = $( this ),
	        nom = $form.find( 'input[name="name"]' ).val(),
	        message = $form.find( 'textarea[name="infos"]' ).val(),
	        subject = $form.find( 'input[name="objet"]' ).val(),
	        mail = $form.find( 'input[name="email"]' ).val(),
	        url = $form.attr( 'action' );
	
	    // Send the data using post and put the results in a div
	    $.post( 'http://www.studiolautrec.fr/'+url, { name: nom, email: mail, objet: subject, infos: message } ,
	      function( data ) {
	          //var content = $( data ).find( '#container' );
	          $( "#container" ).html( data );
	      }
	    );
	  });
	}
}

function init_diaporama(){

	/* Pré-chargement des images */

	var hp_images = new Array();
	
	var li_index = 0;	
	var max = $('#diaporama').children().size();
	
	for(var i=li_index; i<max; i++){
		hp_images.push($('#diaporama li:eq('+i+')').children('img').attr('src'));
	}
	
	$.imgpreload(hp_images,function(){

		$('<div id="zoom"></div>').insertBefore('#diaporama').fadeIn('slow');
	    //$('<div id="descZoom"><span></span><div class="desc"></div></div>').insertBefore('#diaporama');
	    
	      $('#diaporama li').click(function(e){
			click_zoom($(this));
	      	/*$("#diaporama").stopTime(); */    	
	      	e.preventDefault();
	      });
	
	      $('#prev').click(function(e){
	      	if($('#diaporama li.current').index() <= 0) return;
			click_zoom($('#diaporama li.current').prev('li'));    	
	      	e.preventDefault();
	      });
	      
	      $('#next').click(function(e){
	      	if($('#diaporama li.current').index() + 1 >= $('#diaporama').children().size()) return;
			click_zoom($('#diaporama li.current').next('li'));   	
	      	e.preventDefault();
	      });

	    $('#diaporama li:eq('+li_index+')').addClass('current');
	    $('#diaporama li:eq('+li_index+')').children('img').clone().appendTo('#zoom');
		var title = $('#diaporama li:eq('+li_index+')').children('img').attr('title');
		$('#legend').append('<strong>'+title+'</strong>');
		var desc = $('#diaporama li:eq('+li_index+')').children('img').attr('alt');
		$('#legend').append('<p>'+desc+'</p>');
		var url = $('#diaporama li:eq('+li_index+')').children('img').attr('data-desc');
		if(typeof(url)!="undefined") {
			
			/* Détecter les url Viméo */
			var regExp = /vimeo.com\/(\d+)($|\/)/;
			
			var match = url.match(regExp);
			if (match){
			    /* Ajouter un bouton "Play" et init. Fancybox */
			    $('#zoom').append('<a id="play_movie" href="#video" title="Voir la vidéo"><img src="images/fleche_blanche.png" alt="lire la vidéo"/></a>');
			    $('<div id="video_container"><div id="video"><iframe src="http://player.vimeo.com/video/'+match[1]+'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1&amp;color=0000FF" width="601" height="338" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe></div></div>').insertBefore('#diaporama');
			    $('#video_container').hide();
			    
			    $('#play_movie').fancybox({
			    	'overlayColor' : '#000',
			    	'overlayOpacity': '0.6',
			    	'titleShow': false,
			    	'showCloseButton':false,
			    	'padding': 0
			    });
			    
			}else{
			   $('#legend').append('<p>Voir le site : <a target="_blank" href="http://'+url+'" title="">'+url+'</a></p>');
			}
	
		}
			
		$('#prev').addClass('off');
		
		/*		
		$("#diaporama").everyTime("5s",function() {
	
			li_index++;
			
			if(li_index >= max){ 
				li_index = 0;
			}
			
			click_zoom($("#diaporama li:eq("+li_index+")"));
			show_descTitle($("#diaporama li:eq("+li_index+")"));
		});
		*/
		
		/* Slide box Diaporama */
		$('#descZoom').hover(function(){
			$('#descZoom div').stop(true, false).animate({ height: "208px" });
		}, function(){
			$('#descZoom div').stop(true, false).animate({ height: "17px" });
		});
	
	});	
}

	function click_zoom(obj, image){
		$('#zoom').empty();
		
		if(image == true){
		 var img = '<img src="'+$(obj).attr("href")+'" alt="" />';
		 if ($.browser.msie) {
		 	$(img).appendTo('#zoom');
		 }
		 else
		 	$(img).appendTo('#zoom').fadeIn('slow');
		}
		else {
			if ($.browser.msie)
				$(obj).children('img').clone().hide().appendTo('#zoom').show();
			else
      			$(obj).children('img').clone().hide().appendTo('#zoom').fadeIn('slow');
      	}
      	$(obj).siblings().removeClass('current');
      	$(obj).addClass('current');
      	
		if($(obj).index()+1 >= $('#diaporama').children().size()){
			$('#next').addClass('off');
		}else $('#next').removeClass('off');
		
		if($(obj).index()+1 > 1){
			$('#prev').removeClass('off');
		}else $('#prev').addClass('off');
		
		show_descTitle(obj);		     	
	}
	
	function show_descTitle(obj){
		$('#legend').empty();
		var title = $(obj).children('img').attr('title');
		$('#legend').append('<strong>'+title+'</strong>');
		var desc = $(obj).children('img').attr('alt');
		$('#legend').append('<p>'+desc+'</p>');
		var url = $(obj).children('img').attr('data-desc');
		if(typeof(url)!="undefined") {
		
		/* Détecter les url Viméo */
		var regExp = /vimeo.com\/(\d+)($|\/)/;
		
		var match = url.match(regExp);
		if (match){
		    /* Ajouter un bouton "Play" et init. Fancybox */
		    $('#zoom').append('<a id="play_movie" href="#video" title="Voir la vidéo"><img src="images/fleche_blanche.png" alt="lire la vidéo"/></a>');
		    $('#video_container').remove();
		    $('<div id="video_container"><div id="video"><iframe src="http://player.vimeo.com/video/'+match[1]+'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1&amp;color=0000FF" width="601" height="338" frameborder="0" webkitAllowFullScreen allowFullScreen></iframe></div></div>').insertBefore('#diaporama');
		    $('#video_container').hide();
		    
		    $('#play_movie').fancybox({
		    	'overlayColor' : '#000',
		    	'overlayOpacity': '0.6',
		    	'titleShow': false,
		    	'padding': 0
		    });
		    
		}else{
		   if(url.length)
		   $('#legend').append('<p>Voir le site : <a target="_blank" href="http://'+url+'" title="">'+url+'</a></p>');
		}

		}		
	}
