// JavaScript Document


$(document).ready(function(){
	//initImagePreload();
	initLinks();
	initProjectBatch();
	initProjectFeature('fade');
	initProfile();
	initMisc();
});

// Reads from an XML generated by PHP
// the files to be preloaded
// PROBLEM: it does it on every page.
function initImagePreload() {
	$.ajax({
		type: "GET",
		url: "img/file_preload_xml.php",
		dataType: "xml",
		success: function(xml) {
			var fil_length = $(xml).find('fil').length;
			var img_count = 0;
			
			$(xml).find('fil').each( function() {
				var img = new Image();
				//alert('text ' + $(this).text());
				img.onload = function() {
					img_count++;
					//if(img_count == fil_length)
						//alert('all loaded');
				}
				img.src = $(this).text();
				
			});
		
			
		}
	});	
}

function initLinks() {
	
	// 'Return to top'
	$('.go-top').click(function() {
		window.scrollTo(0, $('#top').offset().top);
		return false;		
	});
	
	// 'Skip navigation'
	$('#skip-nav').click(function() {
		window.scrollTo(0, $('#the-content').offset().top);
		return false;		
	});
	
}

function initProjectBatch() {
	
	// Set parent's position to relative so the children can 
	// be placed outside the normal flow of elements
	var thumbProps = {'position':'relative', 'min-height':'inherit'};
	$('.thumb-vertical').css(thumbProps);

	// Img is inline element and leaves a gap at the bottom. 
	// Setting it to display 'block' fixed that. A little trick.
	$('.thumb-vertical').find('img').css('display','block');
	
	// Overlay the paragraph on top of the image
	// SUGGESTION: perhaps put this in the css file instead?
	// ANSWER: perhaps not, since we want this to be generated dynamically
	// without affecting the original CSS settings. 
	// PROBLEM: The implication is 
	// that anything I do here will override the default and if I don't
	// include background color here, it ceases to exist. More complicated 
	// still, jQuery doesn't work with CSS3's RGBA.
	// ANSWER: apply [background] and [background:rgba] in the CSS
	var metaProps = {'position':'absolute', 'top':0, 'left':0, 'display':'none',
						'width':'100%','height':'100%'};

	// $('.thumb-vertical') is important because of context
	$('.thumb-vertical').find('.thumb-meta').css(metaProps);
	
	// Hovering over a thumb reveals description on top
	// The description, 'thumb-meta', is nested within 'thumb-vertical'
	// PROBLEM: there isn't much space for people to click when
	// they hover. I mean, there's a link but it's a lot of wasted space...
	// WE SHOULD GIVE PEOPLE HUUUUUUUUUUUGE BUTTONS TO CLICK! HA HA.
	$('.thumb-vertical').hover(
		function() {
			//$(this).find('.thumb-meta').show();
			$(this).find('.thumb-meta').fadeIn();
		},
		
		function() {
			//$(this).find('.thumb-meta').hide();
			$(this).find('.thumb-meta').fadeOut();
		}
	);
	
	// Solution the problem above!
	// We create an invisible element on top of each (thumb+description) duo.
	// Within this element is a new link that occupies the exact same area as the 
	// thumb underneath. This new area is clickable.
	
	$('.thumb-meta a').each(function() {
		// We fetch the link
		var url = $(this).attr('href');
		var title = $(this).attr('title');
		
		// Create a style for the new element in string form
		var cssStr = "style=position:absolute;top:0px;left:0px;width:100%;height:100%;background:transparent;text-indent:-9999px;";
		
		// Create a style for the link in string form
		var cssLink = 'style=width:inherit;height:inherit;display:block;';
		
		// Put everything together: sugar, spice and everything nice...
		var n = '<div ' + cssStr + '><a href="' + url + '"' + cssLink + ' title="' + title + '">hello</a></div>';	
		
		// Generate the element
		var linkBlock = $(n);
		
		// Append the element to the thumb. The element will be on top
		// because of its 'position:absolute'.
		$(this).parents('.project-thumb').append(linkBlock);
	});
	
}

function initProjectFeature(mode) {
	
	/*
	TO DO: 
	- Image preloader
		Preload everything before initializing slideshow  
	- Pagination
	*/
	
	// If 'project-slide' element exists
	if($('#project-feature').length !=0) {
			
			// Count number of images
			var imageCount = $('#project-feature').find('img').length;
			
			// Add loading screen
			//$('#project-feature').append($('<div id="loading-screen">Loading</div>'));
			
			// Preload image(s)
			//var preloadCount = 0;
			//$('#project-feature').find('img').each(function() {  
						
				// PROBLEM: there's no guarantee that the images
				// load sequentially. The loading is asynchronous
				// and we need to find a way to check constantly,
				// some kind of polling.
				//$(this).load(function(){											  
					//preloadCount++;
					
					// If true, remove loading screen
					//if(preloadCount == imageCount) {
						//alert('All images loaded.');
						//$('#loading-screen').remove()
					//} else {
						// If not, keep loading screen	
					//}
				//});
			//});
			
			if(imageCount == 1 && $('#project-feature a').length !=0) {
				if($('.project-feature-info').length > 0) {
					var singleProps = {'position':'absolute', 
										'top':0, 'left':0, 
										'width':'100%',
										'height':'100%'};
										
										
					$('.project-feature-info').css(singleProps).hide();
					$('#project-feature').hover(
						function() {
							//$(this).find('.project-single-meta').show();
							$(this).find('.project-feature-info').fadeIn();
						},
						
						function() {
							//$(this).find('.project-single-meta').hide();
							$(this).find('.project-feature-info').fadeOut();
						}
					);
				}
				
				// TO DO: compress this block of code into a function since it's
				// being used in more than one place.

				// We create an invisible element on top of each (thumb+description) duo.
				// Within this element is a new link that occupies 
				// the exact same area as the 
				// thumb underneath. This new area is clickable.
				
				// We fetch the link
				// NOTE: since we are assuming that
				// there's only one [.project-single-meta a] per page,
				// we don't carry out this operation more than once
				var url = $('.project-feature-info a').attr('href');
				var title = $('.project-feature-info a').attr('title');
				
				// Create a style for the new element in string form
				var cssStr = "style=position:absolute;top:0px;left:0px;width:100%;height:100%;background:transparent;text-indent:-9999px;";
				
				// Create a style for the link in string form
				var cssLink = 'style=width:inherit;height:inherit;display:block;';
				
				// Put everything together: sugar, spice and everything nice...
				var n = '<div ' + cssStr + '><a href="' + url + '"' + cssLink + ' title="' + title + '">hello</a></div>';	
				
				// Generate the element
				var linkBlock = $(n);
				
				// Append the element to the thumb. The element will be on top
				// because of its 'position:absolute'.
				$('#project-feature').append(linkBlock);
	
			}
		
			// If there is more than one image, we'll build slideshow
			if(imageCount > 1) {
				
				// Fetch the width height of slides
				// PROBLEMS: Safari and Chrome have have problems determining
				// image width/height. As such, we need to wait for the images
				// to load with the 'load' event before doing anything.
				// Bastards.
				// ALSO: Move out all local variables within the 'load' handler
				// to avoid scope problems.
				var imageWidth = 0;
				var imageHeight = 0;
				
				// Current image. For Slide mode only.
				var currentPosition = 0;
				
				//alert('hello');
				
				// We need the value once, so we just determine the 
				// dimensions of the first image.
				//$('#project-feature img:first-child').load(function() {
					
					//imageWidth = $(this).width();
					//imageHeight = $(this).height();	
					
					// The 'load' event doesn't work in IE 
					// if the binding happens after the images are loaded.
					// Until I figure out how to deal with this colossal turd
					// Microbullsh*t, hardcoding will have to do. ARGH!
					// 800 (image) + 10 (left+right borders)
					imageWidth = 810;
					imageHeight = 300;

					$('#project-feature').append($('<div id="slide-track"></div>'));
				
					// Set 'slide-track' container to the height of its 
					// children images
					$('#slide-track').css('height', imageHeight);
						
					// Put images inside 'slide-track' and 
					// wrap each image in a Slide class element
					$('#project-feature').find('img').each(function() {
							$('#slide-track').append($(this));
							$(this).wrap('<div class="slide"></div>');
					});
				
					if(mode == 'slide') {
		
						// Align slides horizontally
						$('.slide').css('width', imageWidth);
						
						// Clip it
						$('#project-feature').css('overflow', 'hidden');
						
						// Calculate the total width of images and assign the
						// value to the element that's going to hold them and
						// move them along like a track.
						// NOTE: This only makes sense if we want to slide it.
						// If we want to fade it, all we need to do is to
						// stack images on top of each other (position absolute
						// for parent, position relative for kids) without 
						// intefering with div dimensions.
						$('#slide-track').css('width', imageCount*imageWidth);
					}
					
					if(mode == 'fade') {
						
						// Slides will be positioned absolutely within #slide-track
						// and they will be stack on top of each other to
						// accomplish the 'fade' effect
						$('#slide-track').css({'position':'relative'});
						//$('#project-feature').css('position','relative');
						var slideProp = {'position':'absolute', 
										'top':'0px', 
										'left':'0px'}; 
										
						$('.slide').css(slideProp);
						
						$('.slide:first-child').addClass('slide-fade-current');
					}
					
					// Build slide controls
					buildControls(mode);
				//});
			}
	}
	
	function buildControls(mode) {
		
		// Create controls
		var controls = $('<div id="slide-controls"><a id="image-previous" href="#image-previous" title="Previous Image">Previous Image</a><a id="image-next" href="#image-next" title="Next Image">Next Image</a></div>');
	
		$('#project-feature').append(controls);

		// Controls show/hide when mouse moves over 'project-feature'.
		// This needs to come after or else we would be 
		// looking for 'slide-controls' that didn't yet exist.
		/*$('#project-feature').hover(
			function() {
				$('#slide-controls').css('visibility', 'visible');
			},
			function() {
				$('#slide-controls').css('visibility', 'hidden');
			}
		);*/
		
		// Adjust position of parent and child so that 'slide-controls' is laid
		// on top of slides
		//$('#project-feature').css('position', 'relative');
		//$('#slide-controls').css({'position':'absolute' , 'top':'0px', 'left':'0px'}); 

		$('#slide-controls').find('a').click(function() {

			if(mode == 'slide') {
				if($(this).attr('id')=='image-next') {
					if(currentPosition < imageCount-1)
						currentPosition++;
				} else {
					if(currentPosition > 0)
						currentPosition--;
				}
				
				$('#slide-track').animate({
					'marginLeft' : imageWidth*(-currentPosition)
				});
			}
			
			if(mode == 'fade') {
				
				// 'Current' has z-index:3 while 'Previous'
				// has z-index:2. By switching classes,
				// we change the order of the stack.
				var current = $('.slide-fade-current');
				current.removeClass('slide-fade-current');
				current.addClass('slide-fade-previous');
				
				// To hold the new 'Current'
				var beside = null;
				
				if($(this).attr('id')=='image-next') {
					// Fetch the previous element
					beside = current.next();
					
					// If we have reached the 
					// end of the train, we 
					// restart from the begining
					if(beside.length == 0) 
						beside = $('.slide:first-child');
					
				} else {
					// Fetch the previous element
					beside = current.prev();
					
					// If we have reached the 
					// beginning of the train, we 
					// restart from the end
					if(beside.length == 0) 
						beside = $('.slide:last-child');
				}
				
				// Hide the upcoming element
				beside.hide();
				
				// Assign the upcoming element as the new current
				beside.addClass('slide-fade-current');
				
				// Bring that element into view, after which
				// we scrub the 'previous' status off the old element 
				beside.fadeIn('slow', function(){
				 current.removeClass('slide-fade-previous');
				});	
			}
			
			return false;									  
		});
	
	}
}

function initProfile() {
	
	//alert('initProfile');
	
	if($('.profile')) {
		
		//alert('profile');

		$('#link-author').css('border-bottom', '2px solid #e2e2e2');
		$('#contact-form').parent().css('display', 'none');

		$('#link-author').click(function() {
			//$('#author').parent().css('display', 'block');								 
			//$('#contact-form').parent().css('display', 'none');
			$('#contact-form').parent().fadeOut(function(){
				$('#author').parent().fadeIn();
			});
			$('#link-contact').css('border-bottom', 'none');
			$(this).css('border-bottom', '2px solid #e2e2e2');
			
			//alert('author');
			
			if($('#submission-message')) {
				$('#submission-message').fadeOut(function(){
					$('#submission-message').text('');										 
				});
			}
			clearForm();
			
			return false;
		});
		
		$('#link-contact').click(function() {
			//$('#author').parent().css('display', 'none');								 
			//$('#contact-form').parent().css('display', 'block');
			$('#author').parent().fadeOut(function(){										 
				$('#contact-form').parent().fadeIn();
			});
			
			//alert('contact');
			
			$('#link-author').css('border-bottom', 'none');
			$(this).css('border-bottom', '2px solid #e2e2e2');
			return false;
		});
		
		//var ajaxParam = $('.form').children('form').attr('action');
		//$('.form').children('form').attr('action', ajaxParam + '?ajax');
		//$('.form').children('form').prepend('<input type="hidden" name="form_mode" value="ajax"/>');
		$('.form').prepend('<div id="submission-message"></div>');
		$('#submission-message').hide();
		
		$('.slot').find('.form').submit(function() {

			// Ref: http://api.jquery.com/jQuery.ajax/
			var target = '/inc/contact_process.php';
			
			// Build package with information extracted from form.
			// 'form_mode' will be used in the php file to determine
			// necessary adaptations for ajax mode.
			// If javascript is disabled,
			// 'form_mode' doesn't exist, and the submission
			// occurs like an ordinary php POST operation.
			var emailPack = {
							'form_mode':'ajax',
							'email_submit':'hello',
							'email_author': $('.form #email-author').val(),
							'email_address': $('.form #email-address').val(),
							'email_subject': $('.form #email-subject').val(),
							'email_message': $('.form #email-message').val()
							};
							
			// Specify the format of the response
			var dataType = 'json';
			
			$.post(target, emailPack,
				function(emailResult) {
					
					if(emailResult.success == 1) {
						
						var success_msg = 'Your email has been teleported through space and time to my secretary. Thank you for your feedback. Have a good day.';
						$('#submission-message').text(success_msg);
						
						$('#submission-message').fadeIn();
						
						clearForm();
						
					} else {
						
						$('#submission-message').fadeOut(function(){
							$('#submission-message').text('');
							
							var error_list = '<ol>';
							
							for(var err_type in emailResult.error_array) {
								error_list += '<li>' + emailResult.error_array[err_type] + '</li>';
							}
							error_list +='</ol>';
							
							$('#submission-message').prepend(error_list);
							$('#submission-message').fadeIn();
						});
					}
				},
				
			dataType);

			return false;
		});

	}
	
	function clearForm() {
		$('.form input').each(function(){
			if($(this).attr('type') == 'text')
				$(this).val('');									   
		});
		$('.form textarea').val('');	
	}
}

function initMisc() {
	$('#print-article').click(function() {
		window.print();
		return false;
	});
}
