// create jquery function for $.personal
jQuery.personal = new function() {
	// display modal dialog for 404 errors
	this.notfound = function() {
		$.modal('<h1>Not Found</h1>A new site has been rolled out. Most if not all the previous links will no longer work. If you are interested why you can <a href="#" onclick="$.modal.close(); $.personal.whathappened(); return false;">read about it</a>.');
	}
	
	// modal box for people clicking the "what happened" banner
	this.whathappened = function() {
		pageTracker._trackEvent('Click', 'Element', 'What Happened?'); // run some analytics tracking for the banner being clicked
		$.modal('<h1>What Happened To Everything?</h1>After many many years of keeping up a website and building my own website from scratch I have decided it just takes too much time out of my day to maintain a site with all the functionality of the previous site. If you want to see the old site, its still there and running at <a>http://old.stevenvondruska.com</a> [currently offline] if you like that better but I won\'t be supporting it any longer.<br /><br />If you liked the features of the live stream of my life, check out <a href="http://friendfeed.com/vondruska">FriendFeed</a>.<br /><br />Thanks for understanding.', { onOpen: dialogbox.open, onClose: dialogbox.close });
		return false;
	}
	
	// keeping it simple with a contact form modal
	this.contact = function() {
		pageTracker._trackEvent('Click', 'Element', 'Contact'); // run some analytics tracking for the contact form being displayed
		$.modal("<div style='text-align: center;'><img src='../img/loading.gif' alt='Loading...' /></div>", { onOpen: dialogbox.open, onClose: dialogbox.close, onShow: dialogbox.contactShow });
		return false;
	}
	
	this.portfolio = function() {
		pageTracker._trackEvent('Click', 'Element', 'Portfolio'); // run some analytics tracking for the portfolio box being displayed
		$.modal("<div style='text-align: center;'><img src='../img/loading.gif' alt='Loading...' /></div>", { onOpen: dialogbox.open, onClose: dialogbox.close, onShow: dialogbox.portfolioShow, containerCss: { height: 400, 'font-size': '13px' } });
		return false;
	}
};


// declare a dialogbox object just so i don't have functions running everywhere
var dialogbox = {
	// since I would like to have access to the message everywhere, just create a null instance of it
	message: null,
    newversion: false,
	// just used to create the effects on dialog opening and closing
	open: function (dialog) {
		dialog.data.show();
		dialog.overlay.fadeIn(200);
		dialog.container.fadeIn(200);
	},
	// 
	close: function (dialog) {
		dialog.container.fadeOut(200);
		dialog.overlay.fadeOut(200, function() { $.modal.close(); });
	},
	
	portfolioShow: function (dialog) {
		$.get("/landing/portfolio/"+dialogbox.newversion, function(data) { // after dialog completes opening, an ajax call is fired to pull the html page from '/contact', then fade out the "Loading" message..., and fade in the data
			try { // try to call localScroll to see if its loaded yet
				jQuery.localScroll();
			}
			catch(e) { // if it isn't, append the required javascript files to the head
				$('head').append("<script type=\"text/javascript\" src=\"/js/jquery.scrollto.js\"></script>");
				$('head').append("<script type=\"text/javascript\" src=\"/js/jquery.localscroll.js\"></script>");
			}
			
			dialog.data.fadeOut(200, function() {
				dialog.data.html(data);
				dialog.data.fadeIn(200, function() {
					$('#links').localScroll({
					   target:'#content',
					   axis:'y',
					   duration: 750
					});
				});
			});
		});
	},
	
	// called after the dialog has appeared only on the contact form
	contactShow: function (dialog) {
		$.get("/landing/contact/"+dialogbox.newversion, function(data) { // after dialog completes opening, an ajax call is fired to pull the html page from '/contact', then fade out the "Loading" message..., and fade in the data
			dialog.data.fadeOut(200, function() {
				dialog.data.html(data);
				dialog.data.fadeIn(200, function() {
					// watermarking the text fields
					// loop through all text fields and textarea's, store all their values in an array just so i can have access to them in case i want to try and access them later, then create events on focus and blur to check the fields and see if some action needs to be taken
					swapValues=[];
			        $("#contact input:text, #contact textarea").each(
			            function(i){
			                swapValues[i]=$(this).val();
			                $(this).focus(function()
			                    {
			                        if($(this).val()==swapValues[i])
			                        {
			                            $(this).val("");
										$(this).css({'color' : 'black'})
			                        }
			                    }
			                ).blur(function()
			                    {
			                        if($.trim($(this).val())=="")
			                            {
			                                $(this).val(swapValues[i]);
											$(this).css({'color' : '#aaaaaa'});
			                            }
			                     }
			                 )
			            }
						
					)
					
					$('#reset').click(function(e) {
						$("#contact input:text, #contact textarea").css('color', '#aaa');
						$('#displayMessage').html("");
					});
					
					// create new click event on submit button
					$('#submit').click(function(e) {
						e.preventDefault(); // prevent the default action of the button, which really isn't needed since the submit button is a html button with nothing associated with it
						// check if the form is valid
						if(dialogbox.validateForm()) {
							$('#displayMessage').css('color', '#fff').html("Submitting..."); // display submitting message
							$('#submit').attr('disabled', 'disabled'); // disable the button
							$.post('/contact', $('#contact').serialize(), function (data) { // start ajax post, repsonse should be in JSON format
								if(data.status == 'error') { // if an error happpened on the PHP end of things, display it here
										$('#displayMessage').css('color', '#f00').html(data.reason);
									}
									else if(data.status == 'success') { // congrats, a sucessful submission
										$('#displayMessage').css('color', '#38991A').html('Your contact form has been sucessfully submitted. Thanks!');
										$('#contact').fadeOut('200');
									}
									else { // something happened where the ajax call failed... gotta tell the user that you don't know what happened
										$('#displayMessage').css('color', '#f00').html("There has been an unknown error... please try again later");
									}
									$('#submit').removeAttr('disabled'); // reenable the submit button
								}, 
							'json');
						}
						else {
							// form validation failed... display the messagse here
							$('#displayMessage').css('color', '#f00').html(dialogbox.message);
						}
					});
				});
			});
		});
	},
	
	validateForm: function() {
		dialogbox.message = ''; // empty the message variable in case it has old validation information in it
		if (!$('#name').val() || $('#name').val() == 'name') { // test to see if the name element is blank or has the standard 'name' text in it, if it does, fail the validiation
			dialogbox.message += 'Name is required. ';
		}

		var email = $('#email').val();
		if (!email || email == 'email') { // test to see if the name element is blank or has the standard 'email' text in it, if it does, fail the validiation
			dialogbox.message += 'Email is required. ';
		}
		else {
			if (!dialogbox.validateEmail(email)) { //test to see if its a valid email address
				dialogbox.message += 'Email is invalid. ';
			}
		}

		if (!$('#message').val() || $('#message').val() == 'message') { // test to see if the message element is blank or has the standard 'message' text in it, if it does, fail the validiation
			dialogbox.message += 'Message is required.';
		}
 
		if (dialogbox.message.length > 0) { // if a message  has actually been stored in the message variable, then return false to the calling statement
			return false;
		}
		else {
			return true;
		}
	},
	
	validateEmail: function (email) {
		var at = email.lastIndexOf("@");

		// Make sure the at (@) sybmol exists and  
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;

		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;

		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);

		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!/^"(.+)"$/.test(local)) {
			// It's a dot-string address...check for valid characters
			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
				return false;
		}

		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;	

		return true;
	}
};

// do this stuff when the document is "ready" or done loading
$(document).ready(function() {
	try {
	$('.iam span').roundCorners('5px'); // round the corners of the "i am" blocks
	} catch(e) {}
	
	// create a click event on the what happened banner...
	$('#whathappened').click(function() {
		$.personal.whathappened(); // run 'whathappened' function from the top of this file
		return false;
	});
	
	// create a client event that will display the contact form
	$('#myself').click(function() {
		$.personal.contact(); // run 'contact' function from the top of this file
		return false;
	});
	
	if(location.hash == '#portfolio')
		$.personal.portfolio();
});