
var VVV_NBSP = 160;		// non-breaking space char
var VVV_NODE_TEXT = 3;	// DOM text node-type
var VVV_EMPTY_STRING = /^\s*$/ ;
var vvvGlobalValueField;	// the field to set after the timer delay


// trim whitespace
function vvvTrim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


function vvvSetFocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  vvvGlobalValueField = valfield;
  setTimeout('vvvSetFocusDelayed()', 100);
}


// delay focus to get around IE bug
function vvvSetFocusDelayed()
{
  vvvGlobalValueField.focus();
}



// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function vvvMessage(fld,     // id of element to display message in
                    msgtype, // class to give element ("warn" or "error")
                    message) // string to display
{
  // 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 dispmessage;
  if (VVV_EMPTY_STRING.test(message)) 
    dispmessage = String.fromCharCode(VVV_NBSP);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}


// --------------------------------------------
//            vvvIsFieldSet
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation is OK), 
//         false (validation failed)
// --------------------------------------------
// return true if the record is OK
function vvvIsFieldSet(valfield,   // element to be validated
                       infofield)  // id of element to receive info/error msg
{
    if (!document.getElementById) return true;  // not available on this browser - leave validation to the server
    var elem = document.getElementById(infofield);
    if (!elem.firstChild) return true;  // not available on this browser
    
    if (valfield.type == "select-one")
    {
        if (valfield.selectedIndex == null) 
        {
            vvvMsg(infofield, "error", "ERROR: required");  
            vvvSetFocus(valfield);
            return false;
        }
        return true;
    }
        
    if (elem.firstChild.nodeType != VVV_NODE_TEXT && valfield.type != "textarea") return true;  // infofield is wrong type of node  
    
    if (VVV_EMPTY_STRING.test(valfield.value)) 
    {
        vvvMsg(infofield, "error", "ERROR: required");  
        vvvSetFocus(valfield);
        return false;
    }
    return true;
}



// --------------------------------------------
//               vvvValidateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------
function vvvValidateEmail(valfield,   // element to be validated
                          infofield)  // id of element to receive info/error msg
{
    var stat = vvvIsFieldSet(valfield, infofield);
    if (stat == false) return false;
    
    var tfld = vvvTrim(valfield.value);  // value of field with whitespace trimmed off
    var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
    if (!email.test(tfld)) 
    {
        vvvMsg(infofield, "error", "ERROR: not a valid e-mail address");
        vvvSetFocus(valfield);
        return false;
    }
    return true;
}


// return true if form is valid, false if one or more errors
function vvvIsFormValid(theForm)
{
    var formIsValid = true;
    for (i=0; i<theForm.length; i++)
    {
        element = theForm.elements[i];
        if (!vvvIsElementValid(element))
        {
            formIsValid = false;
        }
    }
    return formIsValid;
}


// returns true if the element validates OK
function vvvIsElementValid(element)
{
    if (element == null)
    {
        return true;  // ignored - ok
    }
    var statusElementId = element.name;
    if (document.getElementById(statusElementId) == null)
    {
        return true;  // field not present, so no validation required for this field
    }
    
    if (element.type == "text" || element.type == "textarea")
    {
        if (statusElementId.indexOf("email", 0) >= 0)
        {
            return vvvValidateEmail(element, statusElementId);
        }
        else
        {
            return vvvIsFieldSet(element, statusElementId);
        }
    }
    return vvvIsFieldSet(element, statusElementId);
}





/* ================== */
/* IMPLEMENTATION TWO */
/* ================== */
/* The one we use */

var VVV_ERROR_IMG='images/error.png';
var VVV_ERROR_ALT='*';
var VVV_ERROR_ID='errormsg';
var VVV_ERROR_CLASS='error'
var VVV_ERROR_MSG='Please enter or change the fields marked by ';
var VVV_ERROR_TITLE='This field must be supplied';


// returns false when the form is invalid, true when OK to continue.
function vvvCheckForm(theForm)
{
    var required=null;
	for(i=0; i<theForm.elements.length; i++)
	{
		if (theForm.elements[i].name == "required")
		{
			required=theForm.elements[i].value;
	    }
	}

	// Test if DOM is available and there is an element called required
	if(!document.getElementById || !document.createTextNode){return true;}
	if(required==null){return true;}

    var foundError = false;
    var reqfields=required.split(',');
    
    // Cleanup old mess
    // if there is an old errormessage field, delete it
    if(document.getElementById(VVV_ERROR_ID))
    {
        var em=document.getElementById(VVV_ERROR_ID);
        em.parentNode.removeChild(em);
    }
    
    // remove old images and classes from the required fields
    for(var i=0;i<reqfields.length;i++)
    {
        var f=document.getElementById(reqfields[i]);
        if(!f)
        {
//alert('field with ID of ' + reqfields[i] + ' not found on page');        
            continue;
        }
        if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
        {
            f.parentNode.removeChild(f.previousSibling);
        }
        f.className='';
    }
    // loop over required fields
    for(var i=0;i<reqfields.length;i++)
    {
        // check if required field is there
        var f=document.getElementById(reqfields[i]);
        if(!f){continue;}
        // test if the required field has an error, 
        // according to its type
        switch(f.type.toLowerCase())
        {
            case 'text':
                if(f.value=='' && f.id!='email'){vvvAddError(theForm,f); foundError=true;}
                // email is a special field and needs checking
                if(f.id=='email' && !vvvCheckEmailAddr(f.value)){vvvAddError(theForm,f); foundError=true;}
                break;
            case 'textarea':
                if(f.value==''){vvvAddError(theForm,f); foundError=true;}
                break;
            case 'checkbox':
                if(!f.checked){vvvAddError(theForm,f); foundError=true;}		
                break;
            case 'select-one':
                if(f.selectedIndex==0){vvvAddError(theForm,f); foundError=true;}
                break;
        }
    }
    // When false is returned to the form onSubmit method, the form will not be submitted.
    if (foundError) return !foundError;
    return !document.getElementById(VVV_ERROR_ID);
}



/* Tool methods */
function vvvAddError(theForm,o)
{
    // create image, add to and colourise the error fields
    var errorIndicator=document.createElement('img');
    errorIndicator.alt=VVV_ERROR_ALT;
    errorIndicator.src=VVV_ERROR_IMG;
    errorIndicator.title=VVV_ERROR_TITLE;
    o.className=VVV_ERROR_CLASS;
    o.parentNode.insertBefore(errorIndicator,o);
    
    // Check if there is no error message
    if(!document.getElementById(VVV_ERROR_ID))
    {
        // create errormessage and insert before submit button
        var em=document.createElement('div');
        em.id=VVV_ERROR_ID;
        var newp=document.createElement('p');
        newp.appendChild(document.createTextNode(VVV_ERROR_MSG))
        // clone and insert the error image
        newp.appendChild(errorIndicator.cloneNode(true));
        em.appendChild(newp);
        /* added for named list */
        var newul=document.createElement('ul');		
        em.appendChild(newul);
        /* end added for named list */
        // find the submit button 
        for(var i=0;i<theForm.getElementsByTagName('input').length;i++)
        {
            if(/submit/i.test(theForm.getElementsByTagName('input')[i].type))
            {
                var sb=theForm.getElementsByTagName('input')[i];
                break;
            }
        }
        if(sb)
        {
            sb.parentNode.insertBefore(em,sb);
        }	
    } 
    /* added for named list */
    /*
    var em=document.getElementById(VVV_ERROR_ID).getElementsByTagName('ul')[0];
    var newli=document.createElement('li');
    for(var i=0;i<theForm.getElementsByTagName('label').length;i++)
    {
        if(theForm.getElementsByTagName('label')[i].htmlFor==o.id)
        {
            var txt=theForm.getElementsByTagName('label')[i].firstChild.nodeValue;
            break;
        }
    }
    newli.appendChild(document.createTextNode(txt));
    em.appendChild(newli);
    */
    /* end added for named list */
}

function vvvCheckEmailAddr(str) 
{
    return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
}
    

    
// returns false if user has missed some fields.
function vvvStoreCheckFormNavigate(theForm,successUrl)
{ 
    vvvStoreForm(theForm);
    if (!vvvCheckForm(theForm))
    {
        return false;
    }
    window.location.href = successUrl;
    return true;
}



    
// returns false if user has missed some fields.
function vvvCheckAddToCart(theForm)
{ 
    if (!vvvCheckForm(theForm))
    {
        return false;
    }
    AddToCart(theForm);
    return false;
}



/**
 * Validate that the specified field contains an integer value and
 * display an alert dialog if it does not.
 *
 * Example usage:
 *
 * <input type="text" name="Count" onchange="return validateInteger(this, this.name);">
 *
 */
function vvvValidateInteger(field, fieldName)
{
    if (field.value == "")
    {
        return true;
        //field.value = 0;
    }

    if (vvvValidateValue(field.value, "0123456789"))
    {
	    return true;
    }
    else
    {
        alert("The " + fieldName + " field must contain an integer value, but it contains " + field.value);
        field.value = "";
	    field.focus();
	    return false;
    }
}



/**
 * Verify that the value contains only the specified characters
 */
function vvvValidateValue(value, chars)
{
    for (i = 0; i < value.length; i++)
    {
        var found = false;
        var c = value.charAt(i);
        for (j = 0; j < chars.length; j++)
        {
            if (c == chars.charAt(j))
            {
                found = true;
                break;
            }
        }
        if (!found)
        { 
            break;
        }
    }
    return found;
}



function vvvCheckMissingField(key,fieldName,silently)
{
    value = vvvGetValueForKey(key);
    if (value == null || value == '')
    {
        // field missing
        if (!silently)
        {
	   		strOutput = "REQUIRED FIELD: " + fieldName + "<br/>";
	   		document.write(strOutput);
	   		document.close();
	    }
        return false;
    }
    // field is there.
    return true;
}



function vvvCheckMissingFields(silently)
{
    continueFormSubmit = true;
    //if (!vvvCheckMissingField("product_1_code","You have no items in your shopping cart.<br/>Please select at least one product before proceeding through checkout.",silently)) continueFormSubmit = false;
    if (!vvvCheckMissingField("size_name","Measurement size chart name is missing",silently)) continueFormSubmit = true;
    if (!vvvCheckMissingField("size_weight","Measurement weight is missing",silently)) continueFormSubmit = true;
    //if (!vvvCheckMissingField("size_height","Height is missing",silently)) continueFormSubmit = false;
    return continueFormSubmit;
}


function vvvDisplayCartEmptyMessage(silently)
{
    continueFormSubmit = true;
    //if (!vvvCheckMissingField("product_1_code","<br/>You have no items in your shopping cart. Please select at least one product before proceeding through checkout.",silently)) continueFormSubmit = false;
    return continueFormSubmit;
}


function vvvPhoneNumberOnly(evt) 
{
    evt = (evt) ? evt : window.event
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode == 45 || (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) 
    {
        return false
    }
    return true
}




