﻿// classnames ("cc-invalid") not generic

// gets value of a form element - TODO add selects to this
function cc_setValue(obj) {
    if(typeof(obj)=="string") obj = document.getElementById(obj);
    if(obj) {
        return obj.value;
    }
    return;
}
// validates form using a set of custom arrays
function cc_validateForm(e) {
    var submitForm = true; // default to true, makes it easier
    var errorForm;
    var errorMsg = new String();
    var objForm;
    if(e.nodeName == "FORM") {objForm = e};

    // remove invalid chars
   if(typeof(formElValidChars)=="object") {
        for(var i in formElValidChars) {
            var reg = formElValidChars[i];
            var obj = document.getElementById(i);
            if(obj) {
                var val = obj.value;
                // allow only the characters listed - filter the others
                var GREP = new RegExp("[^"+reg+"]","g");
                obj.value = val.replace(GREP,"");
            }
        }
    }
    // test min/max lengths
    if(typeof(formElLengths)=="object") {
        for(var i in formElLengths) {
            var min = formElLengths[i][0];
            var max = formElLengths[i][1];
            var obj = document.getElementById(i);
            if(obj) {
                var len = obj.value.length;
                // ensure length is between the two values, inclusive
                var v = (len >= min && len <= max);
                if(!v) {
                    submitForm = false;
                    errorForm = obj.form;
                }
                // toggle class name to add or remove invalid flag
                if(e) cc_addRemoveClassName(obj,"cc-invalid",!v);
            }
        }
    }
    // test valid string formats
    // Remember to use double escapes in GREP string - eg \\w
    if(typeof(formElGREP)=="object") {
        if(formElGREP["form-class"] && objForm && objForm.className) {
            
            if(objForm.className.match(formElGREP["form-class"]))
            {
               
                // loop through GREP array
                for(var i in formElGREP) {
                    var obj = document.getElementById(i);
                    if(obj) {
                        var objValue = obj.value;
                        var GREP = new RegExp();
                        var g = formElGREP[i];
                        // if passed a string, simple validation
                        if(typeof(g)=="string") {
                            // create regexp from supplied string
                            GREP.compile(formElGREP[i]);
                            // test for match
                            var v = GREP.exec(obj.value);
                            if(!v) {
                                submitForm = false;
                                errorForm = obj.form;
                            }
                            // toggle class name to add or remove invalid flag - only if this is a click event, or if the input has a value
                            if(e || obj.value) cc_addRemoveClassName(obj,"cc-invalid",!v);
                        }
                        // this bit needs tidying up, but it was a bit of a pain to get it working, so I've left it
                        // we can be passed an array of grep matches, with a flag of and / or
                        // eg ["and","^[0]{1}[12]{1}","^[0-9]{10,11}$"], ["or","^[0]{1}[12]{1}","^[0-9]{10,11}$"]
                        else if(typeof(g.splice)=="function") {
                            // first entry should be and / or
                            var logOp = g[0];
                            // and validates every entry, or just needs one
                            var valG = (logOp == "and"); // with and we default to true, since one failure can break it
                                                         // with or we default to false, since one success can make it

                            // loop through each grep string
                            grepLoop:
                            for(var j = 1; j < g.length; j++) {
                                // create regexp from supplied string
                                GREP.compile(g[j]);
                                // test for match
                                var v = GREP.exec(obj.value);
                                // if we have no match
                                if(!v) {
                                    // if this is an "and" test, look no further
                                    if(logOp == "and") {
                                        // input is invalid, don't submit form
                                        valG = false;
                                        // end loop
                                        break grepLoop;
                                    }
                                }
                                else { // if we have a value
                                    if(logOp == "or") { // if this is an or test
                                        valG = true; // flag as successful
                                    }
                                }
                            } // end grep loop

                            // only change our submitForm flag if validation has failed
                            // otherwise we might reset invalid values to be valid
                            if(!valG) {
                                submitForm = valG;
                                errorForm = obj.form;
                            }

                            // toggle class name to add or remove invalid flag - only if this is a click event, or if the input has a value
                            if(e || obj.value) cc_addRemoveClassName(obj,"cc-invalid",!valG);
                        } // array
                    }
                }
            }
        }
    }
    // compare two values
    if(typeof(formElCompare)=="object") {
        for(var i in formElCompare) {
            var obj = document.getElementById(i);
            if(obj) {
                var compObj = document.getElementById(formElCompare[i][0]);
                if(compObj) {
                    var op = formElCompare[i][1];
                    if(obj.value && compObj.value) {
                        try {
                            var v = eval(obj.value + op + compObj.value);
                            if(!v) {
                                submitForm = false;
                                errorForm = obj.form;
                            }
                            if(e) cc_addRemoveClassName(obj,"cc-invalid",!v);
                        }
                        catch(e) { submitForm = false; } // eval returns an error
                    }
                }
            }
        }
    }
    
    if(!submitForm) {
        if(e && e.preventDefault) e.preventDefault(); // Mozilla event cancelling
        cc_displayValidationError(errorForm);
    }
    else 
    {
        //JA hack to add bundling JS if the form contains bundle Info
        var bundleOptions = document.getElementById("bundleSearchOptions")
        if (bundleOptions) {submitForm = validateBundleSearch(objForm)}
        cc_addRemoveClassName("cc-error","cc-no-display",true);
    }
    // IE event cancelling
    return submitForm;
}
function cc_displayValidationError(objForm,str) {
    var obj = document.getElementById("cc-error");
    if(!obj) {
        obj = document.createElement("div");
        obj.setAttribute("id","cc-error");
        obj.setAttribute("class","cc-error");
        obj.setAttribute("className","cc-error");
        if(objForm && objForm.appendChild) objForm.appendChild(obj);
        else document.getElementsByTagName("body")[0].appendChild(obj);
    }
    while(obj.childNodes[0]) {
        obj.removeChild(obj.childNodes[0]);
    }
    var txt = document.createTextNode("This information cannot be submitted.  Please check your entries and try again");
    obj.appendChild(txt);
}
// enable of disable a form field
function cc_toggleField(obj,blnEnabled) {
    if(typeof(obj)=="string") obj = document.getElementById(obj);
    if(blnEnabled) {
      obj.removeAttribute("disabled");
    } else {
      obj.setAttribute("disabled", "disabled");
    }
}
// enable or disable all form fields
function cc_toggleFields(frmID,blnEnabled) {
    var els = document.getElementById(frmID).elements;
    for (var i=0; i<els.length; i++) {
        if(blnEnabled) {
            els[i].removeAttribute("disabled");
        } else {
            els[i].setAttribute("disabled", "disabled");
        }
    }
}

function validateBundleSearch(frmElement)
{ 
    var bErr = false;
    var calcType10 = document.getElementById("calcID10")
    var isHomephone = document.getElementById("isHomephone")
    var isDTV = document.getElementById("isDTV")
    if (calcType10)
    {
        if (calcType10.checked)
        {   
            if (!isHomephone.checked && !isDTV.checked)
            {
                alert("Please select homephone or Digital TV or both");
                bErr = true;
            }
        }
    }
    if (bErr == false) {return true;}else {return false;}
}


function validPostcode(frmElement){
/*
There are 6 possible valid UK postcodes: where L = letter and N = Number
LN NLL LLN NLL LNN NLL LNL NLL LLNN NLL LLNL NLL
*/
var pcode = frmElement.value;
var pcType1 = /^[A-Z]{1}\d{1}\s{1}\d{1}[A-Z]{2}/;
var pcType2 = /^[A-Z]{2}\d{1}\s{1}\d{1}[A-Z]{2}/;
var pcType3 = /^[A-Z]{1}\d{2}\s{1}\d{1}[A-Z]{2}/;
var pcType4 = /^[A-Z]{2}\d{2}\s{1}\d{1}[A-Z]{2}/;
var pcType5 = /^[A-Z]{2}\d{1}[A-Z]{1}\s{1}\d{1}[A-Z]{2}/;
var pcType6 = /^[A-Z]{1}\d{1}[A-Z]{1}\s{1}\d{1}[A-Z]{2}/;
var sAlertEmpty = "Please enter a valid UK post code.";
var sAlertLength = "Sorry, but the postcode you entered was too long or too short. " + sAlertEmpty;
var sAlertInvalid = "Sorry, the postcode [" + frmElement.value + "] is not valid. " + sAlertEmpty;
	if (pcode==null||pcode==""){alert(sAlertEmpty);return false}
	pcode = formatPostcode(pcode);
	if (pcode.length<6||pcode.length>8){alert(sAlertLength);return false}	
	if (pcode.match(pcType1)||pcode.match(pcType2)||pcode.match(pcType3)||pcode.match(pcType4)||pcode.match(pcType5)||pcode.match(pcType6)){
		frmElement.value = pcode; return true
	}
	else {alert(sAlertInvalid);return false}
}

function validPostcodeST(frmElement){

/*
There are 6 possible valid UK postcodes: where L = letter and N = Number
LN NLL LLN NLL LNN NLL LNL NLL LLNN NLL LLNL NLL
*/
var pcode = frmElement.value;

var pcType1 = "^[a-zA-Z]{1}\\d{1}\\s?\\d{1}[a-zA-Z]{2}$";
var pcType2 = "^[a-zA-Z]{2}\\d{1}\\s?\\d{1}[a-zA-Z]{2}$";
var pcType3 = "^[a-zA-Z]{1}\\d{2}\\s?\\d{1}[a-zA-Z]{2}$";
var pcType4 = "^[a-zA-Z]{2}\\d{2}\\s?\\d{1}[a-zA-Z]{2}$";
var pcType5 = "^[a-zA-Z]{2}\\d{1}[a-zA-Z]{1}\\s?\\d{1}[a-zA-Z]{2}$";
var pcType6 = "^[a-zA-Z]{1}\\d{1}[a-zA-Z]{1}\\s?\\d{1}[a-zA-Z]{2}$";
	if (pcode==null||pcode==""){;return false;}
	if (pcode.length<6||pcode.length>8){;return false;}	
	if (pcode.match(pcType1)||pcode.match(pcType2)||pcode.match(pcType3)||pcode.match(pcType4)||pcode.match(pcType5)||pcode.match(pcType6)){
		frmElement.value = pcode; return true;
	}
	else {return false;}
}

