

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// -- -   T H e   J a V a S C R i P T   P o S T a L   W o R K e R   - -- //
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
// Author: mattc
// http://www.orange-splotch.com
// contains hacks of code by Stephen Poley
// http://www.xs4all.nl/~sbpoley/webmatters/formval.js
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

// == =                        G L o B a L S                        = == //
var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
emptyString = /^\s*$/;
aId = 0;
numAttachments = 0;

// == =           F u N C T i o N   D e F i N i T i o N S           = == //

if( document.addEventListener ) {
	document.addEventListener( 'DOMContentLoaded', cmxform, false);
}
window.onload = function () { initializeform(); };

/* Storybook Contact Form Mozilla Fix
   making the contact form a little more charming.
	 This only runs in Mozilla base browsers. */
function cmxform(){
  // Hide forms
  $( 'form.cmxform' ).hide().end();

  // Processing
  $( 'form.cmxform' ).find( 'li/label' ).not( '.nocmx' ).each( function( i ){
    var labelContent = this.innerHTML;
    var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
    var labelSpan = document.createElement( 'span' );
        labelSpan.style.display = 'block';
        labelSpan.style.width = labelWidth;
        labelSpan.innerHTML = labelContent;
    this.style.display = '-moz-inline-box';
    this.innerHTML = null;
    this.appendChild( labelSpan );
  } ).end();

  // Show forms
  $( 'form.cmxform' ).show().end();
}

function initializeform() {
  // Storybook specifics
  // -----------------------
  // Hide optional fields
  hideOptional();
  $( '#addition_link' ).wrap('<a id="link_showHideOptional" onclick="showOptional();" class="clickable"></a>');

  // Remove the attach image field and add an attach image link
  $( '#l_userfile' ).remove();
  $( '#userfile_input' ).remove();
  $( '#attachment_fields' ).after('<a class="clickable" id="add_attach" onclick="addAttachment()">&#187; Attach a storybook image to your message</a>');
}

function hideOptional () {
	$( '#link_showHideOptional' ).set('onclick','showOptional();');
  $( '#optional_fields' ).hide().end();
}

function showOptional () {
	$( '#link_showHideOptional' ).set('onclick','hideOptional();');
	$( '#optional_fields' ).show().end();
}

function addAttachment () {
	if (numAttachments < 3) {
		$( '#attachment_fields' ).append('<li id="li_'+aId+'"><label for="userfile_'+aId+'">Image to attach</label> <input name="userfile_'+aId+'" id="userfile_'+aId+'" size="30" type="file" /> <a class="clickable" onclick="removeAttachment(\''+aId+'\')">Delete</a></li>');
		++aId;
		++numAttachments;
	}
	if (numAttachments == 3) {
		$( '#add_attach' ).remove();
	}
}

function removeAttachment ( attachId ) {
	$( '#li_' + attachId ).remove();
	if (numAttachments == 3) {
		$( '#attachment_fields' ).after('<a class="clickable" id="add_attach" onclick="addAttachment()">&#187; Attach a storybook image to your message</a>');
	}
	--numAttachments;
}

function trim(str) {
// trim leading and trailing whitespace from str
  return str.replace(/^\s+|\s+$/g, '')
} // end function trim
//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  //

function alertMessage (elem_id, err_type, message_str) {
// put an alert for the user that there is a problem
// an empty message_str erases a previous message

	// setting an empty string can give problems if later set to a
  // non-empty string, so ensure a space present. (For Mozilla and
	// Opera one could simply use a space, but IE demands something
	// more, like a non-breaking space.)

  var message_disp;
  if (emptyString.test(message_str))
    message_disp = String.fromCharCode(nbsp);
  else
    message_disp = message_str;

  var elem = document.getElementById(elem_id);
  elem.firstChild.nodeValue = message_disp;

  elem.className = err_type;
} // end function errorAlert
//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  //

function isEmpty (element) {
// returns whether the 'element' is empty or not
	if ( !element.value ) return true;
	if ( element.value == null || element.value == '' ) return true;
	return false;
}

function validateInput (element) {
// validate the input 'element'

	switch (element.id) {
		case 'mailfromname_input':
			if (isEmpty (element)) {
				alertMessage ('name_error', 'required', 'Required.');
				return;
			}
			alertMessage ('name_error', 'required', ''); // no problems
			break;
		case 'city_input':
			if (isEmpty (element)) {
				alertMessage ('city_error', 'required', 'Required.');
				return;
			}
			alertMessage ('city_error', 'required', ''); // no problems
			break;
		case 'state_input':
			if (isEmpty (element)) {
				alertMessage ('state_error', 'required', 'Required.');
				return;
			}
			alertMessage ('state_error', 'required', ''); // no problems
			break;
		case 'mailfromaddress_input':
			if (isEmpty (element)) {
				alertMessage ('email_error', 'required', 'Required.');
				return;
			}

			var return_addr = trim(element.value);
			var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
			if (!email.test(return_addr)) {
				alertMessage ('email_error', 'required', 'Address not valid .');
				return false;
			}

			var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
			if (!email2.test(return_addr)) {
				alertMessage ('email_error', 'warning', 'Unusual e-mail address - check if correct.');
				return true;
			}
			alertMessage ('email_error', 'warning', ''); // no problems
			break;
		case 'comments_input':
			if (isEmpty (element) || element.value == 'Place comments here.') {
				alertMessage ('message_error', 'required', 'Message is required.');
				return;
			}
			alertMessage ('message_error', 'required', ''); // no problems
			break;
	}
	return true;
} // end function validateInput
//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  //

function validatePostage () {
// This function checks a mail form
// to ensure that all required information
// is submitted and valid

	// REQUIRED FIELDS: name, email, message

	var error = 0;

	if ( !document.getElementById ('WSCForm') ) {
		// they aren't even on the contact page
		return false;
	}

	// check for sender name
	if ( !validateInput (document.getElementById ('mailfromname_input')) ){
		if (!error) document.getElementById ('mailfromname_input').focus();
		error++;
	}

	// check for sender city
	if ( !validateInput (document.getElementById ('city_input')) ){
		if (!error) document.getElementById ('city_input').focus();
		error++;
	}

	// check for sender state
	if ( !validateInput (document.getElementById ('state_input')) ){
		if (!error) document.getElementById ('state_input').focus();
		error++;
	}

	// check for sender email
	if ( !validateInput (document.getElementById ('mailfromaddress_input')) ){
		if (!error) document.getElementById ('mailfromaddress_input').focus();
		error++;
	}

	// check for message
	if ( !validateInput (document.getElementById ('comments_input')) ){
		if (!error) document.getElementById ('comments_input').focus();
		error++;
	}

	if ( error ) {
		alert ('There is an error in the information you have submitted.\nPlease correct before sending your message.');
		return false;
	}

	// if you got this far, everything is good
	// so send the message
	document.getElementById('WSCForm').submit();
	return true;

} // end function validatePostage
//  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  //

function clearText (element) {
// remove the standard text from a textarea
	if (element.value == 'Place comments here.')
		element.value = '';

	return;
}