/*******************************************************************************/
/*                                                                             */
/* Javascript functions for the La Lupa call.html Contact Form web page        */
/* Created: 03 March 2009   Author: John James  Various Sources                */
/* Updated: 04 March 2009   By: JWJ Reason: Correct start of over maxLength    */
/*                                          textarea selection                 */
/* Updated: 18 April 2009   By: JWJ Reason: Remove alert() error messages      */
/*                                          replace by Shadowbox               */
/* Updated: 19 May 2009     By: JWJ Reason: Change Contact default to 'No'     */
/*                                          Add 'Can we quote you?' CheckBox   */
/*                                          Add Caps Lock test/error message   */
/* Updated: 21 Sep 2009     By: JWJ Reason: Add Christmas Day Booking option   */
/*******************************************************************************/

var W3CDOM = document.createElement && document.getElementsByTagName && document.getElementById;
/*window.onload = setMaxLength;*/

function setMaxLength() {
    /*************************************************************************************/
    /* Function to set up the counter for the Comments textarea, if it has a 'maxlength' */
    /* attribute defined, and the onchange/onkeyup event handler (checkMaxLength) that   */
	/* keeps/monitors it.                                                                */
    /*************************************************************************************/
  	if (!W3CDOM) return; 
    /*alert("setMaxLength called");*/
	var commentID = document.getElementById('dComments');
	var counter = document.createElement('div');
	counter.id = 'dcounter';
	counter.className = 'counter';
	if (commentID.getAttribute('maxlength')) {
		var counterClone = counter.cloneNode(true);
		counterClone.innerHTML = '<span>' + commentID.value.length + '</span>/' + commentID.getAttribute('maxlength');
		commentID.parentNode.insertBefore(counterClone,commentID.nextSibling);
		commentID.relatedElement = counterClone.getElementsByTagName('span')[0];
		commentID.onkeyup = commentID.onchange = checkMaxLength;
		commentID.onkeyup();
	}
}
	
function checkMaxLength() {
    /****************************************************************************************/
    /* Function to maintain the textarea counter and update the class if it exceeds its     */
    /* 'maxlength' attribute.                                                               */
    /****************************************************************************************/
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength) {
		this.relatedElement.className = 'toomuch'; }
	else {
		this.relatedElement.className = ''; }	
	this.relatedElement.firstChild.nodeValue = currentLength;
}

function validateEmail(emailStr) {
    /*****************************************************************************************/
    /* Function to validate the generic format of the user-entered email address, using a    */
    /* Valid returns true, false otherwise                                                   */
    /*****************************************************************************************/
    /*alert("validateEmail called");*/      
    var emailPattern = /^[a-zA-Z0-9._\-]+@[a-zA-Z0-9.\-]+\.(?:[a-zA-Z]{2}|aero|arpa|asia|biz|cat|com|coop|edu|gov|info|\i\n\t|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$/;
    return emailPattern.test(emailStr); 
}

function checkSpoof(emailStr){
    /**************************************************************************************/
    /* Function to test the user-entered email address for a few obvious silly user names */
    /* Returns 'false' if they're found.                                                  */
    /**************************************************************************************/
    /*alert("checkSpoof called");*/
    var spoofNamesPat;      /* Some common spoof email user names */ 
    spoofNamesPat = /mickey\.mouse|donald\.duck|pluto|ghenghis\.khan|ghengis\.khan|genghis\.khan|adolf\.hitler|fred\.nurke|anon|nowhere|noone|nobody|hahaha|emailthis|spoof/;
    var checkStr;
    checkStr = emailStr.match(spoofNamesPat);
    /*alert("checkStr: " + checkStr);*/
    return checkStr;
}

function checkEmail() {
    /**************************************************************************************/
    /* Function to check the email address has been entered, and is valid. Returns 'false'*/
    /* to the validateForm fn if not.                                                     */
    /**************************************************************************************/
    /*alert("checkEmail called"); */
    var emailID;
    emailID = document.getElementById("dEmailField");
    var emailStr;
    emailStr = emailID.value;
    var contactboxID;
    contactboxID = document.getElementById("ContactBox");
    /*alert("emailStr: " + emailStr);*/
    if (contactboxID.checked)
    {
		/*Check they entered anything at all; if not, complain appropriately and focus on the field in error*/
        if ((emailStr === null) || (emailStr === "")) {
			var selectionboxID;
			selectionboxID = document.ContactForm.SelectionBox;
			var selectionValue;
			selectionValue = selectionboxID.options[selectionboxID.selectedIndex].value;
			if (selectionValue === "Christmas Day Booking") {
				Shadowbox.open({player:"inline", 
						content:"#missingxmasemail", 
						title:"Missing Email", 
						height:150, width:250,
						options:{onClose:function(){emailID.focus();}}
                        }
                        );
			} 
			else {
				Shadowbox.open({player:"inline", 
						content:"#missingemail", 
						title:"Missing Email", 
						height:150, width:250,
						options:{onClose:function(){emailID.focus();}}
                        }
                        );
			}
			return (false);
		}
		/*Check the basic email address is valid; if not, complaint and focus & select the field in error   */
        if (validateEmail(emailStr) === false) {
            Shadowbox.open({player:"inline", 
                            content:"#invalidemail", 
                            title:"Invalid Email", 
                            height:150, width:250, 
                            options:{onClose:function(){emailID.focus(); emailID.select();}}
                            }
                          );
            return (false); }
        /* Check for a few common spoof email addresses that might be put in */
        /*alert("checkSpoof: " + checkSpoof(emailStr)); complaint and focus & select field in error if they have*/
        var matchStr;
        matchStr = checkSpoof(emailStr);
        if (matchStr !== null) {
            document.getElementById('emailaddr').innerHTML=emailStr;
            Shadowbox.open({player:"inline", 
                            content:"#spoofemail", 
                            title:"Email: pull the other one!", 
                            height:150, width:250,
                            options:{onClose:function(){emailID.focus(); emailID.select();}}
                            }
                          ); 
            return (false); }
    }
    /**********************************************************************************************************************/
    /* Either no email address is required (ContactBox chkBox unchecked) or we have a valid and acceptable email address. */
	/* In either case return 'true' to allow processing to continue.                                                      */
    /**********************************************************************************************************************/
    return (true);
}

function checkPhone() {
	/**************************************************************************************/
	/* Function to check Phone Number has been entered IF it's a Christmas Day Booking;   */
	/* otherwise Phone Number is always optional                                          */
	/**************************************************************************************/
	var selectionboxID;
	selectionboxID = document.ContactForm.SelectionBox;
	var selectionValue;
	selectionValue = selectionboxID.options[selectionboxID.selectedIndex].value;
	if (selectionValue === "Christmas Day Booking")
	{	var phoneID = document.getElementById("dPhoneField"); 
        if ((phoneID.value === null) || (phoneID.value === ""))
		{
		    Shadowbox.open({player:"inline", 
                    content:"#missingphone", 
                    title:"No Phone Number", 
                    height:150, width:250, 
                    options:{onClose:function(){phoneID.focus();}}
                    }
                    );
			return (false);
		}
	}
	return (true);
}
	

function textboxSelect(oTextbox, iStart, iEnd) { 
    /*************************************************************************************/
    /* Function to select text in a textarea. Depending of no of parameters passed, it   */
    /* will select all, First(n), or char(x) to char(y).                                 */     
    /*************************************************************************************/
    switch (arguments.length) { 
    case 1: 
        oTextbox.select(); 
        break; 
    case 2: 
        iEnd = oTextbox.value.length; 
        /* falls through */ 
    case 3:          
        if (oTextbox.setSelectionRange) 
        { 
            oTextbox.setSelectionRange(iStart, iEnd); 
        }
	    else 
        {
            if (oTextbox.createTextRange) 
            {
                var oRange;
                oRange = oTextbox.createTextRange();
                oRange.moveStart("character", iStart);
                oRange.moveEnd("character", iEnd);      
                oRange.select(); 
            }
		}                                              
    } 
}

function checkCommentLength() {
    /*****************************************************************************************/
    /* Function to check the number of characters in the Comment field and, if > 'maxlength' */
    /* select the extra text, alert he user and return 'false' to the validateForm fn.       */
    /*****************************************************************************************/
    /*alert("checkCommentLength called");*/
    var commentID;
    commentID = document.ContactForm.Comments;
	var maxLength;
    maxLength = commentID.getAttribute('maxlength');
    var commentLength;
    commentLength = commentID.value.length;
	var excessLength;
    excessLength = commentLength - maxLength;
    var selectStart;
    selectStart = maxLength;
    /*alert("checkCommentLength(): \r\n commentLength: " + commentLength +
            "\r\n excessLength: " + excessLength + "\r\n maxLength: " + maxLength +
            "\r\n selectStart: + selectStart);*/
	var charS;
    charS = "";
    if (commentLength < 1)
    {

        Shadowbox.open({player:"inline", 
                        content:"#missingcomment", 
                        title:"No Comments", 
                        height:150, width:250, 
                        options:{onClose:function(){commentID.focus();}}
                        }
                    );
        return (false);
    }
	if (excessLength > 0) 
    {
        if (excessLength > 1) { charS = "s"; }
            document.getElementById('maxlength').innerHTML=maxLength;
			document.getElementById('excesslength').innerHTML=excessLength;
			document.getElementById('ess').innerHTML=charS;
            Shadowbox.open({player:"inline", 
                            content:"#overlength", 
                            title:"Overlength Comments!", 
                            height:150, width:250,
                            options:{onClose:function(){commentID.focus(); textboxSelect(commentID, selectStart, commentLength);}}
                            }
                          ); 			  
		return (false); 
    }
	else 
    {
    	return (true); 
    }
}

function checkName() {
    /*****************************************************************************************/
    /* Function to check something has been typed into the Name field.  Warns the user and   */
    /* returns 'false' to validateForm fn if not                                             */
    /*****************************************************************************************/
    var nameID = document.ContactForm.Name;
	if ((nameID.value === null) || (nameID.value === "")) {
		Shadowbox.open({player:"inline", 
                        content:"#missingname", 
                        title:"No Name", 
                        height:150, width:250, 
                        options:{onClose:function(){nameID.focus();}}
                        }
                    );	
		return (false); }
	else {
	   return (true)};
}

function checkMailHeader() {
    /****************************************************************************************/
    /* Function to check a valid Topic has been selected or, if 'Other' has been selected,  */
    /* the user has typed their own topic into the field provided for them. If not, returns */
    /* false to validateForm fn.  If yes, puts the user's topic in the right hidden input   */
    /* field and returns 'true'                                                             */
    /****************************************************************************************/
    var selectionboxID;
    selectionboxID = document.ContactForm.SelectionBox;
    var otherfieldID;
    otherfieldID = document.ContactForm.OtherField;
    var fm_mailheaderID;
    fm_mailheaderID = document.ContactForm.fm_mailheader;
    /*alert("CheckMailHeader called \r\n" + " otherfield.value: " + otherfieldID.value + "\r\n" + 
            "selectionbox.value: " + selectionboxID.options[selectionboxID.selectedIndex].value + "\r\n" + 
            "SelectedIndex: " + selectionboxID.selectedIndex);*/
    if (selectionboxID.options[selectionboxID.selectedIndex].value === "Other")
    {
        if ((otherfieldID.value === null) || (otherfieldID.value === ""))
        {
			Shadowbox.open({player:"inline", 
							content:"#missingtopic", 
							title:"No Topic", 
							height:150, width:250, 
							options:{onClose:function(){otherfieldID.value = "Please enter your own topic";
														selectionboxID.style.color = "black";
														otherfieldID.focus();
														otherfieldID.select();}
									}
							}
						);				
            return (false);
        }
        else
        {   selectionboxID.style.color = "black";
            fm_mailheaderID.value = otherfieldID.value;
            return (true);
        }
    }
    else
    {
        if (selectionboxID.selectedIndex === 0)
        {
            /*alert("Please select the topic of your communication");*/
			Shadowbox.open({player:"inline", 
							content:"#selecttopic", 
							title:"Select Topic", 
							height:150, width:250, 
							options:{onClose:function(){selectionboxID.focus();}
									}
							}	
						);				
            return (false);
        }
        else
		{
			selectionboxID.style.color = "black";
			fm_mailheaderID.value = selectionboxID.options[selectionboxID.selectedIndex].value;
            return (true);
		}
    }
}

function shiftFocusToOtherField() {
    /*****************************************************************************************/
    /* Function to set up the Other Topic field.  Separate function to workaround Chrome bug */
    /* with focus() change in event handler.                                                 */
    /*****************************************************************************************/
    /*alert("shiftFocusToOtherField called");*/
    document.getElementById("dOtherField").disabled = false;
    document.getElementById("dOtherField").style.visibility = "visible";
    document.getElementById("dOtherField").value = "Type your topic here ...";
    document.getElementById("dOtherField").select();
    document.getElementById("dOtherField").focus();
}

function resetOtherField() {
    /*****************************************************************************************/
    /* Function fired on Form Reset to ensure the 'Other' topic entry field is not displayed */
    /*****************************************************************************************/
    /*alert("resetOtherField called");*/
    document.getElementById("dOtherField").disabled = true;
    document.getElementById("dOtherField").style.visibility = "hidden";
    document.getElementById("dOtherField").value = "";
    document.getElementById("dOtherField").blur();
}

function resetQuoteBox() {
    /****************************************************************************************/
    /* Function fired on Form Reset to ensure the 'QuoteBox' ChkBox and Label are reset     */
    /****************************************************************************************/
    /*alert("resetQuoteBox called");*/
    document.getElementById("QuoteBox").checked = true;
    document.getElementById("QuoteBox").value = "Yes, I'm happy to be quoted";
    document.getElementById("QuoteBoxLabel").innerHTML = "Yes, I'm happy to be quoted";
}

function checkSelection() {
    /*****************************************************************************************/
    /* Function to check the Topic and enable the 'Other' input field if 'Other' has been    */
    /* selected.  Also, If Christmas Day Booking, make Contact required by setting email and */
	/* phone fields to required                                                              */
    /*****************************************************************************************/
    var selectionboxID;
    selectionboxID = document.ContactForm.SelectionBox;
    var selectionValue;
    selectionValue = selectionboxID.options[selectionboxID.selectedIndex].value;
    selectionboxID.style.color = "black";
    /*alert("selectionValue: " + selectionValue);*/
    if (selectionValue === "Other")
    {
        var resultVar = setTimeout(shiftFocusToOtherField, 1);
		/*********************************************************************************/
        /* Above is workaround for Chrome bug in onchange() whereby selectbox text isn't */
        /* updated if .select or .focus is run within the same event handler function    */
		/*********************************************************************************/
    }
    else
    {	var contactboxID = document.getElementById("ContactBox");
        if (selectionValue === "Christmas Day Booking")	/* Christmas Day Booking */
		{	contactboxID.checked = true; }
		else
		{	contactboxID.checked = false; }
		testContactBox();
		document.getElementById("dOtherField").disabled = true;
        document.getElementById("dOtherField").style.visibility = "hidden";
    }
}

function resetContactFields() {
    /*****************************************************************************************/
    /* Function resets Contact Fields to default. Also called on Form Reset.                 */
    /*****************************************************************************************/
    document.getElementById("ContactBoxLabel").innerHTML = "No, thank you";
    document.getElementById("dEmailLabel").style.color = "grey";
    document.getElementById("dEmailLabel").innerHTML = "Your eMail";
    document.getElementById("dEmailField").disabled = true;
    document.getElementById("dEmailField").value = "Not required";
    document.getElementById("dEmailField").style.color = "grey";
    document.getElementById("dPhoneLabel").style.color = "grey";
    document.getElementById("dPhoneLabel").innerHTML = "Your Phone No";
    document.getElementById("dPhoneField").disabled = true;
    document.getElementById("dPhoneField").value = "Not required";
	document.getElementById("dPhoneField").style.color = "grey";

}

function testContactBox() {
    /******************************************************************************************/
    /* Function enable/disables the contact fields according to the CheckBox setting.         */
    /******************************************************************************************/
    /*alert("testCheckBox called");*/
	var ChkBox = document.getElementById('ContactBox');
    if (ChkBox.checked)
    {
        ChkBox.value = "Yes, please";
        document.getElementById("ContactBoxLabel").innerHTML = "Yes, please";
        document.getElementById("dEmailLabel").style.color = "black";
        document.getElementById("dEmailLabel").innerHTML = "Your eMail (reqd)";
        document.getElementById("dEmailField").value = "";
        document.getElementById("dEmailField").style.color = "black";
        document.ContactForm.fm_from.value = document.ContactForm.fm_defaultFrom.value;
        document.getElementById("dEmailField").disabled = false;
        document.getElementById("dPhoneLabel").style.color = "black";
		var selectionboxID;
		selectionboxID = document.ContactForm.SelectionBox;
		var selectionValue;
		selectionValue = selectionboxID.options[selectionboxID.selectedIndex].value;
		if (selectionValue === "Christmas Day Booking")
		{	document.getElementById("dPhoneLabel").innerHTML = "Your Phone No (reqd)";	}
		else
		{	document.getElementById("dPhoneLabel").innerHTML = "Your Phone No (opt)";	}
        document.getElementById("dPhoneField").disabled = false;
        document.getElementById("dPhoneField").style.color = "black";
        document.getElementById("dPhoneField").value = "";
    }
	else
	{
        resetContactFields();
    }
}

function testQuoteBox(QuoteBox) {
    /****************************************************************************************/
    /* Function enable/disables the Quote fields according to the CheckBox setting.         */
    /****************************************************************************************/
    /*alert("testQuoteBox called");*/
    if (QuoteBox.checked)
    {   /*alert("QuoteBox checked");*/
        QuoteBox.value = "Yes, I'm happy to be quoted";
        document.getElementById("QuoteBoxLabel").innerHTML = "Yes, I'm happy to be quoted";
    }else{ /*alert("QuoteBox unchecked");*/
        QuoteBox.value = "No, I prefer not to be quoted";
        document.getElementById("QuoteBoxLabel").innerHTML = "No, I prefer not to be quoted";
    }
}

function validateForm() {
    /******************************************************************************************/
    /* Function invoked by form submit button. It controls final validation & returns 'true'  */
    /* to submit the form if all fields validate OK, or 'false' to prevent submission if not. */
    /******************************************************************************************/
    /*alert("validateForm() called");*/
    if ((checkName() === true) && (checkMailHeader() === true) && (checkEmail() === true) && (checkPhone() === true) && (checkCommentLength() === true))
    {
        /*alert("Return true");*/
		var selectionboxID;
		selectionboxID = document.ContactForm.SelectionBox;
		var selectionValue;
		selectionValue = selectionboxID.options[selectionboxID.selectedIndex].value;
		if (selectionValue === "Christmas Day Booking")
		{	document.getElementById("fm_privateURL").value = "http://www.la-lupa-3.co.uk/xmasreply.html"	}
		else
		{	document.getElementById("fm_privateURL").value = "http://www.la-lupa-3.co.uk/reply.html"; }
		return (true);
    }
	else 
    {
        /*alert("Return false");*/
		return (false);
    }
}

function resetMaxLength() {
    /*************************************************************************************/
    /* Function invoked by form reset button. It resets the value of the textarea, and   */
    /* forces an onkeyup to reset the counter.                                           */
    /*************************************************************************************/
    /*alert("maxLength: " + document.getElementById("dComments").getAttribute('maxlength'));*/
    var commentID = document.getElementById("dComments");
    commentID.value = "";
    commentID.onkeyup();
}

function resetForm() {
    /*****************************************************************************************/
    /* Function invoked by form Reset button.  It gets confirmation from the user that they  */
    /* really mean to reset.  If yes, it also resets the textarea counter and Contact fields.*/
    /*****************************************************************************************/
    /*alert("resetForm() called");*/ 
    resetMaxLength();
    resetOtherField();
    resetQuoteBox();
    resetContactFields();
    return (true);
}

