﻿//
// register all JQuery functions once the document is loaded. NOTE: anonymous functions are used below because
// they don't pollute the global namespace. 
// See http://jqfundamentals.com/book/book.html#javascript-basics.sections.self-executing-functions
//
$(document).ready(function() {

// ********************************************************************************** 
//
// Install the placeholder plug-in for input and textarea elements, so you can have HTML like:
// <textarea placeholder="Don&rsquo;t forget to let me know your name and email address!"
//  cols="20" rows="10"></textarea>
    $(function() {
        $('input, textarea').placeholder();
    });

// ********************************************************************************** 
//
// setup script for the contact form. Post the form to EE's email handler via AJAX
// and display an appropriate success or failure message.
//
// NOTE: for this to work, you need an .htaccess file that resolves highintegritydesign.com and 
// www.highintegritydesign.com as the same host. Otherwise you'll get AJAX failures because the same
// origin policy will be violated. If visitors submit more than once in quick succession, they will get a
// "not authorized" error from EE.
//
    $(function() 
	{
		/* helper function to display a message describing the results of the form submit */
		function displayAjaxMessage(message)
		{
			$(".contact-message").html(message);
			$(".contact-message-box").fadeIn(1000);
			$(".contact-message-box").show();
			$(".contact-message").show(); 
		}
		
		/* attach a submit handler to the contact form. By default, EE generates the ID "contact_form" */
		$("#contact_form").submit(function(event) 
		{
			/* stop the contact form from submitting normally */
			event.preventDefault(); 
			
			/* hide any left over message from a previous submit */
			$(".contact-message-box").hide();
			$(".contact-message").hide();
			
		
			/* if they didn't actually enter anything, don't bother executing the AJAX call */
			if (($('#message').val() == "Don\’t forget to let me know your name and email address!") 
						     || ($.trim($('#message').val()).length == 0))
			{
				displayAjaxMessage("Please enter a message.");	
				return;
			}
		
			/* send the form data using post and check the results for any errors*/	
			$.ajax(
			{
				url: "/",
				type: "post",
				dataType: "html",			
				data: $(this).serialize(),
				
				/* If there was some kind of an AJAX error, display an appropriate message or take some other action of your choice */
				error: function(jqXHR, textStatus, errorThrown)
				{
					displayAjaxMessage("I apologize! For some reason your email could not be sent. I&rsquo;d like to hear from you, so please do contact me at 541-760-2907.");
				},
		
				/* 	parse the HTML returned by EE to see if they forgot to enter an email address or a message. 
					If so, the HTML will contain a specific error string we can match, and then we can display our own message */
				success: function(html, textStatus, jqXHR) 
				{
					if (html.match(/<title>Error<\/title>/)) 
					{
						var error = $(html).find('ul li:first').text();	
						if (error == "A valid sender email is required")
						{
							displayAjaxMessage("Please enter your email address.");
						}
						else if (error == "Email Message is Required")					
						{
							displayAjaxMessage("Please enter a message.");						
						}
					}
					else
					{
						displayAjaxMessage("Thanks for contacting me! Your email has been sent.");
					}
				}
	
			});
		});
	});



// ********************************************************************************** 
//
// setup script for the comment form. Post the form to EE's comment form handler via AJAX
// and display an appropriate success or failure message.
//
// NOTE: for this to work, you need an .htaccess file that resolves highintegritydesign.com and 
// www.highintegritydesign.com as the same host. Otherwise you'll get AJAX failures because the same
// origin policy will be violated. If visitors submit more than once in quick succession, they will get a
// "not authorized" error from EE.
//
    $(function() {
        $('#comment_form').ajaxForm({
            url: 'http://www.highintegritydesign.com',
            success: function(data) {
                if (data.match(/<title>Error<\/title>/)) {
                    //grab the error message
                    var error = $(data).find('ul li:first').text();
        
                    // if they didn't enter any comment, this is the error we'll get back from the server
                    if (error == 'The comment field is required')
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Please enter a comment.</p>');
                    } 
					// no name was entered
					else if (error == "The name field is required")
					{ 
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Please enter your name.</p>');
                    }
					// no email address entered
					else if (error == "The email field is required")
					{					
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Please enter your email.</p>');
                    }
                    // email provided but it is invalid according to EE
                    else if (error == "The email address you submitted is not valid")
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Oops! That email address appears to be invalid. Please enter a valid email address.</p>');                    
                    }
                    // this will happen if EE thinks the URL they entered is invalid
                    else if (error == "The URL you submitted is invalid")
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Oops! The URL appears to be invalid. Please check it and try again.</p>');                    
                    }
                    // this shouldn't happen since {if allow_comments} shouldn't display the form. 
                    // But, just in case comments are expired...
                    else if (error == "Commenting is not available in this channel entry.")
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Sorry! Comments are expired for this post.</p>');                    
                    }
                    // I think this could happen if they use the same name as someone else, but with a different email address
                    else if (error == "The name you are posting with is reserved.  Please choose a different name.")
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Oops, someone else already has that user name. Please choose a different one.</p>');                    
                    }
                    // this isn't likely but could happen
                    else if (error == "The email address you submitted is banned")
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Oops! That email address is banned. Please use a different one or <a href="/contact">contact me</a> for help.</p>');                    
                    }
                    // this will happen if they enter more than 5K of text in the comment.
                    else if (error.indexOf("The comment you submitted contains") != -1)
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Oops, comments can be at most 5,000 characters. Please make your comment a bit smaller.</p>');                    
                    }
                    // if they have a quick trigger finger, cool them off a little. This shouldn't happen based on my current EE setting
                    else if (error.indexOf("You are only allowed to post comments every") != -1)
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Sorry, new comments are only allowed every 15 seconds.</p>');                    
                    }
                    // this could happen if they hit submit twice in a row
                    else if (error == "Unable to receive your comment at this time.")
                    {
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Oops! It appears that the comment is a duplicate of the previous one. Please try entering a different comment.</p>');                    
                    }
					// else some other kind of error occurred
					else  
					{
                        $('.comment-message').replaceWith('<p class="comment-message mtm mbm">I&rsquo;m sorry! for some reason the comment form isn&rsquo;t working at this time. Please <a href="/contact">contact me</a> for help.</p>');  					 
					}
				}
				else {
					// clear any leftover errors that may be showing on the form    
					$('.comment-message-box').hide(); 
					// else no error, fix up a success message
                    $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Thanks for your comment!</p>');
                    }
                    // display the return message box
                    $('.comment-message-box').fadeIn(1000); 
					// remove the active state from the submit button
					$('#comment-button').blur();
                },
            dataType: 'html'
        });
    });

// ********************************************************************************** 
//
// make the comment form submit link behave as if it's a submit button.
//
    $(function() {
        $('#comment-button').click(function(e) {
            e.preventDefault(); // prevent the browser from "jumping" on the page when it comes back from AJAX. 
            $('.comment-message-box').hide(); // clear any leftover errors that may be showing on the form    
            $('.comment-message').replaceWith('<p class="comment-message mtm mbm">Sending your comment...</p>');			
            $('.comment-message-box').fadeIn(1000); // display the sending comment message 			
            $('#comment_form').submit(); 
        });
    });
    

// ********************************************************************************** 
//
// convert all img.captions into HTML5 <figure> and <figcaption>. For discussion, see: 
// http://www.highintegritydesign.com/blog/articles/image-captions-in-html5-using-figcaption-and-jquery
//
(function($) {
	$.fn.captionate = function() {
		return this.each(function() { 
            
            var   $this = $(this), // save a reference to the current img.caption element
                    altText = $this.attr('alt'), // grab the value of the image ALT attribute		
                    imgWidth = $this.width(), // grab the width of the image
                    classList = $this.attr('class'); // save any classes attached to the <img>

            $this.removeAttr('class'); // remove any classes from the original <img> element
            
            // check and see if the image is contained in an immediate parent anchor link. 
            // if it is, construct a <figure> wrapping the anchor link instead of wrapping the <img>
            // add the <figcaption> after the link, using the ALT element
            // set the <figure> width to be the same as the <img>
            // add back in any classes from the original <img> to the new <figure>
            // finally move the new <figure> to be just before the paragraph it was contained in.
            var $parentAnchorLink = $this.parent();
            if ($parentAnchorLink.is('a')) {
                $newFigure = $parentAnchorLink.wrap('<figure></figure>').parent(); 
                $parentAnchorLink.after('<figcaption>' + altText + '</figcaption>');
                $newFigure.width(imgWidth);
                $newFigure.addClass(classList);
                $newFigure.parent('p').before($newFigure);                
            }
            // or else it's just an image tag, not wrapped with an anchor link.
            // so do all the same as above except wrap the <img> instead of an anchor link
            else {
                $newFigure = $this.wrap('<figure></figure>').parent(); 
                $this.after('<figcaption>' + altText + '</figcaption>');
                $newFigure.width(imgWidth);
                $newFigure.addClass(classList);
                $newFigure.parent('p').before($newFigure);                
            }
        });
    };
})(jQuery);
    

// ********************************************************************************** 
//
// turn on the captionate script
//
$(function() {	
    $('img.caption').captionate();
});


    
// ********************************************************************************** 
//
// turn on code prettify-cation script by Google    
    $(function() {    
         prettyPrint();
    });
});
