/**
 * @author eli geske
 * Validation for all forms in the secured side agency center.
 * Returns a prepended error box with <li> of errors.
 */
$(document).ready(function(){	

    $('#agency-form').submit(function(){  
		if($('#NoActive').length > 0){
			return true;
		}  
		$('#form_error_div').remove();
		
        
		$msg = validateForm("#agency-form");
		
		if($msg.length > 0){
				
				$errorBox = '<div class="form_intro" id="form_error_div" style=" margin: 10px 0 10px 0; border: 5px solid #ce9090;  font-size: 12px; color: #ce9090";"><div style="padding: 10px;">';
				$errorBox += $msg;
				$errorBox += '</div></div>';
				
				$('#agency-form').prepend($errorBox);

			return false;
		} 
    });    
});


function validateForm($formId)
{
	$($formId + ' :input').removeClass("redError");
	if($form = createInputsArray('#agency-form', $byName = false)){
		$msg = "";
		
		for($val in $form){	
			//alert($form[$val]['title']);
			$msg += doValidationFromAlt($form[$val]['alt'],$form[$val]['name'], $form[$val]['value'], $form[$val]['type'], $form[$val]['title']);
		}	
	}
	
	return $msg;
}

/**
 *
 * @param {Object} $field_alt  (yes, no)
 * @param {Object} $field_name (input name)
 * @param {Object} $field_value (input value)
 */
function doValidationFromAlt($field_alt, $field_name, $field_value, $field_type, $field_title){
	
	if($field_alt == undefined){ $field_alt = ""; }
    // if alt tag has value
	$valMsg = "";
    if ($field_alt.length > 0) {
        $field_alt = $field_alt.replace(" ", "");

		$array = $field_alt.split(",");
        
//		for($val in $array){
//			$('#agency-form').append($val + " : " + $array[$val] + "<br/>");
//		}
		$i = 0;	
		for ($attr in $array) { // assign attributes to values if defined
			
			// REQUIRED            
			if ($array[$attr] == "required") {						
				// validate checkbox required
				if($field_type == "checkbox"){
					if(!$("input[name='" + $field_name + "']").is(":checked")){
						$valMsg += inputRequired("", $field_name, $field_title)+"<br/>";						
						$i++;
						//$("input[name = '" + $field_name + "' ]").addClass("redError");
					}
				}else{
				// validate others				
	                if (inputRequired($field_value, $field_name)) {
	                    $valMsg += inputRequired($field_value, $field_name, $field_title)+"<br/>";
						$i++;
						//$("input[name = '" + $field_name + "' ]").addClass("redError");
	                }	
				}				
            }
            // NAME
            if ($array[$attr] == "name") {
                if (inputName($field_value, $field_name)) {
					if($i == 0){
						$valMsg += inputName($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}                    
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
            // NUMBER
            if ($array[$attr] == "number") {
				if (inputNumber($field_value, $field_name)) {
					if($i == 0){
						$valMsg += inputNumber($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}                    
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
            // PHONE
            if ($array[$attr] == "phone") {				
                if (!inputPhone($field_value, $field_name)) {
                    //$("input[name = '" + $field_name + "' ]").val(phoneFormat($field_value));
                }
                else{
					if($i == 0){
						$valMsg += inputPhone($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}                	
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
            // EMAIL
            if ($array[$attr] == "email") {
                if (inputEmail($field_value, $field_name)) {
					if($i == 0){
						$valMsg += inputEmail($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}
                    
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
            // THOUSANDS
            if ($array[$attr] == "thousands") {
                if (inputThousands($field_value, $field_name)) {
					if($i == 0){
						$valMsg += inputThousands($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}                    
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
			
			//FEDERAL ID
			
            if ($array[$attr] == "fedid") {
                if (inputFedId($field_value, $field_name)) {
					if($i == 0){
						$valMsg += inputFedId($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
			
			if ($array[$attr] == "year") {
                if (inputYear($field_value, $field_name)) {
					if($i < 1){
						$valMsg += inputYear($field_value, $field_name, $field_title)+"<br/>";
						$i++;
					}
					//$("input[name = '" + $field_name + "' ]").addClass("redError");
                }
            }
            
        }
    }
    
    return $valMsg;
    
}

function inputRequired($value, $name, $title){
    if ($value.length > 0) {
        return false;
    }
    else {
        //return "The " + $name + " field is required.";
		return $title + " is required.";
    }
}

function inputYear($value, $name, $title) { 

	if (!isValidYear($value))
	{
		return $title + " is not a valid year.";
	}

}

function inputName($value, $name, $title){
    //if (!isAlphaNum($value)) {
    //    return "Please enter a valid " + $name + ".";
    //}
    if (isNotSpecialChar($value)) {
        //return "Please enter a valid " + $name + ".";
		return $title + " is not valid.";
    }
}

function inputNumber($value, $name, $title){
    if (isNaN($value)) {
        //return "Please enter a valid " + $name + ", numeric only.";
		return $title + " must be numeric only.";
    }
}

function inputFedId($value, $name, $title) {
	if (!isFedId($value)) {
		return $title + "  must contain nine numbers without spaces or dashes.";
	}
}

function inputPhone($value, $name, $title){
    if (!isPhone($value)) {
        //return "Please enter a valid " + $name + ".";
		return $title + " is not valid.";
    }
}

function inputThousands($value, $name, $title){
    if (!isNumberComma($value)) {
        //return "Please enter a valid " + $name + ".";
		return $title + " needs be a whole dollar amount or a comma separated amount ex.(1,000 or 1,054,970)";
    }
}

function inputEmail($value, $name, $title){
    if (!isEmail($value)) {
        //return "Please enter a valid " + $name + ".";
		return $title + " does not contain a valid email address.";
    }
}

/**
 * Input the form ID and it will grab all form input and assign it to a multi dimensional array.
 * If $byName is true "$form[name][elements]" else "$form[0++][elements] <-- name will be in the elements".
 * $attributes will always assign "value" and "name"
 * @param {string} $formId
 * @param   {bool} $byName
 * @param  {array} $attributes !!!!optional, if not set, all defined html attributes will be set.
 * @return $form array()  "$form[0]['element-name'] || $form['name']['elements']"
 */
function createInputsArray($formId, $byName, $attributes){
    if ($attributes === undefined) {// default attributes			
        $attributes = ['alt', 'title', 'checked', 'disabled', 'maxlength', 'readonly', 'size', 'type', 'src', 'id', 'lang', 'class', 'dir', 'accesskey', 'accept']
    }
    else {// user attributes
        if (typeof($attributes) == "string") {
            $attributes = [$attributes];
        }
    }
    
    
    // get from object
    $inputsObject = $($formId + ' :input');
    
	$form = new Array();
    
    // object/array iterator
    $n = 0;
    $inputsObject.each(function(){
        if ($byName) {
            $n = $(this).attr('name');
        }
        $form[$n] = new Array();
        $form[$n]['value'] = $(this).val(); // value of element		
        for ($attr in $attributes) { // assign attributes to values if defined
            if ($(this).attr($attributes[$attr] != undefined)) {
                $form[$n][$attributes[$attr]] = $(this).attr($attributes[$attr]);
            }
        }
        if ($byName == false) { //iterate the number and assign element name if $byName == false
            $form[$n]['name'] = $(this).attr('name');
            $n++;
        }
    });
    return $form;
}






/**
 * VALIDATE ALPHA/NUMERIC/SPACE - input a string and validates whether or not it contains only ALPHA/NUMERIC, NO Special Characters
 * @param {Object} $string
 */
function isAlphaNum($string){
    if ($string.search(/[^a-zA-Z0-9 \. ]/g) == -1) {
        return true;
    }
}

function isNotSpecialChar($string){
    if ($string.search(/[\<\>%]/g) == -1) {
        return false;
    }
    else
    	return true;
}

/**
 * VALIDATE EMAIL - simple regex check for email layout for @, dot and returns true if passes
 * @param {Object} $email
 */
function isEmail($email){
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (reg.test($email) == false) {
        return false;
    }
    else {
        return true;
    }
}

/**
 * VALIDATE THOUSANDS COMMA SEPARATOR - Limit to 999,999,999 length.  Pass $number returns true if it fits
 * the thousands comma separator pattern. If you have a regex for this, let me know. ejgeske@yahoo.com
 * @param {Object} $number
 */
function isNumberComma($number){
    $success = true;
    $count = $number.length;
    $clean = $number.replace(/,/g, '');
    $array = $number.split(',');
    
    // check last array for contents (weird, javascript will count the last array if empty, but says its undefined.)
    if ($array.length - 1 != 0) {
        if ($array[$array.length - 1].length != 3) {
            $success = false;
        };
            };
    
    // if more than three arrays. false 999,999,999 limit remember.
    if ($array.length > 3) {
        $success = false;
    }
    // check $clean if numeric only
    if (validateNumeric($clean) == false || $count > 11) {
        $success = false;
    }
    else {
        // Check first array
        if ($array[0]) {
            if ($array[0].length < 1 || $array[0].length > 3) {
                $success = false;
            }
            // Check first number in array to ensure it is 1 or higher,  but allows just 0
            else {
                if ($array[0].slice(0, 1) == 0) {
                    $success = false;
                }
            }
        }
        else {
            $success = false;
        }
        // Check second array
        if ($array[1]) {
            if ($array[1].length != 3) {
                $success = false;
            }
        }
        //checks next array
        if ($array[2]) {
            if ($array[2].length != 3) {
                $success = false;
            }
        }
    }
	if($number === "0"){ $success = true; }
    return $success;
}

/**
 * VALIDATE PHONE # - simple regex check for phone
 * @param {Object} $phone
 */
function isPhone($phone){
    $phone = js_preg_replace(/\D/g, '', $phone);
	if($phone.length == 10){
		return true
	}
}

function phoneFormat($phone){
    $phone = js_preg_replace(/\D/g, '', $phone);
    if ($phone.length == 10) {
        $phone1 = $phone.slice(0, 3);
        $phone2 = $phone.slice(3, 6);
        $phone3 = $phone.slice(6, 10);
        $phone = $phone1 +"-"+$phone2+"-"+$phone3;
    }
    return $phone;
}

function js_preg_replace($pattern, $replace, $value){
    $result = $value.replace($pattern, $replace);
    return $result
    
}

function isFedId($string) {
	if (!validateNumeric($string)) return false;
	if ($string.length != 9) return false;
	if ($string > 999999999) return false;
	if ($string < 0) return false;
	
	return true;
}

function isValidYear($year) {
	if (!validateNumeric($year)) return false;
	
	var d = new Date();
	var curr_year = d.getFullYear();
	
	
	if ($year < 1800) return false;
	if ($year > curr_year) return false;
	
	return true;
}



