/*
** People.js
** Copyright Ronningen Design, LLC (http://www.websitesthatdostuff.com)
** Subcontracted to Substratal Code LLC (http://www.substratalcode.com)
** Tampered with by Way Short of Heaven (http://www.wayshortofheaven.com)
**
*/

$(document).ready(function() {

	$('#addProfileLoginForm .formLogIn').click(function(){
		alumniLogin();
		return false;
	});

	$("#addProfileLoginForm").keypress(function(e){
		if(e.keyCode==13){
			e.preventDefault();
			$(".formLogIn").click();
			return false;
		}
	});

	// Add the click listeners:
   $("#personModal").dialog({
		autoOpen: false,
		modal: true,
		height: $(window).height() - 30,
		width: $(window).width() - 30,
		position: [15, 15],
		dialogClass: 'peopleModal'
   });

	$("#listView a.modal").click(function(){
		// Get the ID of the clicked link:
		var link = $(this).closest("h3").attr("title");
		var id = $(this).closest("div").attr("id");
		showDialog(link, id);

		return false;
	});

	$("#mainlistView a.modal").click(function(){
		// Get the ID of the clicked link:
		var link = $(this).closest("h2").attr("title");
		var id = $(this).closest("div").attr("id");
		showDialog(link, id);

		return false;
	});

	$("#gridView a.modal").click(function(){
		// Get the ID of the clicked link:
		var link = $(this).attr("href");
		var id = $(this).closest("td").attr("id");
		showDialog(link, id);

		return false;
	});

	$("#alphaList li a").click(function(){
		// Get the ID of the clicked link:
		var id = $(this).attr("title");
		scrollWin(id);

		return false;
	});

	$("#decadeList li a").click(function(){
		// Get the ID of the clicked link:
		var id = $(this).attr("title");
		scrollWin(id);

		return false;
	});

	$(".donorList #peopleSidebar p a").click(function(){
		// Get the ID of the clicked link:
		var id = $(this).attr("href");
		scrollWin(id);

		return false;
	});

	$("#registerLink a").click(function(){
		$('#formToggle').toggleClass('updateInfo');
		$('#registerForm').toggle();
		$('#updateForm').toggle();

		return false;
	});

	$("#updateInfoLink a").click(function(){
		$('#formToggle').toggleClass('updateInfo');
		$('#registerForm').toggle();
		$('#updateForm').toggle();

		return false;
	});

	$('.addSpouse').click(function(){
		$(this).replaceWith('<input type="text" name="data[User][spouse]" />');

		return false;
	});

	$('.addChild').click(function(){
		num = $('input.children').length;
		$('<input type="text" name="data[User][children_'+num+']" class="children" />').insertBefore(this);

		return false;
	});

	// Launch a profile when the person variable is in the URL:
	var personID = $.getUrlVar('person');
	if(personID !== undefined) {
		// Launch the modal:
		var link = "/alumni/"+personID;
		showDialog(link, personID);
	}

	// Check to see if you are trying to update rather than register
	var updatingProfile = $.getUrlVar('updatingProfile');
	if(updatingProfile !== undefined) {
		$('#formToggle').toggleClass('updateInfo');
		$('#registerForm').toggle();
		$('#updateForm').toggle();
	}

	// Make the links inside the profile window go to the parent:
	if(location.pathname.indexOf("/modal") != -1) {
		// Add targets to the classes that are directly associated with this:
		$('a[class!="associatedLink"]').attr('target', '_parent');

		// Remove the targets on other links, append modal:
		var list = $('a[class^="associatedLink"]');
		list.removeAttr('target');

		$.each( list, function( intIndex, obj ){
				var link = $(obj);
				link.attr('href', link.attr('href')+"/modal");
			}
		);
	}

	// Set up the decade list to scroll all fancy like
	if($('body').attr('class') == 'page donorList') {
		var top = 650;
		var totalHeight = $(document).height();
		var footerHeight = 840;
		var lockDown = totalHeight - ($('#footer').height() + 30) - 330 - top - 63;
	} else {
		var top = 880;
		var totalHeight = $(document).height();
		var footerHeight = 605;
		var lockDown = totalHeight - ($('#footer').height() + 30) - 92 - top - 63;
	}
	
	$(window).scroll(function (event) {
		// what the y position of the scroll is
		var y = $(this).scrollTop();
		
		// fix this to not go too far
		if (y >= top) {
			 if ((totalHeight - y) <= footerHeight) {
				// pin it to the bottom
				$('#decadeList').css("top",lockDown);
				$('#decadeList').removeClass('fixed');
			} else {
				// add the fixed class
				$('#decadeList').addClass('fixed');
				$('#decadeList').removeClass('fixed_bottom');
				$('#decadeList').removeAttr('style');
			}
		} else {
			// otherwise remove it
			$('#decadeList').removeClass('fixed');
			$('#decadeList').removeClass('fixed_bottom');
		}
	  });

	$(".ui-dialog").css({"position" : "fixed"});

	/*
	******************************************************************
	// Cause the errors to disappear on re-focus
	$("#AlumnusRecentNews").focus(function(){
		$.validationEngine.closePrompt(this)
		$('div[class$="AlumnusRecentNewsformError"]').fadeOut("fast");
	});
	$("#AlumnusFavCampMemory").focus(function(){
		$('div[class$="AlumnusFavCampMemoryformError"]').fadeOut("fast");
	});
	$("#AlumnusFunniestMemory").focus(function(){
		$('div[class$="AlumnusFunniestMemoryformError"]').fadeOut("fast");
	});
	$("#AlumnusFavFood").focus(function(){
		$('div[class$="AlumnusFavFoodformError"]').fadeOut("fast");
	});
	$("#AlumnusFavTradition").focus(function(){
		$('div[class$="AlumnusFavTraditionformError"]').fadeOut("fast");
	});
	$("#AlumnusFavEp").focus(function(){
		$('div[class$="AlumnusFavEpformError"]').fadeOut("fast");
	});
	$("div.yearsAtCamp input").focus(function(){
		$('div[class$="AlumnusYearsAtCamp0formError"]').fadeOut("fast");
	});
	/******************************************************************
	*/

});


/*
** Function to log the user in via the side login box.
*/
function alumniLogin(){
	var data = $("#addProfileLoginForm").serialize();
	$.ajax({
		type:"POST",
		url:"/users/login/",
		data:data,
		dataType:"json",
		beforeSend: function(){
			$(".formLogIn").toggleClass("loginLoader")
		},
		complete: function(){
			$(".formLogIn").toggleClass("loginLoader")
		},
		success: function(response){
			if(response.success==true) { 
				window.location.reload();
			} else { 
				$(".loginError").html(response.data).show().animate({backgroundColor:"#c01a1a",color:"white"},500);
			}
		}
	});
}


/*
** Function to open a modal window displaying an iframe holding news content.
**
** param slug: the URL of the news content to display.
** param id: the ID of the originating request to pull related data from.
*/
function showDialog(slug, id) {

	var date = $("#"+id+" p.timestamp").html();
	if(date == "") {
		date = "a while ago";
	}

	$("#personModal").html('<iframe id="modalIframeId" width="959" height="453" marginWidth="0" marginHeight="0" frameBorder="0" scrolling="auto" class="ieModalIframe" />').dialog("open");
	$("#modalIframeId").attr("src", slug);
	$("#personModal").append('<a class="neueButton closeBtn" href="#">close</a>');
	$("#personModal").append('<a id="prevButton" class="prevButton neueButton" href="#">prev</a>');
	$("#personModal").append('<a id="nextButton" class="nextButton neueButton" href="#">next</a>');

	$("#ui-dialog-title-personModal").before("<span id='modalTitle'></span>");

	// Set the stuff on the modal:
	var timestamp = {
		typeface: "Silkscreen",
		typeColor: "#222222",
		typeSize: "8",
		allCaps: "false",
		content: "posted "+date
	};
	var params = {
		menu: "false",
		salign: "LEFT",
		wmode: "transparent"
	};
	var attributes = {};

	swfobject.embedSWF("/swf/customType.swf", "ui-dialog-title-itemModal", "250", "20", "10","/swf/expressInstall.swf", timestamp, params, attributes);

	// Set the modal title:
	var modalTitle = {
		typeface: "Helvetica Bold",
		typeColor: "#222222",
		typeSize: "16",
		allCaps: "false",
		content: "Greystone People"
	};
	var params = {
		menu: "false",
		salign: "LEFT",
		wmode: "transparent"
	};
	var attributes = {};

	swfobject.embedSWF("/swf/customType.swf", "modalTitle", "250", "21", "10","/swf/expressInstall.swf", modalTitle, params, attributes);

	$("#alumni").addClass("childModal");
	if(typeof ieModalfix == 'function') {
		ieModalfix();
	}

	modalSize();

	$(window).resize(function(){
		modalSize();
	});

	// Add close modal listener
	$(".closeBtn").click(function(){
		// Close the dialog:
		$('#personModal').dialog('close');
		$("#alumni").removeClass("childModal");
		$("#alumni").parent().removeClass("childModal");
		// This only useful in Firefox as far as I can tell. It's not worth it, I don't think.
		// $('#alphabet').removeClass('fixed');

		return false;
	});

	$("#nextButton").click(function() {
		getProfile(true);
	});

	$("#prevButton").click(function() {
		getProfile(false);
	});

	return false;
}

function getProfile(forward) {
	// Get the current id  from the iframe:
	var src = $("#modalIframeId").attr('src');
	var id = src.substr(src.lastIndexOf('/')+1, src.length);

	// Check to make sure the profiles array is available:
	if($.isArray(profileIDs)) {
		// Go through the array of ids and find the next one:
		var idPos = $.inArray(Number(id), profileIDs);

		var nextID = 0;
		if(idPos == 0 &&  forward == false) {
			nextID = profileIDs[profileIDs.length-1];
		} else if (idPos == (profileIDs.length-1) && forward == true) {
			nextID = profileIDs[0];
		} else if (forward == false) {
			nextID = profileIDs[idPos - 1];
		} else {
			nextID = profileIDs[idPos + 1];
		}

		$("#modalIframeId").attr('src', '/alumni/view/'+nextID);

		var date = $("#person"+nextID+" p.timestamp").html();
		if(date == "") {
			date = "a while ago";
		}

		// Set the stuff on the modal:
		var timestamp = {
			typeface: "Silkscreen",
			typeColor: "#222222",
			typeSize: "8",
			allCaps: "false",
			content: "posted "+date
		};
		var params = {
			menu: "false",
			salign: "LEFT",
			wmode: "transparent"
		};
		var attributes = {};

		swfobject.embedSWF("/swf/customType.swf", "ui-dialog-title-personModal", "250", "20", "10","/swf/expressInstall.swf", timestamp, params, attributes);
	}

	return false;
}

/*
** Function to monitor window width and resize the modal accordingly.
*/
function modalSize() {

	viewPortWidth = $(window).width();
	viewPortHeight = $(window).height();

	// set the modal dimensions
	$(".peopleModal").width(viewPortWidth - 30);
	$(".peopleModal .ui-dialog-content").height(viewPortHeight - 88);
	$(".peopleModal").css({'top':'15px','left':'15px'});

	// set the iframe dimensions
	$(".peopleModal .ui-dialog-content iframe").width(viewPortWidth - 50);
	$(".peopleModal .ui-dialog-content iframe").height(viewPortHeight - 130);

	$(".ui-widget-overlay").width(viewPortWidth + 30);
}

function scrollWin(id){
	var offset = $('#'+id).offset().top - 63;
	$('html, body').animate({ scrollTop: offset }, 600);
	$('#'+id).animate({backgroundColor:'#ff95ea'}, 1200).animate({backgroundColor:'#ffffff'}, 700);
}

