var oForm               = null;
var hasSteps            = false;
var wizard_last_step    = false;
var hasTabSteps         = false;


function focusField(field_name, has_steps, oForm){
    if (field_name) {
        if( document.getElementsByName(field_name) ){
            field = (!oForm) ? document.getElementsByName(field_name) : oForm[field_name];

            if(typeof(field) == 'object' && (typeof(field.tagName) != 'undefined') ) {
                // If its a step table
                if (has_steps == true) {
                    hasSteps = true;
                    hideStepTables();

                    var focus_tbl = getStepTable(field);
                    if (focus_tbl) {
                        focus_tbl.style.display = '';
                    }
                }

                if (!field.disabled && isVisible(field) && (typeof(field.tagName) != 'undefined')) {

                    field.focus();
                }
            }
		}
    }
}


function makePhoneNumber(e, field_name) {
  	if(!e.srcElement) {
		obj = e.currentTarget;
	} else {
		obj = e.srcElement;
	}

    form = obj.form;

    eval('phone_field = form.' + field_name);
    eval('area_code = form.' + field_name + '_area');
    eval('ph_number = form.' + field_name + '_no');
    phone_field.value = area_code.value + ' ' + ph_number.value;
}



//
// Form Validation Functions
//

var err                     = "Please make sure you have filled the form in correctly:\n\n";
var to_focus                = null;
var sf_website_filter       = new RegExp('^(http:\/\/|https:\/\/|ftp:\/\/)+([a-z0-9\.\/\-])+$', 'i');
var sf_alpha_filter			= new RegExp('^\w.+$', 'i');
var sf_alphanumeric_filter 	= new RegExp('^[0-9a-z\s]+$', 'i');
var sf_numeric_filter		= new RegExp('^[0-9\-\s]+$', 'i');
var sf_unlimited_numeric_filter = new RegExp('^([0-9\-\s]+)|(Unlimited)$', 'i');
var sf_float_filter		    = new RegExp('^[0-9\s\.\-]+$', 'i');
var sf_date_filter			= new RegExp('^$', 'i');
var sf_user_filter			= new RegExp('^[_0-9a-z]+$', 'i');

var sf_phone_filter         = new RegExp('^[0-9 +-.]{7,30}$', 'i');
var sf_password_filter      = new RegExp('^\w.+$', 'i');

var sf_prevent_multiple_checks = {};
var sf_checked_radios = {};

function checkField(fld_obj) {

	fld_name = fld_obj.getAttribute('sf_title');

	field_error = '';

	if (fld_obj.tagName != "SELECT") {
	    fld_val		= fld_obj.value.trim();
	} else {
	    fld_val		= fld_obj[fld_obj.selectedIndex].value.trim();
	}


	fld_val_len = fld_val.length;
	mandatory	= fld_obj.getAttribute('mandatory');
	validate	= (fld_obj.getAttribute('validation') ? fld_obj.getAttribute('validation') : false);

    var mandatory_failed = false;

    if (mandatory && fld_obj.type == 'radio' && !fld_obj.checked && !sf_checked_radios[fld_name]) {
        sf_checked_radios[fld_name] = true;
        mandatory_failed = true;
        var radios = document.getElementsByTagName('input');
        for (var i = 0; i < radios.length; i ++) {
            if ((radios[i].type == 'radio') && (radios[i].getAttribute("sf_title") == fld_name) && radios[i].checked) {
                mandatory_failed = false;
                break;
            }
        }
    }

	if ((mandatory && ! fld_val_len) || mandatory_failed) {
		field_error += " - '" + fld_name + "' is a Mandatory field\n";

		// Phone Number - Cant focus hidden field
		if (validate == "11") {
		    ph_fld = eval('oForm.' + fld_obj.name + '_no');
		    to_focus = (to_focus==null) ? ph_fld : to_focus;
		} else {
			to_focus = (to_focus==null) ? fld_obj : to_focus;
		}
	}



	if ((validate != false) && fld_val.length) {

		switch( validate ){

			case "email":
			case "SF_EMAIL":
			case "1":
			    if(!validateEmail(fld_val)) {
					field_error += " - '" + fld_val + "' is not a valid Email Address\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
			    }
			    break;

			case "website":
			case "SF_WEBSITE":
			case "2":
                if(fld_val == 'http://') {
                    fld_obj.value = '';
                    fld_val        = '';
                } else {
                    if( ! sf_website_filter.test(fld_val)){

                        if(sf_website_filter.test('http://' + fld_val)){
                            fld_obj.value = 'http://' + fld_obj.value;
                        } else {
                            field_error += " - '" + fld_val + "' is not a valid Website Address\n";
                            to_focus = (to_focus==null)?fld_obj:to_focus;
                        }
                    }
                }
				break;

			case "alpha":
			case 3:
				if( ! sf_alpha_filter.test(fld_val) ){
					field_error += " - '" + fld_val + "'  must only contain Alphabetic characters\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
				}
				break;

			case "SF_ALPHANUMERIC":
			case "4":
				if( ! sf_alphanumeric_filter.test(fld_val) ){
					field_error += " - '" + fld_val + "'  must only contain Alphanumeric characters\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
				}
				break;

			case "SF_NUMERIC":
			case "5":
				if( ! sf_numeric_filter.test(fld_val) ){
					field_error += " - '" + fld_val + "' must be a number\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
				}
				break;
			case "SF_UNLIMITED_NUMERIC":
			case "18":
				if( ! sf_unlimited_numeric_filter.test(fld_val) ){
					field_error += " - '" + fld_val + "' must be a number\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
				}
				break;
            case "8":
                emails = fld_val.split(',');
                error  = false;

                for(a=0; a<emails.length; a++ ) {
			        if(!validateEmail(emails[a])) {
			            error = true;
			        }
			    }

				if (error == true) {
				    field_error += " - One of the Emails in the " + fld_name + " field is not Valid\n";
				    to_focus = (to_focus==null)?fld_obj:to_focus;
				}
                break;

            // Sf Phone validation
            case "SF_PHONE_NUMBER":
		    case "11":

		        if (!sf_phone_filter.test(fld_val)) {
		            field_error += " - '" + fld_val + "' is not a valid Phone Number\n";
                    //Only works for phone fields.
                    //{
		             //ph_fld = eval('oForm.' + fld_obj.name + '_no');
					 //to_focus = (to_focus==null) ? ph_fld:to_focus;
                     to_focus = (to_focus==null)?fld_obj:to_focus;
                    // }
				}
		        break;

            // Sf Float validation
            case "12":
                if( ! sf_float_filter.test(fld_val) ){
					field_error += " - '" + fld_val + "' must be a number\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
				}
                break;

			//Credit Card validation
			case "13":
                var cc_num = document.getElementById(fld_obj.id + '_fld[number_1]').value +
                             document.getElementById(fld_obj.id + '_fld[number_2]').value +
                             document.getElementById(fld_obj.id + '_fld[number_3]').value +
                             document.getElementById(fld_obj.id + '_fld[number_4]').value;
                var cc_type = document.getElementsByName(fld_obj.id + '_fld[cc_type]');
                var cc_type_value = 0;
                var cc_type_obj;
                for(var i=0;i<cc_type.length;i++) {
                    if(cc_type[i].checked) {
                        cc_type_obj   = cc_type[i];
                        cc_type_value = cc_type_obj.value;
                    }
                }


                // check 'Name on Card' field
                var cc_name = document.getElementById(fld_obj.id + '_fld[name]');
                if(cc_name.value.length == 0) {
                    error        = true;
                    field_error += " - Please enter the Name on the Card\n";
                    to_focus     = (to_focus==null)?cc_name:to_focus;
                }

                // check credit card type radio buttons
                if(cc_type_value == 0) {
                    error        = true;
                    field_error += " - Please select a Credit Card type\n";
                    to_focus     = (to_focus == null) ? cc_type_obj : to_focus;
                }

                // check valid credit card number
				if(!creditCardIsValid(cc_num, cc_type)) {
                    error        = true;
					field_error += " - Please enter a valid Credit Card number\n";
					to_focus = (to_focus == null)?document.getElementById(fld_obj.id + '_fld[number_1]'):to_focus;
				} else if(getCreditCardType(cc_num) != cc_type_value) {
                    error        = true;
                    field_error += " - The Credit Card number does not match the selected Credit Card type\n";
                    to_focus     = (to_focus == null) ? cc_type_obj : to_focus;
                }

                var exp_month = document.getElementById(fld_obj.id + '_fld[exp_month]');
                var exp_year  = document.getElementById(fld_obj.id + '_fld[exp_year]');
                var ccv       = document.getElementById(fld_obj.id + '_fld[ccv]');

                if(exp_month.value.charAt(0) == '0') {
                    exp_month.value = exp_month.value.substr(1,1);
                }
                if(exp_year.value.charAt(0) == '0') {
                    exp_year.value = exp_year.value.substr(1,1);
                }

                if(isNaN(parseInt(exp_month.value)) || parseInt(exp_month.value) < 1 || parseInt(exp_month.value) > 12) {
                    error        = true;
                    field_error += " - Please enter a valid Credit Card expiration month\n";
                    to_focus     = (to_focus == null) ? exp_month : to_focus;
                }

                if(isNaN(parseInt(exp_year.value)) || parseInt(exp_year.value) < 5 || parseInt(exp_year.value) > 50) {
                    error        = true;
                    field_error += " - Please enter a valid Credit Card expiration year\n";
                    to_focus     = (to_focus == null) ? exp_year : to_focus;
                }

                if(ccv && isNaN(parseInt(ccv.value))) {
                    error        = true;
                    field_error += " - Please enter a valid Credit Card CCV number\n";
                    to_focus     = (to_focus == null) ? ccv : to_focus;
                }

                break;

            /*case "SF_STRONGPASS":
            case "14":
                if( ! sf_password_filter.test(fld_val) ){
					field_error += " - '" + fld_name + "' must be over 8 characters and contain a number\n";
					to_focus = (to_focus==null)?fld_obj:to_focus;
				}
                break;
                */
	    }
	}


	return new qfErrorObj(field_error, to_focus);

}


function checkForm(form_obj){
    //updateCheckboxes();
    oForm    = form_obj;
    to_focus = null;
    sf_checked_radios = {};

    if(typeof(oForm) == 'undefined') {
        oForm = document.forms[0];
    }

    err = "Please make sure you have filled the form in correctly:\n\n";

    //var sf_website_filter 		= new RegExp('^[(http:\/\/|https:\/\/|ftp:\/\/)]+((?:\w+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)([a-z0-9A-Z\.-\/])*$', 'i');
	var olen = err.length;

	for(i=0; i<oForm.length; i++){

		if( oForm[i].getAttribute('sf_title') == null ) {
			continue;
		}

		// Pass off to checkField
		err     += checkField(oForm[i]).err;
		to_focus = checkField(oForm[i]).to_focus;

	}

	if(err.length > olen) {

	    if (hasSteps) {
    	    //Firstly hide all the step tables
    	    hideStepTables();

    	    // Focus to the First field with the Error
    	    var focus_tbl = getStepTable(to_focus);
        	    focus_tbl.style.display = '';
    	}

        if (to_focus) {
            if (hasTabSteps) {
        	    focusTabField(to_focus.name, hasSteps, oForm);
            } else {
                focusField(to_focus.name, hasSteps, oForm);
            }
        }

		alert(err);
		return false;
	}

	if (typeof(oForm.submitted) != 'undefined') {
        oForm.submitted.disabled = true;
    }

    if (wizard_last_step) {
        setCookie('wizard_step', wizard.next_step_id, null, '/');

    }

	return true;
}



function qfErrorObj(err,to_focus) {
    this.err        = err;
    this.to_focus   = to_focus;
}


function isVisible(element) {
    vis = true;

    if((typeof(element) == 'object') && (typeof(element.style) == 'object')) {

        if(element.style.display=='none') {
            vis = false;
        }

        if(element.type && element.type.toLowerCase() == 'hidden') {
            vis = false;
        } else if(element.type && element.type.toLowerCase() == 'radio') {
            vis = false;
        }

        if (vis) {
            el = element.parentElement;
            while(el != null){
                if (el.style.display == 'none') {
                    vis = false;
                }
                el = el.parentElement;
            }
        }
    }

    return vis;
}

function updateTextCheckField(checkbox, textfield) {
    if(checkbox.checked) {
        textfield.value = "";
        textfield.focus();
    } else {
        textfield.value = "Unlimited";
        checkbox.focus();
    }
}


// NOTE:
// This has been copied from the common file, needs to be duplicated for trial signup form and users em forms
String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};
