/*================================================== GLOBAL JAVASCRIPT */
/*
Javascript Document for juliendecaudin.com
By Julien Decaudin - 01/05/2009
*/

$('html').addClass('js');

/************* GLOBAL VARIABLES *************/
/* LOGO */
var logoHoverSpeed = 400;
var logoBlurSpeed = 200;

/* CONNECT SLIDE */
var flagconnectOpen = false;
var flagconnectLinkOver = false;
var connectLinkHoverSpeed = 200;
var connectOpenSpeed = 300;
var connectCloseSpeed = 800;
var connectCloseOffset = "";
var connectIntLinkOverSpeed = 100;
var connectIntLinkOutSpeed = 250;

/* PROJECTS THUMBNAILS */
var flagThumbOpen = false;
var thumbTimer;
var thumbTimerDuration = 1000;
var thumbOpenSpeed = 200;
var thumbCloseSpeed = 400;
var thumbCloseOffset = "";
var thumbListBg;

/* PROJECTS NAVIGATION */
var navLinkHoverSpeed = 200;
var currentProjectPosition = 0;
var projectOffset = 623;
var projectSlideSpeed = 250;
var projectLocked = false;
var totalProjects = 0;
var lastProject = false;
var hashProject = "";

/* EXPERTISES */
var expTimer;
var expTimerDuration = 2000;

$(document).ready(function() {
    /*////////////////////////////////////// INIT */
    connectCloseOffset = $('#connect').css('marginLeft');
    thumbCloseOffset = $('#thumbnails_bg ul').css('marginTop');
    thumbListBg = $('#thumbnails_bg ul');    

	//Init Contact smooth scroll
	$('#connect, .home_copy, #footer').localScroll();

    //Init projects
    totalProjects = $('div.project').length;
    var projectListMarginLeft = $('#projects').css('marginLeft').split('px')[0];
    $('.project').each(function(n) {
        var offset = -(n * projectOffset) + parseInt(projectListMarginLeft);
        if (n == 0) {
            offset = projectListMarginLeft;
        }
        $(this).data("offset", offset);        
        $(this).data("position", n + 1);        
    });        
    
    //Init Contact form    
	var options = { 
		url: '/', // Here we pass the xhr flag
        dataType:  'json', 
		success:   processJson, //What to call after a reply from Django
		beforeSubmit: beforeForm
	};
    // bind form using ajaxForm 
    $('#contact_form').ajaxForm(options);

	//Load a specific project if anchor link url detected
	hashProject = window.location.hash;
	if(hashProject != ''){
		//console.log('load:' + hashProject);				   
		//console.log($('#page').offset().left);		
	    var projectToLoadPosition = parseInt($(hashProject , '#projects').data('position')) - 1;
	    //console.log(window.pageYOffset);
	    if(projectToLoadPosition){
	    	//$(window).scrollTo(0,0);
	    	if(LoadProject(projectToLoadPosition)) currentProjectPosition = projectToLoadPosition;	
	    }	    
	}

    /*////////////////////////////////////// INTERACTIONS */
    /* ====================== LOGO ROLLOVER */
    $('#logo h1 a').hover(
      function() {
          $(this).css({ backgroundImage: "none" });
          $(this).append('<div></div>');
          $(this).find('div').stop().fadeIn(logoHoverSpeed);
      },
      function() {
          $(this).find('div').stop().fadeOut(logoBlurSpeed, function() {
              $(this).remove();
          });
      }
    );

    /* ====================== CONNECT SLIDE */
    $('#connect_link_container').hover(function() {
        if (!$('#connect').hasClass('opened')) {
            RollOverConnectLink();
        }
    }, function() {
        if (!$('#connect').hasClass('opened')) {
            RollOutConnectLink();
        }
    });

    $('#connect_link_container').mousedown(function() {
        if ($('#connect').hasClass('opened')) {
            //Close connect
            CloseConnectContainer();
        } else {
            //Open connect
            OpenConnectContainer();
        }
        return false;
    });

    $('#logo h1').click(function() {
        return false;
    });
    
    //Display the Intro
    $('#logo h1').mousedown(function() {
        if(LoadProject(0)) currentProjectPosition = 0;        
    });
    
    //Internal connect links rollover
    $('#connect_content ul li a')
    	.css({backgroundPosition: "0 -43px"})
	    .hover(function() {    
	    	var bg_icon = $(this).find('span');
	    	
	        bg_icon.stop().animate({        	
	            backgroundPosition: "(0 0)"
	        }, connectIntLinkOverSpeed, 'linear');        
	    }, function() {
	    	var bg_icon = $(this).find('span');
	    	
	        bg_icon.stop().animate({        	
	            backgroundPosition: "(0 -43px)"
	        }, connectIntLinkOutSpeed, 'linear');        
	    });

    $(document).bind('mousedown', function(e) {
        var target = $(e.target);

        //Close connect if clicked outside of the connect box
        if (!(target.is('#connect') || target.parents('#connect').length) && flagconnectOpen) {
            CloseConnectContainer();
        }
    });

    /* ====================== PROJECTS THUMBNAILS */
    $('#thumbnails_front').hover(function() {
        //Open
        window.clearTimeout(thumbTimer);
        OpenProjectThumbs();
    }, function() {
        //Close        
        if(flagThumbOpen){
        	thumbTimer = window.setTimeout('CloseProjectThumbs()', thumbTimerDuration);	
        }else{
        	CloseProjectThumbs();	
        }                
    });

    $('#thumbnails_front li a').hover(function() {
        var projectTitle = $(this).attr('title');
        $('#thumbnails_title_panel').text(projectTitle);
        
        var projectId = $(this).attr('href').split('#')[1];
        var thumbBg = $('#thbg_' + projectId).find('img');
        
        thumbBg.stop().animate({
	            paddingTop: "4px"
	        }, 100);
        
    }, function() {
    	var projectId = $(this).attr('href').split('#')[1];
        var thumbBg = $('#thbg_' + projectId).find('img');
        
        thumbBg.stop().animate({
	            paddingTop: "0"
	        }, 300);    	
    });
    
	$('#thumbnails_front li a').click(function(){ return false; });

    $('#thumbnails_front li a').mousedown(function(){
    	if(!projectLocked){
	    	var projectToLoadId = $(this).attr('href');    
	    	var projectToLoadPosition = parseInt($(projectToLoadId , '#projects').data('position')) - 1;
	    	
	    	if(LoadProject(projectToLoadPosition)) currentProjectPosition = projectToLoadPosition;    	
	    	//console.log(projectToLoadPosition);	
    	}    	
    	return false;
    });

    /* ====================== PROJECTS NAVIGATION */
    $('#link_previous')
    	.css({backgroundPosition: "-75px 0"})
	    .hover(function() {
	        if (currentProjectPosition > 0) {
	            $('#link_previous_bg').stop().animate({
	                backgroundPosition: "(0 0)"
	            }, navLinkHoverSpeed);
	        }
	    }, function() {
	    	if (currentProjectPosition > 0) {
		        $('#link_previous_bg').stop().animate({
		            backgroundPosition: "(-75px 0)"
		        }, navLinkHoverSpeed);
		    }else{
		    	$('#link_previous_bg').animate({
		            backgroundPosition: "(-75px 0)"
		        }, navLinkHoverSpeed);
		    }
	    });

    $('#link_next')
    	.css({backgroundPosition: "0 0"})
	    .hover(function() {
	    	if(!lastProject){
		        $('#link_next_bg').stop().animate({
		            backgroundPosition: "(-75px 0)"
		        }, navLinkHoverSpeed);
		    }
	    }, function() {
	    	if(!lastProject){
		        $('#link_next_bg').stop().animate({
		            backgroundPosition: "(0 0)"
		        }, navLinkHoverSpeed);
		    }else{
		    	$('#link_next_bg').animate({
		            backgroundPosition: "(0 0)"
		        }, navLinkHoverSpeed);
		    }  
	    });


    $('#link_next').mousedown(function() {
        if (!projectLocked && !lastProject) {
            if(LoadProject(currentProjectPosition + 1)) currentProjectPosition++;
        }
    });

    $('#link_previous').mousedown(function() {
        if (!projectLocked && currentProjectPosition > 0) {
            if(LoadProject(currentProjectPosition - 1)) currentProjectPosition--;
        }
    });

    $('#link_next, #link_previous').click(function() {
        return false;
    });   
    
    $('#link_previous').hide();
	$('#link_previous_bg').hide();    
	
	/* ====================== TOP LINK */
	$('#link_top')
    	.css({backgroundPosition: "0 9px"})
	    .hover(function() {    	    		
	        $(this).stop().animate({        	
	            backgroundPosition: "(0 0)"
	        }, connectIntLinkOverSpeed, 'linear');        
	    }, function() {	    	
	        $(this).stop().animate({        	
	            backgroundPosition: "(0 9px)"
	        }, connectIntLinkOutSpeed, 'linear');        
	    });

	
	/* ====================== EXPERTISES */
	$('#areaexp_container a').hover(function(){
		window.clearTimeout(expTimer);
		var desc = $(this).find('+ span').text();
		$('#areaexp_description').html('<p>' + desc + '</p>');
		expTimer = window.setTimeout('TagExpertise("' + $(this).attr('id') + '")', expTimerDuration);
	}, function(){
		window.clearTimeout(expTimer);
		$('#areaexp_description').empty();
	});
});

/*////////////////////////////////////// EXPERTISES */
function TagExpertise(linkId){
	//console.log(link.attr('href'));
	$('#' + linkId).attr('class', 'tagged');
}

/*////////////////////////////////////// PROJECTS */
function UpdateLinkPrevious(projectPosition){
	if(projectPosition == 0){
		$('#link_previous').hide('fast', function(){
			$('#link_previous_bg').fadeOut('slow');
		});		
	}else if($('#link_previous:hidden').length > 0){
		$('#link_previous').show('fast', function(){
			$('#link_previous_bg').fadeIn('slow');
		});		
	}
}

function UpdateLinkNext(){
	if(lastProject){
		$('#link_next').hide('fast', function(){
			$('#link_next_bg').fadeOut('slow');
		});		
	}else if($('#link_next:hidden').length > 0){
		$('#link_next').show('fast', function(){
			$('#link_next_bg').fadeIn('slow');
		});		
	}
}

function LoadProject(projectPosition) {
    projectLocked = true;
    //console.log('current:' + currentProjectPosition + ', toload:' + projectPosition);
    
    if(projectPosition != currentProjectPosition){
		var projectToLoad = $('#projects div.project:eq(' + projectPosition + ')');
		var thumbFrontCurrent = $('#thumbnails_front li a[href=#' + projectToLoad.attr('id') + ']');
	
		//Disable current project
	    $('div.current_project').find('div.home_copy, div.project_copy').stop().hide();
	    $('div.current_project').find('ul.project_images').stop().hide();
	    $('div.current_project').removeClass('current_project').addClass('disabled_project');	
	
		//Update thumbnail current state
		$('#thumbnails_front a').removeClass('current');
		$('#thumbnails_front a').removeClass('highlight');
		thumbFrontCurrent.addClass('current');
		if(flagThumbOpen) thumbFrontCurrent.addClass('highlight');
	
	    //Slide projects
	    $('#projects').animate({
	        marginLeft: projectToLoad.data("offset")
	    }, projectSlideSpeed, "swing", function() {	        
	        projectToLoad.removeClass('disabled_project');
	        
	        //Update the date
	        $('#year').text(projectToLoad.find('p.project_year').text());
	        
	        //Reveal the project content
	        projectToLoad.find('ul.project_images').slideDown('fast');
	        projectToLoad.find('div.home_copy, div.project_copy').slideDown('fast', function() {
	        	projectToLoad.addClass('current_project');
	            projectLocked = false;            
	        });        	        
	    });		
	    
	    //Flag if this is the last project
	    if(projectToLoad.data("position") == totalProjects){
	    	lastProject = true;	    		    		    	
		}else{
			lastProject = false;			
		}
		UpdateLinkPrevious(projectPosition);
		UpdateLinkNext();
		return true;   	
    }else{
    	projectLocked = false;   
    }
    return false;        
}

/*////////////////////////////////////// CONNECT BOX */
function RollOverConnectLink() {
    flagconnectLinkOver = true;

    //connect link rollover
    $('#connect_link').stop().animate({
        backgroundPosition: "(0 0)"
    }, connectLinkHoverSpeed);

    //bars motion
    $('#connect_link_bar_front').stop().animate({
        left: 10
    }, connectLinkHoverSpeed);
    $('#connect_link_bar_back').stop().animate({
        left: 20
    }, connectLinkHoverSpeed);
}

function RollOutConnectLink() {
    flagconnectLinkOver = false;

    //bars motion
    $('#connect_link_bar_back').stop().animate({
        left: 0
    }, connectLinkHoverSpeed);
    $('#connect_link_bar_front').stop().animate({
        left: 0
    }, connectLinkHoverSpeed);

    //connect link rollover out
    $('#connect_link').stop().animate({
        backgroundPosition: "(-11px 0)"
    }, connectLinkHoverSpeed);
}

function OpenConnectContainer() {

    if (!flagconnectLinkOver) {
        RollOverConnectLink();
    }

    $('#connect').addClass('opened');

    //Hide the link bars
    $('#connect_link_bar_back').stop().animate({
        left: 0
    }, connectLinkHoverSpeed);
    $('#connect_link_bar_front').stop().animate({
        left: 0
    }, connectLinkHoverSpeed);

    //Open the panel
    $('#connect').animate({
        marginLeft: "0px"
    }, connectOpenSpeed, function() {
        flagconnectOpen = true;
    });
}

function CloseConnectContainer() {
    //Close the panel
    $('#connect').animate({
        marginLeft: connectCloseOffset
    }, connectCloseSpeed, function() {
        $('#connect').removeClass('opened');
        flagconnectOpen = false;

        //Return connect link to default state
        RollOutConnectLink();
    });
}

/*////////////////////////////////////// PROJECTS THUMBNAILS */
function OpenProjectThumbs() {
    thumbListBg.stop().animate({
        marginTop: 0
    }, thumbOpenSpeed, function() {        
        $('#thumbnails_title_panel').slideDown('fast');
        flagThumbOpen = true;
    });
    
    $('#thumbnails_front a').stop().animate({
		backgroundPosition: "(0 0)"
	}, thumbOpenSpeed + 50);		
}

function CloseProjectThumbs() {
    thumbListBg.stop().animate({
        marginTop: thumbCloseOffset
    }, thumbCloseSpeed, function() {        
    	flagThumbOpen = false;
    });
    $('#thumbnails_title_panel').slideUp('fast');
    
    $('#thumbnails_front a').stop().animate({
		backgroundPosition: "(0 -30px)"
	}, thumbCloseSpeed + 50);			
}

/*////////////////////////////////////// CONTACT FORM */
function beforeForm() { 
	$('#submit').attr("disabled","disabled"); //Disable the submit button - can't click twice
	$('span.error').remove(); //Get rid of any old error uls
	$('#submit_message').hide(); //Get rid of the main error message
	return true; //Might not need this...
}

function processJson(data) { 
	//Do we have any data at all?
	if (data) {
		e_msg = "Your message has been submitted, thank you.";
		// Did we set the 'bad' flag in Django?
		// Use eval() to turn the stuff in the data object into actual vars.
		if (eval(data.bad)) {
			e_msg = "Please check and try again.";
			errors = eval(data.errs); //Again with the eval :)
			// Go thru the errors, build an id name and
			// then access that tag and add the HTML from the Django error
			$.each(errors,function(fieldname,errmsg)
			{
				id = "id_" + fieldname;
				$('label[for=' + id + ']').after("<span class='error'>" + errmsg + "</span>");
			});
			// re-enable the submit button, coz user has to fix stuff.
			$('#submit').attr("disabled","");
		}else{
			//data submitted: clear the form			
			$('#contact_form fieldset input').val('');
			$('#contact_form fieldset textarea').val('');			
		}
		//Show the message
		$('#submit_message').text( e_msg ).show();
	} else {
		$('#submit_message').text("Ajax error : no data received. ").fadeIn("slow");
	}
}

/*////////////////////////////////////// UTILITIES */
function GetQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}