$(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();
                $('#contactFormLoading').fadeIn(300, function () {
                    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.aspx",
                        data: dataString,
                        dataType: "html",
                        success: function (returnedData) {
                            //todo determine if success or error is returned alert("DATA=" + returnedData);                    
                            if (returnedData == "success") {

                                $('#contactFormLoading').fadeOut(300, function () {
                                    $('#contactFormSuccess').show();
                                })
                            } else if (returnedData == "error") {
                                $('#contactFormLoading').fadeOut(300, function () {
                                    $('#contactFormError').show();
                                })
                            }
                        },
                        err: function () {
                            $('#contactFormLoading').fadeOut(300, function () {
                                $('#contactFormError').show();
                            })
                        }
                    }); //end ajax
					*/
					$.post("forms/contact.aspx", { 
						name: $('#contactFormName').val(),
						email: $('#contactFormEmail').val(),
						message: $('#contactFormComment').val()
					},
						function(data) {
							if (data != "error") {
                                $('#contactFormLoading').fadeOut(300, function () {
                                    $('#contactFormSuccess').show();
                                })
                            } else {
                                $('#contactFormLoading').fadeOut(300, function () {
                                    $('#contactFormError').show();
                                })
                            }
					});	
















                });
            }); //end contactForm fadeOut function
        } //end if valid

    });

    $(".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');
		
		//initUFO();
    }

    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(' ');
    }

	function initUFO(){
		
		//create my little ufo
		$('body').append('<div id="ufo"><div class="ship"></div><div class="beam"></div><div class="shadow"></div></div>');
		
		//hover up and down
		hoverUFO();
		moveUFO();
		
		
		
		
		//tell my ufo what to do
		
		//tell my ufo what to do when user intereres
		
		
	}
	
	function moveUFO(){		
		var screenWidth = $(window).width() - $('#ufo').width();
		var	screenHeight = $(window).height() - $('#ufo').height();
		
		var randomLeft = Math.floor(Math.random()*screenWidth);
		var randomTop = Math.floor(Math.random()*screenHeight);
		//$('#ufo').animate({	top: '+=50'  }, 5000, function() { });
		var ufoPosition = $('#ufo').position();
		
		var maxSpeed = 100;	
		var diffLeft = ufoPosition.left - randomLeft;
		var diffTop = ufoPosition.top - randomTop;
		var distanceToTravel = Math.sqrt( Math.pow(diffLeft, 2) + Math.pow(diffTop, 2) );
		var speedToDestination = 50 * maxSpeed;		
		
		var ufoSpeed = .25; 
		var ufoTravelTime = distanceToTravel/ufoSpeed;
		
		var maxPitStop = 4000;
		var ufoPitStopDelay = distanceToTravel * 2;//Math.floor(Math.random()*maxPitStop);				
		
		//$('#ufo .beam').html("<span style='color:white;'>randomX: " + randomX + "<br />randomY: " + randomY + "</span>");
		//$('#ufo .beam').html("<span style='color:white;'>X: " + ufoPosition.left + "<br />Y: " + ufoPosition.top + "<br />Distance: " + distanceToTravel);
		$('#ufo').delay(ufoPitStopDelay).animate({	top: randomTop, left:randomLeft  }, ufoTravelTime, function() {moveUFO();});		
	}
	
	function hoverUFO(){}
	
	
	
});
 
 
 
 
 
