$(document).ready(function() {
	
	var flickrFeedBuilt = false;
	var defaultSection = "#home"; //default to home page
	
	
	
	
	//load shadowbox 
	Shadowbox.init({handleOversize: "drag",	overlayOpacity: 0.8, modal: true	});
	
	//initial navigation
	init();	
	

	$("#contactForm").validate({
		rules: {contactFormName: "required", contactFormEmail:{required:true, email:true}, contactFormComment: "required"},
		message: {contactFormName: "Your name is required", contactFormEmail:"Please enter a valid email address", contactFormComment: "required"}
	
	
	
	});
	
	$("#contactForm").submit(function(e){
		e.preventDefault();
		if($("#contactForm").valid())
		{
			//contact email message
			$('#contactForm').fadeOut(300, function(){
				$('#contactFormLoading').show();
			});	
			
			
			$("#contactName").val("Testing");
			var name = $('#contactFormName').val();
			var email = $('#contactFormEmail').val();
			var message = $('#contactFormComment').val();
			var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
			$.ajax({
				type: "POST",
				url: "forms/contact.php",
				data: dataString,
				dataType: "html",
				success: function (returnedData) {
					//todo determine if success or error is returned alert("DATA=" + returnedData);
					
					$('#contactFormLoading').fadeOut(300, function(){
						$('#contactFormSuccess').show();
					})
				}
			  });	
		}
		
	 })
	
	$(".sectionBtn").click(function(e) {
		e.preventDefault();	
		var sectionToDisplay = $(this).attr("href"); 		
		displaySection(sectionToDisplay);
	});	
	
	$('.sectionHeaderBtn').click(function(e) {
		e.preventDefault();	
		var sectionToDisplay = $(this).attr("title"); 			
		$( 'body' ).animate( { scrollTop: 0 }, 'slow', function(){
			displaySection(sectionToDisplay);
		});
		
		
	});	
		
	$(".hoverImg").hover(function(){			
		$(this).attr("src", addHover($(this).attr("src")))
	} , function() {
		$(this).attr("src", removeHover($(this).attr("src")))
	});
	
	$("#jeremyBtn").toggle(
      function () {
        $(".hiddenHeaderBox").show();		
		$('html').animate({ marginTop: "100px"}, 500 );
      },
      function () {        		
		$('html').animate({ marginTop: "0px"}, 500, function(){$(".hiddenHeaderBox").hide();} );
      }
    );
	
	
	
	function init(){
		//hide all sections
		$(".section").hide();		
		if(window.location.hash.length > 0){
			var hashArray = window.location.hash.split("?");
			defaultSection = hashArray[0];
			displaySection(defaultSection);
		} else {
			$(defaultSection).show();
			$("a[href=" + defaultSection + "]").addClass('current');
		}			
		scrollbackground('html', 0, 503, 100, 'x');				

	}
	
	function displaySection(sectionToDisplay){	
		window.location.hash = sectionToDisplay;
		//TODO Fix scroll to item and add form validation
		//alert("sectionToDisplay: " + sectionToDisplay);
		var sectionOpened = false;
		var cleanSectionArray = sectionToDisplay.split("?");
		sectionToDisplay = cleanSectionArray[0];
		//alert("cleanSectionArray[1]: " + cleanSectionArray[1])
		var itemToOpen = '';
		if(cleanSectionArray[1]){ itemToOpen = getParameterByName("item");}		
		//alert("itemToOpen: " + itemToOpen);
		$(".sectionBtn").removeClass('current');		
		$("a[href=" + sectionToDisplay + "]").addClass('current');		
		$( 'body' ).animate( { scrollTop: 0 }, 'fast', function(){
			$(".section:visible").fadeOut('fast', function(){			
				sectionOpened = true;
				$(sectionToDisplay).fadeIn('fast', function(){
					if(itemToOpen != '')
					{
						itemToOpen = "#" + itemToOpen;
						$.scrollTo(itemToOpen);
						//alert("itemToOpen: " + itemToOpen);		
					}
				});
			});
			if(sectionOpened == false){
				$(sectionToDisplay).fadeIn('fast', function(){
					if(itemToOpen != '')
					{
						itemToOpen = "#" + itemToOpen;
						$.scrollTo(itemToOpen);
						//alert("itemToOpen: " + itemToOpen);
					}
				});
			}
			
			
		});
		
		switch(sectionToDisplay)
		{
			case "#photos":
				buildFlickrFeed();	
				break;
			case "#contact":
				resetContactForm();	
				break;
			default:
				//alert("CASE DEFAULT " + sectionToDisplay)
				break;
		}
	}
	
	function addHover(fileName){
		var hoverFileArray = fileName.split('.');
		var newFileName = hoverFileArray[0] + "-hover." + hoverFileArray[1];
		return newFileName;	
	}
	
	function removeHover(fileName){		
		var newFileName = fileName.replace("-hover","");
		return newFileName;	
	}
	
	function buildFlickrFeed(){
	
		if(flickrFeedBuilt == false)		{
			
			var jsonFile ="http://api.flickr.com/services/feeds/photos_public.gne?id=49008621@N08&lang=en-us&format=json&jsoncallback=?";
						
			$.getJSON(jsonFile,
				function(data){				  
				  
				  var PhotoHTML = "";
				  if(data)
				  {
					PhotoHTML +='<ul><li><h2>Photos</h2><ul class="fourColumn portfolioList">';
				  }
				  
				  $.each(data.items, function(i,item){
					var title = item.title;
					var thumbnail = item.media.m;
					var fullImage = thumbnail.replace("_m","");					
					var newListItem = '<li><a href="' + fullImage + '" rel="shadowbox[Photos]" title="' + title + '" style="display:block; width:180px; height:100px; background:url(' + thumbnail + ')"> </a></li> ';
					//$("#photos").append(newListItem);
					PhotoHTML += newListItem;
					//$("<img/>").attr("src", item.media.m).appendTo("#photos"); 					
				  });
				  
				  
				  
				  if(data)
				  {
					PhotoHTML += '</ul></li></ul><div class="clear"> </div>';
					$("#photos").append(PhotoHTML);
					
					//load shadowbox 	
					Shadowbox.setup("#photos a", {
						gallery: "Photos",
						handleOversize: "drag",
						overlayOpacity: 0.8,
						modal: true
					});
				  }
				  
				  
				});
			
						

		
		
			flickrFeedBuilt = true;
			//alert("flickrFeedBuilt = " + flickrFeedBuilt);
			
			
			
		}
	
	
	}
	
	function getParameterByName( name )	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
	}
	
	function getParameterFromQueryString(name, string){
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( string );
		if( results == null )
			return "";
		else
			return results[1];
	}
	
	function scrollbackground(id, offset, backgroundheight, timeout, coordinate) {
		// decrease the offset by 1, or if its less than 1 increase it by
		// the background height minus 1
   		offset = (offset < 1) ? offset + (backgroundheight - 1) : offset - 1;
		// apply the background position
		if(coordinate == 'x')
		{
			$(id).css("background-position", offset + "px " + "0");
		} else
		{	
			$(id).css("background-position", "50% " + offset + "px");
		}
		
   		
   		// call self to continue animation
   		setTimeout(function() {
			scrollbackground(id, offset, backgroundheight, timeout, coordinate);
			}, timeout
		);
   	}
	
	function resetContactForm(){
		$('#contactForm').show();
		$('#contactFormLoading').hide();
		$('#contactFormSuccess').hide();
		$('#contactFormError').hide();		
		//$('#contactFormName').val();
		//$('#contactFormEmail').val();
		$('#contactFormComment').val(' ');		
	}
	
 });
 
 
 
 
 