/*global $, jQuery, document, screen, window, setTimeout*/
"use strict";

// Global variables
var currentPage;
var currentFilter;
var currentClip;
var currentNav;
var currentMenu;
var projectFilter;
var windowHeight;

// Boolean values
var clipOver = false;
var modalOpen = false;
var projectOpen = false;
var networksOpen = false;
var contactOpen = false;

var slowFade = 800;
var fastFade = 200;
var moveSpeed = 800;

jQuery.easing.def = "easeInOutExpo";

// If local
// var path = "http://www.codygroom.com/";

// If remote
//var path = "/"

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// GLOBAL FUNCTIONS FOR ALL SECTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
String.prototype.capitalize = function () {
	return this.replace(/(^|\s)([a-z])/g, function (m, p1, p2) { return p1 + p2.toUpperCase(); });
};

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function removeKeyEvents() {
	$(window).unbind("keydown");
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function onResize() {
	var theOffset, theWidth;
	
	windowHeight = $(window).height();
	theWidth = $('body').width() * 0.5;	
	theOffset = 200 - (200 * ($(window).width() / screen.width));
	
	if (projectOpen){
		$("#sharing").css("left", theWidth + 380);
		$("#proNav").css("left", theWidth - $("#proNav").width() / 2);	
	} else{
		$("#theProject").css("top", -windowHeight);	
	}
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// MODAL FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function positionModal() {
	var modalWidth, modalHeight, prevWidth, prevHeight, modalInner;
	
	modalInner = $('#modalInner');
	
	modalHeight = modalInner.height();
	modalWidth = modalInner.width();
	
	// CONSOLE MESSAGE
	//console.log('modalWidth : ' + modalWidth);
	
	$('#modal').animate({
		height : modalHeight,
		width : modalWidth,
		'marginLeft' :  -(modalWidth * 0.5),
		'marginTop' :  -(modalHeight * 0.5)
	}, moveSpeed, function () {	
		$('#modalLoader').remove();
		modalInner.fadeIn(slowFade);
	});
}

function openModal(modalContent) {
	
	// CONSOLE MESSAGE
	//console.log('open modal');
	
	$('#modal').append('<img id="modalLoader" src="images/loading.gif" class="loader" />');
	
	$('#modalContainer').fadeIn(slowFade, function(){
		
		$('#modalInner').hide().html(modalContent);
		positionModal();
		
		modalOpen = true;
	});
}

function closeModal() {
	$('#modalInner').html("");
	
	var modalHeight = 0;
	var modalWidth = 0;
	
	$('#modal').animate({
		height: modalHeight,
		width: modalWidth,
		'marginLeft' :  -(modalWidth * 0.5),
		'marginTop' :  -(modalHeight * 0.5)
	}, moveSpeed, function () {	
		$('#modalContainer').fadeOut(slowFade, function () {
			modalOpen = false;
		});
	});	
}

function miniModal() {
		
	$('#modal').css('bottom', '0');
	modalOpen = false;
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// HEADER FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function showHeader() {
	$('header').animate({ 
		top: 0
	}, moveSpeed);
}

function hideHeader() {
	$('header').animate({ 
		top: -300
	}, moveSpeed);
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// PROJECT FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function closeProject() {
	var theProject;
	
	theProject = $('#theProject');

	$('#project').fadeOut(moveSpeed, function(){ 
		
		$('#theProject').animate({ 
			top: -windowHeight
		}, moveSpeed, function () {
			
			showHeader();
	
			// clear previous project content
			theProject.html("");
			
		    // remove keyEvents
		    removeKeyEvents();
	
			projectOpen = false;
			
			if (currentFilter === "all" || currentFilter === "") {
				document.location.hash = "/projects";
			} else {
				document.location.hash = "/" + currentFilter;
			}
			
		});
	});
}

function enableProjectLinks() {
	var timer;
	
	// SET UP THE MOUSE OVER
	$("#projects a").bind('mouseenter', function(e){
		
		var currentInfo = $(e.currentTarget).find('.projectInfo');
		currentClip = this;
				
		// fade the clips out		
		$("#projects a:visible").stop().not(currentClip).fadeTo(fastFade, 0.07);
		$(currentClip).stop().fadeTo(fastFade, 1.0);
		var pos = $(currentClip).position();
		var tempWidth = $(currentInfo).width();
			
		$(currentInfo).css({
			top: pos.top + 115,
			left: pos.left + 20,
			width: tempWidth
		}).fadeIn(fastFade).animate({ 
			top : pos.top + 120
		}, 40);		
		clearTimeout(timer);
			
	}).bind('mouseleave' , function(e){
		$(e.currentTarget).find('.projectInfo').hide();
		$(e.currentTarget).stop().fadeTo(slowFade, 0.1);
		timer = setTimeout(function(){
			$("#projects a:visible").fadeTo(slowFade, 1.0);	
		}, 400);
	});
	
	//console.log('projects enabled');
}

function disableProjectLinks() {
	$("#projects a").unbind('mouseenter').unbind('mouseleave');
	
	//console.log('projects disabled');
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// KEYBOARD EVENTS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function addKeyEvents() {
		
	$(window).bind("keydown", function (event) {
		
		if (event.keyCode === 27) {
			
			event.preventDefault();
			
			if (modalOpen) {
				closeModal();	
			} else {
				closeProject();	
			}
		}
		
		/*
		// use to switch projects???
		if (event.keyCode === 37) {
			event.preventDefault();
			prevProject()
		}
		
		if (event.keyCode === 39) {
			nextProject()
		}
		*/
	});
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// CONTACT FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkEmail(inputvalue) {
	var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	if (pattern.test(inputvalue)) {         
		return true;   
	} else {   
		return false; 
	}
}

function showMessage(theMessage) {
	$('.message').html(theMessage).fadeIn(1000).delay(5000).fadeOut(1000);
}

function submitForm() {
	var theName, theEmail, theMessage;
	
	theName = document.contact.name.value;
	theEmail = document.contact.email.value;
	theMessage = document.contact.message.value;
	
	//console.log('Form Submit')
	
	if (checkEmail(theEmail)) {
		$.post("php/email.php", { myName: theName, myEmail: theEmail, myMessage: theMessage },
		function (data) {
			
			$('#name').focus();
			showMessage("Your email has been sent.");
			
			$('#contact').delay(5000).fadeOut(1000);
			
			document.contact.name.value = "";
			document.contact.email.value = "";
			document.contact.message.value = "";
		});
	} else {
		$('#email').focus();
		showMessage("You must enter a valid email.");
	}
}

function showContact () {
		
	// HIDE THE SOCIAL NETWORK LINKS
	if (networksOpen) {
		$('#networkLink').click();
	}
	
	$('#innerContent').stop().fadeTo(fastFade, 0.1);
	
	$('#contact').show().animate({
		opacity: 1,
		bottom: 65
	}, { duration: fastFade, queue: false, complete: function(){
	
		// DISABLE PROJECT HOVERS
		disableProjectLinks();
		contactOpen = true;
	   	//console.log('Open Contact')
	}});
}

function closeContact () {
	
	// ENABLE PROJECT HOVERS
	enableProjectLinks();
	
	$('#innerContent').fadeTo(fastFade, 1.0);
	
	$('#contact').animate({ 
		opacity: 0,
		bottom: 45
    }, { duration: fastFade, queue: false, complete: function(){
    	$('#contact').hide();
    	contactOpen = false;
		//console.log('Close Contact');
    }});	
    
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function showSocial () {
		
	// HIDE THE CONTACT FORM
	if (contactOpen) {
		$('#contactLink').click();	
	}
	
	$('#innerContent').stop().fadeTo(fastFade, 0.1);
	
	$('#socialNetworks').show().animate({ 
		opacity: 1,
		bottom: 65
	}, { duration: fastFade, queue: false, complete: function(){
	
		// DISABLE PROJECT HOVERS
		disableProjectLinks();
		networksOpen = true;
 	  	//console.log('Open Social')
	}});
}

function closeSocial () {
	
	// ENABLE PROJECT HOVERS
	enableProjectLinks();
	
	$('#innerContent').fadeTo(fastFade, 1.0);
	$('#socialNetworks').animate({ 
		opacity: 0,
		bottom: 45
    }, { duration: fastFade, queue: false, complete: function(){
    	$('#socialNetworks').hide();
    	networksOpen = false;
		//console.log('Close Social');
    }});
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// SEARCHING FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function showSearchBar () {
	$('#searchContainer').animate({ 
			top: 0
	}, { duration: moveSpeed, queue: false});	
}

function hideSearchBar () {
	$('#searchContainer').animate({ 
		top: -100
	}, { duration: moveSpeed, queue: false});	
}

function searchItems() {
	var searchText = $("#search").val();
	
	$("#searchClear").show();
	$('#projects a').hide();
			
	$("#projects a[title*='" + searchText + "']").show();
	
	searchText = searchText.capitalize();
	$("#projects a[title*='" + searchText + "']").show();
	
	searchText = searchText.toLowerCase();
	$("#projects a[title*='" + searchText + "']").show();
			
	if (searchText === "search by title") {
		clearSearch ();
	}
}

function clearSearch () {
	$("#search").val('Search By Title');
	$("#searchClear").hide();
	$('#projects a').show();
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++
// UPDATE CONTENT HEIGHT
// ++++++++++++++++++++++++++++++++++++++++++++++++++
function updateContent() {
	
	var contentHeight = $('#innerContent').height();
			
	$('#content').animate({
		height: contentHeight + 45
	}, moveSpeed, function () {
		$('#innerContent').show();
	});
	
	// CONSOLE MESSAGE
	//console.log('updateContentHeight');
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++
// FILTERING FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++
function filterProjects(filter) {
	
	// CONSOLE MESSAGE	
	//console.log('filterProject : ' + filter)
	
	$("#search").val('Search By Title');
		
	if (filter === "projects") {
		$('#projects a').show();
	} else {
		$('#projects a').hide();
		$("#projects a[type*='" + filter + "']").show();
	}
	
	$(projectFilter).removeClass('selected');
	
	if (filter === "projects") {
		projectFilter = $('#filters li:first-child').addClass('selected');
	} else {
		projectFilter = $('#filters li:contains(' + filter + ')').addClass('selected');
	}	
	
	currentFilter = filter;
	updateContent();
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// PROJECT FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function loadProject(thePage) {
	var theHeight, tempPosition, theProject;
	
	// CONSOLE MESSAGE
	//console.log('load : ' + thePage);
	
	clipOver = false;
	
	theHeight = $(document).height();
	
	disableProjectLinks();
			
	// hide the header
	hideHeader();
	hideSearchBar();
		
	$('#content').fadeOut(slowFade,function(){		
		
		theProject = $('#theProject');
		
		theProject.show().load('projects/' + thePage + '/index.html', function () {			
			theProject.css({
				'background-image': 'url(projects/' + thePage + '/images/main.jpg)',
				'top': -windowHeight
			});
			
			projectOpen = true;
			addKeyEvents();
			onResize();
		
			$('#project').hide();
		
			theProject.delay(500).animate({ 
				top : 0
			}, moveSpeed, function () {
								
				var pageTitle = $('#project h2').html();
												
				// Sets the page title
				$.address.title("Cody Groom { " + pageTitle + " }");
				
				/*
				$('#sharing').css('bottom', '-50px');
				
				$('#sharing').animate({ 
					bottom: 0
				}, moveSpeed);
				*/
				
				$('#project').fadeIn(slowFade);
				
				
			});
		});
	});
}

function prevProject() {
	document.location.hash = "/alienation";
}

function nextProject() {
	document.location.hash = "/iris";
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// HOVER TITLE FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
function showTitle(item) {
	
	
	var topOffset, leftOffset, projectHover;
	
	projectHover = $("#projectHover");
	
	$("#projectHover p").html(title);
	
	topOffset = projectHover.height();
	leftOffset = projectHover.width() / 2 - 50;
	
	projectHover.show();
	
	projectHover.css({
		top: position.top - (topOffset + 20),
		left: position.left - leftOffset
	}).animate({
		top: position.top - (topOffset + 45),
		left: position.left - leftOffset,
		opacity: 1
	}, moveSpeed * 0.1);
	
	clipOver = true;
	
	console.log('showTitle : ' + title);

}

function updateTitle(title, position) {
	
	var topOffset, leftOffset, projectHover;
	
	projectHover = $('#projectHover');
	
	$("#projectHover p").html(title);
	
	topOffset = projectHover.height();
	leftOffset = projectHover.width() / 2 - 50;
	
	projectHover.animate({
		top: position.top - (topOffset + 45),
		left: position.left - leftOffset,
		opacity: 1
	}, moveSpeed * 0.1);
	
	console.log('updateTitle : ' + title);
}

function hideTitle(position) {
		
	var topOffset, projectHover;
	
	projectHover = $('#projectHover');	
		
	topOffset = projectHover.height();
	
	projectHover.animate({ 
		top: position.top - (topOffset + 60),
		opacity: 0
	}, moveSpeed * 0.1, function (){
		projectHover.hide();
	});
}

function createBigTitle() {
	
	var timer;
	
	var projectHover = $('#projectHover');
	projectHover.css('opacity','0');
	
	// sound = '<embed id="clickSound" src="sounds/clicked.mp3" width="0" height="0" autoplay="false"></embed>';
	// sound += '<embed id="overSound" src="sounds/over.mp3" width="0" height="0" autoplay="false"></embed>';
	// $("#sounder").html(sound);
	
	
	// SET UP THE MOUSE OVER
	$("#projects a").bind('mouseenter', function(e){
		
		console.log(e.currentTarget)
		
		currentClip = this;
		
		var currentInfo = $(e.currentTarget).find('.projectInfo');
		
		// fade the clips out		
		$("#projects a:visible").stop().fadeTo(200, 0.07);
		$(currentClip).stop().fadeTo(200, 1.0, function(){
			$(currentInfo).css({
				left: 120	
			});
		
			$(currentInfo).show().animate({ 
				left : 125
			}, 40, function () {
			
			});
		});
		clearTimeout(timer);
		
		// showTitle(this);
		
		var tempTitle, tempPosition;
	
		currentClip = this;		
		
		// create the title hover
		tempPosition = $(currentClip).offset();		
		tempTitle = $(currentClip).attr('title');
		//$(currentClip).attr("title", "");
		
		projectHover.stop(true, false).animate({ 
			margin : '0'
		}, 50, function () {
						
			if (clipOver){
				updateTitle(tempTitle, tempPosition);
				
				// Play a sound
				//clickSound.Play();
					
			} else {
				showTitle(tempTitle, tempPosition);
				
				clipOver = true;
					
				// Play a sound
				//clickSound.Play();
			}
										
			// fade the clips out
			$(currentClip).fadeTo(200, 1.0);
			$("#projects a:visible").not(currentClip).fadeTo(200, 0.1);		
		});
		
	}).bind('mouseleave' , function(e){
		$(e.currentTarget).find('.projectInfo').hide();
		$(e.currentTarget).stop().fadeTo(slowFade, 0.1);
		timer = setTimeout(function(){
			$("#projects a:visible").fadeTo(slowFade, 1.0);	
		}, 400);
		var tempPosition;
		
		currentClip = this;
		// $(currentClip).attr("title",  $("#projectHover p").html());
				
		projectHover.animate({ 
			opacity: 1
		}, 100, function () {
			if (clipOver){
															
				tempPosition = $(currentClip).offset();
				hideTitle(tempPosition);
				
				// fade the clips in
				$("#projects a:visible").fadeTo(200, 1.0);
					
				// Play a sound
				// overSound.Play();
					
				clipOver = false;
			}
		});
	});
	
	console.log('createTitle');
}
*/

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initProjects(){
	
	filterProjects(currentFilter);
			
	// SET UP THE FILTER AND PROJECT CLICKS
	$('#filters a').address(function() {
		return $(this).attr('href').replace(location.pathname, '');
	});

	$('#projects a').address(function() {
		return $(this).attr('href').replace(location.pathname, '');
	});
	
	enableProjectLinks();
	
	//console.log('Init Projects');
					
	/*
	$("#projects").mousemove(function(e) {
		var mouseX = (-(e.clientX - ($("body").width() / 2 - 370)) * ((theWidth - 740) / 740)) + 5;
															
		$(this).animate({ 
			left: mouseX
    		}, { duration: 5000, queue: false}
    	);
	});
	*/
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// MAIN PAGE FUNCTIONS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function loadPage(thePage) {
	var theContent, theHeight, theWidth;
	
	// CONSOLE MESSAGE
	//console.log('load : ' + thePage);
	
	// Store variable for the content
	theContent = $('#content');
	
	$(currentNav).removeClass('selected');
	currentNav = $('#mainNav li:contains(' + thePage.capitalize() + ')').addClass('selected');		
			
	theWidth = $(document).width();
		
	theContent.fadeIn(slowFade);
	
	$('#loadingImage').css({
		top : $(theContent).height() * 0.5	
	}).fadeIn(slowFade);
	
	// CHECKING THINGS OUT
	$('#innerContent').hide().load('pages/' + thePage + '.php', function () {
	
		// store the page name
		currentPage = thePage;
		
		// Sets the page title
		$.address.title("Cody Groom { " + thePage.capitalize() + " }");
	
		if (thePage === "projects") {
			showSearchBar();
			
			$('#loadingImage').fadeOut(slowFade, function () {
				initProjects();
			});
		} else {
			hideSearchBar();
			
			$('#loadingImage').fadeOut(slowFade, function () {
				updateContent();
			});
		}
	});
}

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ADDRESS DEEP LINKING EVENTS
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
$.address.init(function (event) {
	
}).change(function (event) {
			
	var newPage = event.path.substring(1);
	
	if (projectOpen) {
		closeProject();
	}
	
	// hide the social networking
	if (networksOpen) {
		$('#networkLink').click();
	}
	
	// hide the social networking
	if (contactOpen) {
		$('#contactLink').click();	
	}
	
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// This code loads all pages except the project page
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	if (newPage === "about" || newPage === "news") {	
		loadPage(newPage);
	} 
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// LOAD PROJECTS
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	else if (newPage === "" || newPage === "projects") {
		
		if (newPage === "") {
			newPage = "projects";
		}
				
		if (currentPage === "projects") {
			filterProjects(newPage);
		} else {			
			loadPage(newPage);
		}
	}
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// FILTER PROJECTS
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	else if (newPage === "audio" || newPage === "photo" || newPage === "video" || newPage === "web" || newPage === "installation"){
		
		// check if the current page is set. if not we need to load the project page
		if (currentPage !== "projects") {
			currentFilter = newPage;
			loadPage('projects');
		} else {			
			filterProjects(newPage);
		}
	}
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// LOAD PROJECT
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	else {		
		loadProject(newPage);
		currentPage = newPage;
	}
});

// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// INIT SITE
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function siteInit() {
	
	currentMenu = "";
	currentFilter = "projects";
	currentPage = "";
	projectFilter = "";
	
	$(window).resize(function () {
		onResize();	
	});
	
	// MAIN NAV
	$('#mainNav li').bind('click', function() {
		$(currentMenu).removeClass('selected');
		$(this).addClass('selected');
		currentMenu = this; 	
	});
	
	currentMenu = $('#mainNav li:nth(2)-child');
	
	// ++++++++++++++++++++++++++++++++++++++++++++++++++
	// SEARCH BAR
	// ++++++++++++++++++++++++++++++++++++++++++++++++++
	$('#search').keydown(function() {
  		searchItems()
	}).blur(function() {
  		searchItems();
	});	
		
	// ++++++++++++++++++++++++++++++++++++++++++++++++++
	// SOCIAL NETWORKS TOGGLE
	// ++++++++++++++++++++++++++++++++++++++++++++++++++
	$('#networkLink').toggle(function() {
		showSocial();
	},function() {
		closeSocial();
	});
	
	// ++++++++++++++++++++++++++++++++++++++++++++++++++
	// CONTACT FORM TOGGLE
	// ++++++++++++++++++++++++++++++++++++++++++++++++++
	$('#contactLink').toggle(function() {
		showContact();
	},function() {
		closeContact();	
	});
		
	onResize();
	showHeader();	
}
