var grayOutInputs = function() {
    $("input.grayOut").each(function(){
        if (this.value != this.title && $(this).hasClass("grayOut")) {
            $(this).removeClass("grayOut");
        }
        
        $(this).focus(function () {
            if (this.value == this.title) {
                this.value = "";
                $(this).removeClass("grayOut");                
            }
        });
        $(this).blur(function () {
            if (this.value == "") {            
                $(this).addClass("grayOut");
                this.value = this.title;
            }
        });        
     });
};

var toggleCommentsHandler = function() {
    if($("#toggleComments")) {
        $("#toggleComments").click(function(){
            if ($('#commentsArea:animated').length == 0) {
        	    $('#commentsArea').toggle(400);
        	}
        });        
    }
};

var updateComments = function(data) {
    if (data) {
        var newComment = document.createElement("LI");
        $(newComment).addClass("newComment");
        var name = data['name'];
        if (data['url'].length > 0) {
            name = "<a href=\""+ data['url'] +"\">"+ name +"</a>";
        }
        
        newComment.innerHTML = "<strong>"+ name +"</strong><span class='commentDate'> "+ data['datetime'] +"</span><br />"+ data['message'];
        $("#commentsArea ul")[0].appendChild(newComment);
        $(newComment).fadeIn("slow");
        
        // clean up the form
        $("#nameField").val("");
        $("#urlField").val("");
        $("#messageField").val("");
        $("#wtf").val("");
    }
};

var showErrors = function(data) {
    if (data) {
        // remove errors block if theres one – to avoid duplicates
        $("ul.errors").remove();
        
        // make a new errors block
        var errors = document.createElement("UL");
        $(errors).addClass("errors");
        
        // add all errors as li elements
        errors.innerHTML = "<li class='heading'>Something went wrong with your comment</li>";
        $.each(data, function(){
            errors.innerHTML += "<li>– "+ this +"</li>";
        });                            
        
        // append errors block
        $("#commentsArea")[0].insertBefore(errors, $("#commentForm")[0]);
    }
};

var postComment = function() {

    // remove default "name" and "www" from inputs, if they are there
    if ($("#nameField").val == "name") {
        $("#nameField").val("");  
    }
    
    if ($("#urlField").val == "www") {
        $("#urlField").val("");  
    }
    
    // do ajax post request with json response        
    $.post("/addcomment.php?x=add_comment", { name: $("#nameField").val(), url: $("#urlField").val(), message: $("#messageField").val(), parent_id: $("#imageParentId").val(), parent_name: $("#imageParentName").val(), wtf: $("#wtf").val() },
        function(data){
	        if (!data['message']) {
	            showErrors(data);
			} else {
			    // if there's an error block, remove it
			    $("ul.errors").remove();
			    // update comments
				updateComments(data);
			}
        }, "json");
};

var commentSubmitHandler = function () {
    $("#commentForm").submit(function(ev) {
        ev.preventDefault();
        postComment();
    });
};

var keyboardBrowsing = function () {
    $(document).keyup(function(e){
	    // back 37, 100
	    // fwd 39, 102
	    
	    // next image
	    if ( e.keyCode == 39 || e.keyCode == 102 ) {
	        if ( $("a.next").length ) {
	            document.location = $("a.next")[0].href;
	        }
	    }

		// previous image
	    if ( e.keyCode == 37 || e.keyCode == 100 ) {
	        if ( $("a.prev").length ) {
	            document.location = $("a.prev")[0].href;
	        }
	    }
	});
};

var fadePhoto = function () {
    if (!jQuery.browser['msie'] && $("#photo").length > 0) {
        $("#photo").animate( {opacity: 1}, 500, function (){
            $("#exifContainer").animate( {opacity: 1}, 200);
        });        
    }
};

var mainInit = function() {
    if ( $("#imageContainer").length ) {
        if ( $("#exifBlock").length ) {
            addExifFlashObj();
        }
        toggleCommentsHandler();
        commentSubmitHandler();
        keyboardBrowsing();    
    }    
    grayOutInputs();
};

$(window).load(function(){
    fadePhoto();
});

$(document).ready(function(){
    mainInit();
});