var myCarousel = '';
var currentIndex = 0;
var baseCategory = 0;
var faculty = true;
var indexArray = [];
var graduate = false;
var displayDirectory, beginsWithLetter, setFirstLetter, emptyIndexArray, loadDirectoryActions, carouselCallback, 
fillCategories, replaceContentWide, doSearch, buildCategoryOptions, buildGCategories, 
buildUGCategories, studentControls, graduateControls, fixHeader, replaceContentWideStudent,
fiveColData, threeColData, fourColData, imageActions;

displayDirectory = function(data, cat, isFaculty, isGraduate){
	baseCategory = cat;
	if(isGraduate){graduate = isGraduate;}
	faculty = isFaculty;
	var directoryHtml = "<div id='carousel-container'><div id='carousel-images'><ul id='carousel'>";
	var alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

	for(var i=0; i < data.length; i++){
		d = data[i];
		directoryHtml += "<li person-id='"+d.DirectoryPerson.id+"'>";
		if(d.Asset.file_name){directoryHtml += "<img src='/assets/asset_thumbnails/width_147/"+d.Asset.file_name+"'  />";}
		else{directoryHtml += "<img src='/assets/asset_thumbnails/width_147/NOT_PICTURED_LG.jpg' />";}
		directoryHtml += "<div class='name'>"+d.DirectoryPerson.first_name+" "+d.DirectoryPerson.last_name+"</div>";
		directoryHtml += "<div class='title'>"+d.DirectoryPerson.title+"</div>";	
		directoryHtml += "</li>";
	}

	directoryHtml +="</ul>";
	if(data.length > 5){
		directoryHtml += "<div id='next'></div><div id='prev'></div>";
	}
	directoryHtml += "</div>";
	directoryHtml += "<div id='carousel-controls'>";
	if(faculty){
		directoryHtml += "<div id='viewall'>VIEW ALL</div>";
		directoryHtml += "<div id='categories'>CATEGORIES </div><img id='category-icon' src='/media/img/categories_icon.png' />";
		directoryHtml += "<div id='search'><div id='search-text'>SEARCH DIRECTORY</div></div><img id='search-icon' src='/media/img/search_icon.png' />";
		if(data.length > 5){
			directoryHtml += "<div id='alphabet'>";

			for(var x = 0; x<alphabet.length;x++){
				directoryHtml += "<div class='alphabet_letter' id='letter_"+alphabet[x]+"'>"+alphabet[x]+"</div>";
			}

			directoryHtml += "</div>";
		}
	}else{
		if(graduate){
			directoryHtml += graduateControls();
		}else{
			directoryHtml += studentControls(data[0].DirectoryCategory);
		}
	}
	directoryHtml += "<img src='/media/img/ajax-loader.gif' id='ajaxload' style='display:none' />";
	directoryHtml += "</div>";
	directoryHtml += "<div id='category-list' style='display:none'>";
	directoryHtml += "<div class='clear'></div>";
	directoryHtml += "</div>";
	directoryHtml += "</div>";
	return directoryHtml;
};

//Check whether the person's last name begins with the specific letter 
beginsWithLetter = function(letter){
	var exists = false;

	$("#carousel li div.name").each(
		function(){
		if(letter == $(this).text().split(" ")[$(this).text().split(" ").length-1].charAt(0)){
			exists = true;
			if(!indexArray[letter]){
				indexArray[letter] = $(this).parent().attr('jcarouselindex');
			}
		}
	}
	);
	return exists; 
};

//Set the first letter variable based on the first letter of the person's last name.
//This variable is used to check whether we have scrolled to the correct person
//when a letter is clicked
setFirstLetter = function(carousel, element, index, action){
	currentIndex = index;
};

emptyIndexArray = function(){
	indexArray = [];
	return true;
}

loadDirectoryActions = function(){
	$('#carousel').jcarousel({
		initCallback: carouselCallback,
		buttonNextHTML: null,
		buttonPrevHTML: null,
		itemFirstInCallback: setFirstLetter,
		scroll: 1
	});


	$('#ajaxload').ajaxStart(function(){$(this).show();});
	$('#ajaxload').ajaxStop(function(){$(this).hide();});
	$("#search-text, #search-icon").click(
		function(){
		if($("#search").html("<input type='text' />")){
			$("#search input").focus();
			$("#search input").keydown(function(e){
				if(e.which == 13){
					doSearch($("#search input").val());
				}
			});
			$("#search-icon").unbind('click');
			$("#search-icon").click(
				function(){
				doSearch($("#search input").val());
			});
		}
	}
	);

	$("#carousel li").hover(function(){
		$("#carousel li").not($(this)).stop().animate({opacity: 0.4});
	},function(){
		$("#carousel li").stop().animate({opacity: 1});
	});

	$.getJSON('/directory_category_group/view/4.json', fillCategories);

	$("#viewall, #categories, #search").each(function(){
		$(this).hover(
			function(){$(this).toggleClass('active-control');},
			function(){$(this).toggleClass('active-control');}
		);
	});
	if(emptyIndexArray()){$("#alphabet div.alphabet_letter").each(function(){
		if(beginsWithLetter($(this).text())){
			$(this).hover(
				function(){
				$(this).removeClass('active-control');
			},function(){
				$(this).addClass('active-control');
			}
			);
			$(this).addClass('active-control');
			$(this).click( function(){
				myCarousel.scroll(parseInt(indexArray[$(this).text()], 10));
			});
		}

	});
	}
	$("#carousel li").click(function(){
		$.ajax({
			url: '/directory/view/'+$(this).attr('person-id')+'.json',
			dataType: "json",
			success: function(data){
				if(faculty){
					replaceContentWide(data);
				}else{
					replaceContentWideStudent(data);
				}
			}
		});
	});
	//Set the click actions for the controls
	$('#viewall').click(function(){
		$.ajax({
			url: '/directory/index.json?categories='+baseCategory,
			dataType: "json",
			success: function(data) {
				$('#carousel-container').remove();
				if($(".section-panel-active").after(displayDirectory(data, baseCategory, faculty))){loadDirectoryActions();}
			}
		});
	});

	$('#categories, #category-icon').click(function(){
		$('#category-list').toggle();
	});
};
carouselCallback = function(carousel){
	myCarousel = carousel;
	$('#next').click(function(){
		carousel.next();
		return false;
	});
	$('#prev').click(function(){
		carousel.prev();
		return false;
	});
};

fillCategories = function(data){
	var categoryList = "";
	for(var x in data.DirectoryCategory){
		if(data.DirectoryCategory.hasOwnProperty(x)){
			d = data.DirectoryCategory[x];
			categoryList += "<div class='category-item' category-value='"+d.id+"'>"+d.title+"</div>";
		}
	}
	if($("#category-list").html(categoryList)){
		$('.category-item').each(function(){
			$(this).hover(function(){
				$(this).toggleClass('active-control');
			},function(){
				$(this).toggleClass('active-control');
			});
			$(this).click(function(){
				$(this).toggleClass('active-control');
				$.ajax({
					url: '/directory/index.json?categories='+$(this).attr('category-value'),
					dataType: "json",
					beforeSend: function(data){
						$('#category-list').hide();
					},
					success: function(data){
						$('#carousel-container').remove();
						if($(".section-panel-active").after(displayDirectory(data, baseCategory, faculty))){
							loadDirectoryActions();
						}
					}
				});
			});
		});
	}
};

replaceContentWide = function(data){
	bio_html = "";
	if(data.Asset.file_name){bio_html += "<img id='person-image' src='/assets/asset_thumbnails/width_300/"+data.Asset.file_name+"' />";}
	else{bio_html += "<img id='person-image' src='/assets/asset_thumbnails/width_300/NOT_PICTURED_LG.jpg' />";}
	bio_html += "<h4 id='person-name'>"+data.DirectoryPerson.full_name+"</h4>";
	bio_html += "<div id='person-title'>"+data.DirectoryPerson.title+"</div>";
	bio_html += "<div id='person-phone'>Phone: ";
	if(data.DirectoryPerson.phone_number){bio_html += data.DirectoryPerson.phone_number;}
	bio_html += "</div>";
	bio_html += "<div id='person-email'>E-Mail: ";
	if(data.DirectoryPerson.email_address){bio_html += "<a href='mailto:"+data.DirectoryPerson.email_address+"'>"+data.DirectoryPerson.email_address+"</a>";}
	bio_html += "</div>";
	bio_html += "<div id='person-bio'>"+data.DirectoryPerson.bio+"</div>";
	if($(".content-wide").html(bio_html)){
		$('html, body').animate({scrollTop: ($('#carousel-controls').offset().top + $('#carousel-controls').outerHeight())+'px'},400);	
	}
};

doSearch = function(term){
	$.ajax({
		type: 'POST',
		url: '/directory/search.json',
		data: {"data[DirectoryPerson][search_string]" : term, "data[DirectoryPerson][advanced_go]" : true, "data[DirectoryCategory][1]" : baseCategory, "data[SelectAll][0]" : 0 },
		dataType: "json",
		success: function(data){
			if(data.length > 0){
				replaceContentWide(data[0]);
				$("#carousel-container").remove();
				$(".section-panel-active").after(displayDirectory(data, baseCategory, faculty));
			}else{
				myCarousel.scroll(1);
				if($(".content-wide").prepend("<div id='results-error'>No results found for your search of: "+term+"</div>")){
					$('#results-error').fadeOut(5000);
				}
			}
		},
		complete: function(){
			loadDirectoryActions();
		}
	});
};


//Student specific functions
buildCategoryOptions = function(data){
	categoryList = "";
	categoryList += "<div id='categoryList'><span id='category-header'>View:</span>";
	categoryList += "<ul>";
	for(var x in data.DirectoryCategory){
		if(data.DirectoryCategory.hasOwnProperty(x)){
			d = data.DirectoryCategory[x];

			categoryList += "<li><a href='#'>"+d.title+"</a></li>";
		}
	}
	categoryList += "<li>";

	categoryList += "</ul></div>";
	return categoryList;

};
buildGCategories = function(){
	categoryList = "";
	categoryList += "<div id='categoryList'><span id='category-header'>VIEW:</span>";
	categoryList += "<ul>";
	categoryList += "<li><a href='/185'>DESIGN</a></li>";
	categoryList += "<li><a href='/187'>DRAMATIC WRITING</a></li>";
	categoryList += "<li><a href='/188'>DIRECTING</a></li>";
	categoryList += "<li><a href='/186'>PRODUCTION</a></li>";
	categoryList += "</ul></div>";
	return categoryList;
};

buildUGCategories = function(ids){
	categoryList = "";
	categoryList += "<div id='categoryList'><span id='category-header'>VIEW:</span>";
	categoryList += "<ul>";
	categoryList += "<li><a href='/"+ids[0]+"'>ACTING</a></li>";
	categoryList += "<li><a href='/"+ids[1]+"'>DRAMATIC WRITING</a></li>";
	categoryList += "<li><a href='/"+ids[2]+"'>DESIGN</a></li>";
	categoryList += "<li><a href='/"+ids[3]+"'>DRAMATURGY</a></li>";
	categoryList += "<li><a href='/"+ids[4]+"'>DIRECTING</a></li>";
	categoryList += "<li><a href='/"+ids[5]+"'>PRODUCTION TECHNOLOGY & MANAGEMENT</a></li>";
	categoryList += "</ul></div>";

	return categoryList;
};

studentControls = function(d){
	var yearControlInfo;
	for(var x in d){
		if(d.hasOwnProperty(x)){
			if(d[x].directory_category_group_id === "1" && d[x].info !== ""){
				yearControlInfo = d[x].info;
			}
		}
	}
	yearControlInfo = yearControlInfo.split(',');
	controls = "<div id='studentControls'>";
	controls += "<a href='/"+yearControlInfo[0]+"'>SHOWCASE</a>";
	controls += "<a href='/"+yearControlInfo[1]+"'>ACTING</a>";
	controls += "<a href='/"+yearControlInfo[2]+"'>DESIGN</a>";
	controls += "<a href='/"+yearControlInfo[3]+"'>DIRECTING</a>";
	controls += "<a href='/"+yearControlInfo[4]+"'>DRAMATIC WRITING</a>";
	controls += "<a href='/"+yearControlInfo[5]+"'>DRAMATURGY</a>";
	controls += "<a href='/"+yearControlInfo[6]+"'>PRODUCTION TECHNOLOGY & MANAGEMENT</a>";
	controls += "</div>";
	return controls;

};
graduateControls = function(){
	controls = "<div id='studentControls'>";
	controls += "<a href='/28'>VIEW ALL</a>";
	controls += "<a href='/185'>DESIGN</a>";
	controls += "<a href='/186'>PRODUCTION</a>";
	controls += "<a href='/187'>DRAMATIC WRITING</a>";
	controls += "<a href='/188'>DIRECTING</a>";
	controls += "</div>";
	return controls;
};
fixHeader = function(){
	fulltext = $(".section-panel-active").text();

	temp = fulltext.split('/');

	$(".section-panel-active").html(temp[0]+" / <span style='color:#f26522'>"+temp[1]+"</span>");
};

replaceContentWideStudent = function(data){
	var extraData = false;
	if(data.ExtendedDataBlob.content){
		extraData = eval('('+data.ExtendedDataBlob.content+')');
	}
	bio_html = "";
	if(data.Asset.file_name){bio_html += "<a href='/media/assets/"+data.Asset.file_name+"' rel='lightbox' id='student-image-link'><img id='student-image' src='/assets/asset_thumbnails/width_275/"+data.Asset.file_name+"' /></a>";}
	else{bio_html += "<a href='/media/assets/NOT_PICTURED_LG.jpg' rel='lightbox' id='student-image-link'><img id='student-image' src='/assets/asset_thumbnails/width_275/NOT_PICTURED_LG.jpg' /></a>";}
	bio_html += "<div id='extra-headshots'>";
	if(data.DirectoryPerson.headshot_one){bio_html += "<img id='first-headshot' src='/assets/asset_thumbnails/height_110/"+data.DirectoryPerson.headshot_one+"'/>";}
	//else{bio_html += "<img id='first-headshot' src='/assets/asset_thumbnails/height_110/NOT_PICTURED_LG.jpg'/>";}
	if(data.DirectoryPerson.headshot_two){bio_html += "<img id='second-headshot' src='/assets/asset_thumbnails/height_70/"+data.DirectoryPerson.headshot_two+"'/>";}
	//else{bio_html += "<img id='second-headshot' src='/assets/asset_thumbnails/height_70/NOT_PICTURED_LG.jpg'/>";}
	bio_html += "</div>";
	bio_html += "<div id='detailed-info'>";
	bio_html += "<div id='person-name'>"+data.DirectoryPerson.first_name+" "+data.DirectoryPerson.last_name+"</div>";
	bio_html += "<div class='student-data-title' id='student-degree'>Degree</div>";
	if(data.DirectoryPerson.degree){bio_html += "<div class='student-data'>"+data.DirectoryPerson.degree+"</div>";}

	bio_html += "<div class='student-data-title' id='student-specialization'>Specialization</div>";
	if(data.DirectoryPerson.specialization){bio_html += "<div class='student-data'>"+data.DirectoryPerson.specialization+"</div>";}

	bio_html += "<div class='student-data-title' id='student-email'>Email</div>";
	if(data.DirectoryPerson.email_address){bio_html += "<a class='student-data' href='mailto:"+data.DirectoryPerson.email_address+"'>"+data.DirectoryPerson.email_address+"</a>";}

	bio_html += "<div class='student-data-title' id='student-phone'>Phone</div>";	
	if(data.DirectoryPerson.phone_number){bio_html += "<div class='student-data'>"+data.DirectoryPerson.phone_number+"</div>";}

	bio_html += "<div class='student-data-title' id='student-url'>Website</div>";
	if(data.DirectoryPerson.url){bio_html += "<a class='student-data' href='http://"+data.DirectoryPerson.url+"' target='_blank'>"+data.DirectoryPerson.url+"</a>";}

		if(data.DirectoryPerson.notes){
		bio_html += "<div class='student-data-title' id='student-notes'>Notes</div>";
		bio_html += "<div class='student-data'>"+data.DirectoryPerson.notes+"</div>";
	}

	bio_html += "</div>";
	bio_html += "<div id='full-size'>Click image to view full size</div>";

	bio_html += "<div id='student-data'>";
	bio_html += "<div><h1 style='margin-bottom:0px;'>Resume Highlights</h1>";
	if(data.DirectoryPerson.resume){bio_html += "<div class='student-data-title' id='student-resume' style='margin-bottom:20px;'>Full Resume: ";
		bio_html += "<a class='student-data' target='_blank' href='/media/assets/"+data.DirectoryPerson.resume+"'>PDF Format</a></div>";}
		bio_html+= "</div>";
		if(extraData['Productions Workshops and Readings'] && extraData['Productions Workshops and Readings'].length > 0){
			fields = ['Production', 'Type of Event', 'Theatre', 'Year'];
			bio_html += fourColData(extraData, 'Productions/Workshops/Readings', 'Productions Workshops and Readings', fields);
		}

		if(extraData['Directing and Assistant Directing'] && extraData['Directing and Assistant Directing'].length > 0){
			fields = ['Play', 'Position', 'Theatre', 'Year'];
			bio_html += fourColData(extraData, 'Directing/Assistant Directing', 'Directing and Assistant Directing', fields);
		}
		//If the (acting) student has data in the Theatre field, display it
		if(extraData.Theatre && extraData.Theatre.length > 0){
			fields = ['Play', 'Role', 'Theatre', 'Director'];
			bio_html += fourColData(extraData, 'Theatre', 'Theatre', fields);
		}
		if(extraData['Theatre Experience'] && extraData['Theatre Experience'].length > 0){
			fields = ['Play', 'Position', 'Theatre', 'Year'];
			bio_html += fourColData(extraData, 'Theatre Experience', 'Theatre Experience', fields);
		}
		if(extraData['Film and Industrial'] && extraData['Film and Industrial'].length > 0){
			fields = ['Film', 'Role', 'Studio Name', 'Director'];
			bio_html += fourColData(extraData, 'Film/Industrial', 'Film and Industrial', fields);
		}
		if(extraData['TV Film and Radio Work'] && extraData['TV Film and Radio Work'].length > 0){
			fields = ['Production', 'Position', 'Theatre', 'Year'];
			bio_html += fourColData(extraData, 'TV/Film/Radio Work', 'TV Film and Radio Work', fields);
		}
		if(extraData['Special Events Concerts and Vocal Performances'] && extraData['Special Events Concerts and Vocal Performances'].length > 0){
			fields = ['Title', 'Role', 'Location'];
			bio_html += threeColData(extraData, 'Special Events/Concerts/Vocal Performances', 'Special Events Concerts and Vocal Performances', fields);
		}
		if(extraData['Professional Experience'] && extraData['Professional Experience'].length > 0){
			fields = ['Company', 'Position', 'Supervisor Name', 'Month and Year'];
			bio_html += fourColData(extraData, 'Professional Experience', 'Professional Experience', fields);
		}
		if(data.DirectoryPerson.bio){
			bio_html += "<div id='student-bio'>";
			bio_html += data.DirectoryPerson.bio;
			bio_html += "</div>";
		}
		if(extraData['Honors and Awards'] && extraData['Honors and Awards'].length > 0){
			fields = ['Title of Award', 'Foundation', 'Year'];
			bio_html += threeColData(extraData, 'Honors/Awards', 'Honors and Awards', fields);
		}
		if(extraData.References && extraData.References.length > 0){
			fields = ['Reference Name', 'Job Title', 'Theatre', 'Email', 'Phone'];
			bio_html += fiveColData(extraData, 'References', 'References', fields);
		}

		bio_html += "</div>";


		if($(".content-wide").html(bio_html)){
			imageActions();
			$('html, body').animate({scrollTop: ($('#carousel-controls').offset().top + $('#carousel-controls').outerHeight())+'px'},400);	}
};
fiveColData = function(data, header, fieldName, fields){
	fiveCol = "";
	fiveCol += "<h2>"+header+"</h2>";

	fiveCol += "<table>";

	for(var x in data[fieldName]){
		if(data[fieldName].hasOwnProperty(x)){
			fiveCol += "<tr>";
			fiveCol += "<td class='fivecol'>"+data[fieldName][x][fields[0]]+"</td>";
			fiveCol += "<td class='fivecol'>"+data[fieldName][x][fields[1]]+"</td>";
			fiveCol += "<td class='fivecol'>"+data[fieldName][x][fields[2]]+"</td>";
			fiveCol += "<td class='fivecol'>"+data[fieldName][x][fields[3]]+"</td>";
			fiveCol += "<td class='fivecol'>"+data[fieldName][x][fields[4]]+"</td>";
			fiveCol += "</tr>";
		}
	}

	fiveCol += "</table>";

	return fiveCol;

};
threeColData = function(data, header, fieldName, fields){
	threeCol = "";
	threeCol += "<h2>"+header+"</h2>";

	threeCol += "<table>";

	for(var x in data[fieldName]){
		if(data[fieldName].hasOwnProperty(x)){
			threeCol += "<tr>";
			threeCol += "<td class='threecol'>"+data[fieldName][x][fields[0]]+"</td>";
			threeCol += "<td class='threecol'>"+data[fieldName][x][fields[1]]+"</td>";
			threeCol += "<td class='threecol'>"+data[fieldName][x][fields[2]]+"</td>";
			threeCol += "</tr>";
		}
	}

	threeCol += "</table>";

	return threeCol;
};
fourColData = function(data, header, fieldName, fields){
	fourcol = "";

	fourcol += "<h2>"+header+"</h2>";

	fourcol += "<table>";
	for(var x in data[fieldName]){
		if(data[fieldName].hasOwnProperty(x)){
			fourcol += "<tr>";
			fourcol += "<td class='fourcol'>"+data[fieldName][x][fields[0]]+"</td>";
			fourcol += "<td class='fourcol'>"+data[fieldName][x][fields[1]]+"</td>";
			fourcol += "<td class='fourcol'>"+data[fieldName][x][fields[2]]+"</td>";
			fourcol += "<td class='fourcol'>"+data[fieldName][x][fields[3]]+"</td>";
			fourcol += "</tr>";
		}
	}

	fourcol += "</table>";

	return fourcol;
};
imageActions = function(){
	$("#first-headshot").hover(function(){
		var oldimg = $("#student-image").attr("src").split('/');
		var thisimg = $(this).attr("src").split("/");

		$(this)[0].src="/assets/asset_thumbnails/height_110/"+oldimg[oldimg.length-1];
		$("#student-image")[0].src="/assets/asset_thumbnails/width_275/"+thisimg[thisimg.length-1];
		$("#student-image-link").attr("href", "/media/assets/"+thisimg[thisimg.length-1]);	

	}, function(){});

	$("#second-headshot").hover(function(){
		var oldimg = $("#student-image").attr("src").split('/');
		var thisimg = $(this).attr("src").split("/");

		$(this)[0].src="/assets/asset_thumbnails/height_70/"+oldimg[oldimg.length-1];
		$("#student-image")[0].src="/assets/asset_thumbnails/width_275/"+thisimg[thisimg.length-1];	
		$("#student-image-link").attr("href", "/media/assets/"+thisimg[thisimg.length-1]);

	}, function(){});
	$('#student-image-link').lightBox({
		imageLoading: '/media/img/lightbox-ico-loading.gif',
		imageBtnClose: '/media/img/lightbox-btn-close.gif',
		imageBtnPrev: '/media/img/lightbox-btn-prev.gif',
		imageBtnNext: '/media/img/lightbox-btn-next.gif'
	});	
};

