/*
 * Copyright (c) Dreamcatcher Web Solutions 2011. All Rights Reserved.
 *
 * Licensed Materials - Property of Dreamcatcher Web Solutions
 * -------------------------------------------------------------------
 * -------------------------------------------------------------------
 * File name:      main.js
 *
 * Project:        Ronda's Montessori Garden website
 *                 http://www.rondasgarden.net
 *
 * Creation date:  2011-06-27
 *
 * Description:    External JavaScript file for the web site.
 *
 * Notes:          1. Uses jQuery 1.5.1 from Google.
 *                 2. Uses "jQuery Drop Down Menu Plugin" (jddm) code
 *                    from 
 *                    http://javascript-array.com/scripts/jquery_
 *                    simple_drop_down_menu/
 *                 3. Uses "How to create a stunning and smooth popup
 *                    using jQuery" technique to popup a notice img.
 *                    This technique is from yensdesign website,
 *                    http://yensdesign.com/2008/09/how-to-create-a-
 *                    stunning-and-smooth-popup-using-jquery/
 *                 4. Add code to $(document.ready() to make non-link
 *                    parent nav element look like link nav elements.
 *
 * Revision history:
 * Date       Author                 Description
 * ---------- ---------------------  ---------------------------------
 * 2011-06-27 prebman@austin.rr.com  Initial release.
 * 2011-06-30 prebman@austin.rr.com  Add #4 above.
*/

/* ---------------------------------------------------------------- */
/* Global Variables.                                                */
/* ---------------------------------------------------------------- */
var timeout    = 500;				// 500 milliseconds to close dd.
var closetimer = 0;
var ddmenuitem = 0;

var popupStatus = 0;					// Required for notice popup.
 
/* ---------------------------------------------------------------- */
/* $(document).ready() function.                                    */
/*                                                                  */
/* Purpose:  1. Bind events to menu items. (code from jddm)         */
/*           2. Remove last main nav link border-right.             */
/*           3. Link the "notice button" to the popup notice        */
/*              (modified code from "popup")                        */
/*           4. Return false for links marked with class = noLink   */
/*              so won't go to link.                                */
/*           5. Return false for id = popupNoticeClose so won't go  */
/*              to link.                                            */
/*                                                                  */
/* Notes:  None.                                                    */
/* ---------------------------------------------------------------- */
$(document).ready(function()
{
	/* 1. Bind events to menu items.        								  */
	$('#jsddm > li').bind('mouseover', jsddm_open);
	$('#jsddm > li').bind('mouseout', jsddm_timer);
	
	/* 2. Remove last main nav link border-right.                    */
	$('#jsddm li a:last').css('border-right', 'none');
	
	/* 3. Link the "notice button".                                  */
	// LOADING POPUP using the button click event.
	$('.button').click(function()
	{
		// centering with css
		centerPopup();
		// load popup
		loadPopup();
	});
	// CLOSING THE POPUP in 3 different ways:  hitting ESC, Clicking
	// out from the popup, and Clicking on X.
	// Click the x event!
	$('#popupNoticeClose').click(function()
	{
		disablePopup();
	});
	// Click out event!
	$('#backgroundPopup').click(function()
	{
		disablePopup();
	});
	$('#popupNotice').click(function()
	{
		disablePopup();
	});
	//Press ESC event!
	$(document).keypress(function(e)
	{
		if(e.keyCode == 27 & popupStatus == 1)
		{
			disablePopup();
		}
	});
	
	/* 4. Bind a click event on '.noLink' links that returns false.  */
	$('.noLink').click(function()
	{
		return false;
	});
	
	/* 5. Bind a click event on '#popupNoticeClose" link to return   */
	/*    false.																	  */
	$('#popupNoticeClose').click(function()
	{
		return false;
	});
	
});
 
/* ---------------------------------------------------------------- */
/* document.onclick function.                                       */
/*                                                                  */
/* Purpose:  Close open submenu after a click anywhere on the doc.  */
/*                                                                  */
/* Notes:  Code from jddm.                                          */
/* ---------------------------------------------------------------- */
document.onclick = jsddm_close;
 
/* ---------------------------------------------------------------- */
/* jsddm_open() function.                                           */
/*                                                                  */
/* Purpose:  1. Opens "current" submenu, if there is one.			  */
/*              (code from jddm)                                    */
/*                                                                  */
/* Notes:  None.                                                    */
/* ---------------------------------------------------------------- */
function jsddm_open()
{
	// Clear the timer.
	jsddm_canceltimer();
	// Close (hide) any submenu that are open.
	jsddm_close();
	// Open (show) current submenu, if there is one.
	ddmenuitem = $(this).find('ul').css('visibility', 'visible');
}
 
/* ---------------------------------------------------------------- */
/* jsddm_close() function.                                          */
/*                                                                  */
/* Purpose:  Closes "current" submenu.                              */
/*                                                                  */
/* Notes:  Code from jddm.                                          */
/* ---------------------------------------------------------------- */
function jsddm_close()
{
	// If there is a submenu open, close it.
	if(ddmenuitem)
	{
		ddmenuitem.css('visibility', 'hidden');
	}
}
 
/* ---------------------------------------------------------------- */
/* jsddm_timer() function.                                          */
/*                                                                  */
/* Purpose:  Set timeout for open submenus.                         */
/*                                                                  */
/* Notes:  Code from jddm.                                          */
/* ---------------------------------------------------------------- */
function jsddm_timer()
{
	closetimer = window.setTimeout(jsddm_close, timeout);
}
 
/* ---------------------------------------------------------------- */
/* jsddm_canceltimer() function.                                    */
/*                                                                  */
/* Purpose:  Cancel the timeout for open submenus.                  */
/*                                                                  */
/* Notes:  Code from jddm.                                          */
/* ---------------------------------------------------------------- */
function jsddm_canceltimer()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}
 
/* ---------------------------------------------------------------- */
/* loadPopup() function.                                            */
/*                                                                  */
/* Purpose:  Loads the popup with jQuery magic!                     */
/*                                                                  */
/* Notes:  Code from "popup"                                        */
/* ---------------------------------------------------------------- */
function loadPopup()
{
	// loads popup only if it is disabled
	if(popupStatus==0)
	{
		$('#backgroundPopup').css({'opacity': '0.7'});
		$('#backgroundPopup').fadeIn('slow');
		$('#popupNotice').fadeIn('slow');
		popupStatus = 1;
	}
}
 
/* ---------------------------------------------------------------- */
/* disablePopup() function.                                         */
/*                                                                  */
/* Purpose:  Disabling popup with jQuery magic!                     */
/*                                                                  */
/* Notes:  Code from "popup"                                        */
/* ---------------------------------------------------------------- */
function disablePopup()
{
	// disables popup only if it is enabled
	if(popupStatus==1)
	{
		$('#backgroundPopup').fadeOut('slow');
		$('#popupNotice').fadeOut('slow');
		popupStatus = 0;
	}
}
 
/* ---------------------------------------------------------------- */
/* centerPopup() function.                                          */
/*                                                                  */
/* Purpose:  Centering popup.                                       */
/*                                                                  */
/* Notes:  Code from "popup"                                        */
/* ---------------------------------------------------------------- */
function centerPopup()
{
	// request data for centering
	var windowWidth  = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight  = $('#popupNotice').height();
	var popupWidth   = $('#popupNotice').width();
	
	// centering
	$('#popupNotice').css(
	{
		'position': 'absolute',
		'top': windowHeight/2 - popupHeight/2,
		'left': windowWidth/2 - popupWidth/2
	});
	
	// only need force for IE6
	$('#backgroundPopup').css(
	{
		'height': windowHeight
	});
}
 
/* ---------------------------------------------------------------- */
/* completeReset() function.                                        */
/*                                                                  */
/* Called by:  "reset" button's onclick event                       */
/*                                                                  */
/* Purpose:    Hides all sub questions, empty error messages, and   */
/*             sets focus to first field.                           */
/*                                                                  */
/* ---------------------------------------------------------------- */
function completeReset()
{	
	document.getElementById("nameError").innerHTML = "";
	document.getElementById("phoneError").innerHTML = "";
	document.getElementById("emailError").innerHTML = "";
	document.getElementById("radContactPrefError").innerHTML = "";
	document.getElementById("messageError").innerHTML = "";
	
	document.forms["formContact"].name.focus();
	return true;
}
 
/* ---------------------------------------------------------------- */
/* validate() function.                                             */
/*                                                                  */
/* Called by:  "Send Message" button's onclick (submit) event       */
/*                                                                  */
/* Parameters: None                                                 */
/*                                                                  */
/* Purpose:    Ensures all required fields have values and that     */
/*             some values are correctly formatted.                 */
/*                                                                  */
/* ---------------------------------------------------------------- */
function validate()
{
	var aForm = document.forms["formContact"];
	var returnValue = true;			/* true = form validated.          */
	var radioChosen = false;		/* true = radio button clicked.    */
	var strippedEmail = "";       /* Email without blanks.           */
	var strippedPhone = "";			/* Phone number with only digits.  */
	
	/* Get the values of every field in the form.                    */
	var theName = aForm.name.value;
	var thePhone = aForm.phone.value;
	var theEmail = aForm.email.value;
	var theRadContactPref = aForm.radContactPref;
	var theMessage = aForm.message.value;
	
	/* Set all of the error messages to blank.                       */
	document.getElementById("nameError").innerHTML = "";
	document.getElementById("phoneError").innerHTML = "";
	document.getElementById("emailError").innerHTML = "";
	document.getElementById("radContactPrefError").innerHTML = "";
	document.getElementById("messageError").innerHTML = "";
	
	/* Check fields, in reverse order so can put focus on topmost    */
	/* error.                                                        */
	
	// MESSAGE field: only need to check that something is entered.----
	if (theMessage.length == 0)
	{
		// Empty, set error message and focus.
		document.getElementById("messageError").innerHTML = "Please provide a message";
		aForm.message.focus();
		returnValue = false;
	}
	
	// CONTACT PREFERENCE field: only need to check that a choice is-----
	// selected.---------------------------------------------------------
	for (var i = 0; i < theRadContactPref.length; i++)
	{
		if (theRadContactPref[i].checked)
		{
			radioChosen = true;
		}
	}
	if (!radioChosen)
	{
		// Radio button not clicked, set error message and focus.
		document.getElementById("radContactPrefError").innerHTML = "Please select a contact preference";
		document.getElementById("radphone").focus();
		returnValue = false;
	}
	
	// EMAIL field:------------------------------------------------------
	//    1. Check that a value was not entered.-------------------------
	if (theEmail.length == 0)
	{
		// Empty, set error message and focus.
		document.getElementById("emailError").innerHTML = "Please enter your email";
		aForm.email.focus();
		returnValue = false;
	}
	else
	{
		//   2. Check that the e-mail address is properly formated.-------
		// First strip out blanks.----------------------------------------
		strippedEmail = theEmail.replace(/\s/g, "");
		
		// Then check for proper format.----------------------------------
		if (strippedEmail.search(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/) == -1)
		{
			// Error in formation, set error msg and focus.
			document.getElementById("emailError").innerHTML = "Please enter a valid email";
			aForm.email.focus();
			returnValue = false;
		}
	}
	
	// PHONE field:------------------------------------------------------
	//    1. Check that a value was not entered.-------------------------
	if (thePhone.length == 0)
	{
		// Empty, set error message and focus.
		document.getElementById("phoneError").innerHTML = "Please enter your phone number";
		aForm.phone.focus();
		returnValue = false;
	}
	else
	{
		//    2. Check that there are at least 10 digits and no other-----
		//       chars other than "()-. " in the phone number.------------
		// First strip out the non-digit acceptable characters.-----------
		strippedPhone = thePhone.replace(/[\(\)-\.\s]/g, "");
		
		// Now verify only at least digits are left.----------------------
		if (strippedPhone.search(/^\d{10,}$/) == -1)
		{
			// Error, either less than 10 digits, or other chars.
			// Set error message and focus.
			document.getElementById("phoneError").innerHTML = "Please enter a valid phone number";
			aForm.phone.focus();
			returnValue = false;
			
		}
	}
	
	if (theName.length == 0)
	{
		// Empty, set error message and focus.
		document.getElementById("nameError").innerHTML = "Please enter your name";
		aForm.name.focus();
		returnValue = false;
	}
	
	return returnValue;
}
