﻿// This file is required by templates
// to validate forms

/* usage:
    <input type="text" validator="required" />
    <input type="text" validator="number" />
    <input type="text" validator="text" />
    <input type="text" validator="email" />
    <input type="text" validator="decimal" />
    
    <input type="checkbox" validator="required" />
    <input type="checkbox" validator="required" error="Set the checkbox!" />
    
    Optional [error] attribute can be used in any validated input.
*/

function TemplateValidator()
{
    // this function using to validate element
    this.Validate = function(element)
    {
        // if element is not visible or disabled return true
        if (!IsElementVisible(element) || element.disabled) return true;
        
        var value = element.value;
        var pattern = GetValidatorAttribute(element);

        // for check boxes
        if (element.type == "checkbox") pattern = 'cb_' + pattern;
        
        // call validation function
        var isValid = this[pattern](value, element);
        var error = this.ErrorMsg(element);
        
        // add error message to stack
        if (!isValid && error) errorMessageStack.push(error);
        
        return isValid;
    }
        
    // input type == text
        
    this.required = function(value)// cannot be empty, can be any value
    {
        return !(value.replace(/ */, '').length == 0);
    }
    
    this.number = function(value, element)  // must be number
    {
        var isValidNumber = this.required(value) && (value.replace(/[0-9]+/, '').length == 0);
        if (this.required(value) && value != '' && !isValidNumber)
            errorMessageStack.push('One or more number fields are incorrect');
        return isValidNumber;
    }
    
    this.text = function(value)    // must be text
    {
        var isValidText = this.required(value) && (value.replace(/[a-zA-Z ]*/, '').length == 0);
        if (this.required(value) && value != '' && !isValidText)
            errorMessageStack.push('One or more text fields are incorrect');
        return isValidText;
    }
    
    this.email = function(value)   // must be valid email
    {
        var isValidEmail = this.required(value) && (value.replace(/^\w+([.-]\w+)*@\w+([.-]\w+)*\.\w{2,8}$/, '').length == 0);
        if (this.required(value) && value != '' && !isValidEmail)
            errorMessageStack.push('Invalid email address');
        return isValidEmail;
    }
    
    this.decimal = function(value) // must be a number with a decimal
    {
        var isValidDecimal = this.required(value) && !isNaN(value);
        if (this.required(value) && value != '' && !isValidDecimal)
            errorMessageStack.push('One or more decimal fields are incorrect');
        return isValidDecimal;
    }
    
    this.docfile = function(value)    // must be text
    {
        var index = value.lastIndexOf(".");
        var extension = value.substring(index + 1);
        
        var isValidText = this.required(value) && ((extension == "doc") || (extension == "docx"));
        if (this.required(value) && value != '' && !isValidText)
            errorMessageStack.push('Invalid file format. Only .doc and .docx allowed.');
        return isValidText;
    }
    
    // input type == checkbox
    
    this.cb_required = function(value, element)
    {
        return element.checked;
    }
    
    this.ErrorMsg = function(element)
    {
        for (var i = 0; i < element.attributes.length; i++)
            if (element.attributes[i].nodeName == 'error') 
                return element.attributes[i].nodeValue;
                
        return false;
    }
    
    // this function using to display alert for element
    this.Alert = function(element)
    {
        if (errorDisplaying) return;
        errorDisplaying = true;
        
        var error = this.ErrorMsg(element);
        
        if (error)
        {
            alert(error); 
            errorDisplaying = false;
            return;
        }
        
        var pattern = GetValidatorAttribute(element) + 'ErrorMsg';
        
        if (element.type == "checkbox") pattern = 'cb_' + pattern;
                
        alert(this[GetValidatorAttribute(element) + 'ErrorMsg']);
        
        errorDisplaying = false;
    }

    this.cb_requiredErrorMsg = 'Checkbox should be checked';
    this.requiredErrorMsg = 'Cannot be empty, can be any value';
    this.numberErrorMsg = 'Must be number';
    this.textErrorMsg = 'Must be text';
    this.emailErrorMsg = 'Must be valid email';
    this.decimalErrorMsg = 'Must be a number with a decimal';
    this.docfileErrorMsg = 'Must be .zip file';
}


var tplValidator = new TemplateValidator();
var isFormValid = false;
var isAllChecked = true;    // flag
var isDoSubmitUsed = false;
var focusElements = Array();
var elementToFocus = null;
var defaultErrorMessage = 'One or more fields are required';
var errorMessageStack = Array();
var errorDisplaying = false;



function validateLength()
{
    if (this.value.length > 1000) {
        isFormValid = false;
        this.value = this.value.substring(0,1000);
        errorMessageStack.push('Maximum limit of 1000 characters exceeded in one or more of the fields.  Please remove additional characters to proceed.');
        DisplayError();
        return  false;
    }              
}

function doSubmit()
{
    isDoSubmitUsed = true;
        
    try { 
        ValidateForm(); 
    } 
    catch(e) {
        alert(e); return false;
    }
    
    if (!isFormValid)
    {
        DisplayError();
        return false;
    } 
    
    for (var i = 0; i < document.forms[0].elements.length; i++)
    {
        var input = document.forms[0].elements[i];


		
        if (typeof(input.value) != 'undefined')
            if (input.value.replace(/ */, '').length == 0)
                continue;

        if (input.value && input.value.length > 1000) {
            isFormValid = false;
            errorMessageStack.push('Maximum limit of 1000 characters exceeded in one or more of the fields.  Please remove additional characters to proceed.');
            DisplayError();
            return false;
        }
                		
        if (input.name == '') 
            input.name = input.id;

            //replace select values with the corresponding texts
        if (input.tagName.toLowerCase() == 'select')
        {
			for (var j = 0; j < input.options.length; j++)
			{
				 input.options[j].value = input.options[j].innerHTML;
			}
        }
    }

    document.forms[0].submit();
}

//need to comment all JS. Will be used in Talent network
//function GerReferalKeywords()
//{
//    var r=document.referrer,t="",q; 
//    var offset;
//    if(r.indexOf("google.")!=-1)t="q"; 
//    if(r.indexOf("msn.")!=-1)t="q"; 
//    if(r.indexOf("yahoo.")!=-1)t="p"; 
//    if(r.indexOf("altavista.")!=-1)t="q"; 
//    if(r.indexOf("aol.")!=-1)t="query"; 
//    if(r.indexOf("ask.")!=-1)t="q"; 
//    t="q";
//    if(t.length&&((q=r.indexOf("?"+t+"="))!=-1||(q=r.indexOf("&"+t+"="))!=-1))
//    {
//        if (q=="undefined")
//        {
//          t="p";
//          if(t.length&&((q=r.indexOf("?"+t+"="))!=-1||(q=r.indexOf("&"+t+"="))!=-1))     
//          offset = r.substring(q+2+t.length).split("+").toString().indexOf("&") +q+2+t.length;
//          return r.substring(q+2+t.length,offset).split("+").toString(); 
//        }
//        else
//        {
//            if (r.substring(q+2+t.length).split("+").toString().indexOf("&") != 1)
//            {
//                offset = r.substring(q+2+t.length).split("+").toString().indexOf("&")+q+2+t.length;
//            }
//            else
//            {
//                offset = r.substring(q+2+t.length).split("+").toString();
//            }
//            return r.substring(q+2+t.length,offset).split("+").toString(); 
//        }
//    } 
//    else
//    {
//    return "";
//    } 

//}


//function GetReferalHost() {
//    if (document.referrer == null) {
//        return null;
//    }
//    return document.referrer.match(/:\/\/(.+)\//)[1];
//}


function DisplayError()
{
    if (errorDisplaying) return;
    errorDisplaying = true;

    if (errorMessageStack.length)
    {
        alert(errorMessageStack[0]); 
        errorDisplaying = false;
        return;
    }
    
    alert(defaultErrorMessage);
    errorDisplaying = false;
}


function GetValidatorAttribute(element)
{
    for (var i = 0; i < element.attributes.length; i++)
        if (element.attributes[i].nodeName == 'validator') 
            return element.attributes[i].nodeValue;
            
    return false;
}


function ValidateForm()
{   
    errorMessageStack = Array();
    isFormValid = true;
        
    for (var i = 0; i < document.forms[0].elements.length; i++)
        if (GetValidatorAttribute(document.forms[0].elements[i]))
            isFormValid = isFormValid && tplValidator.Validate(document.forms[0].elements[i]);
 
    return isFormValid;
}





function IsElementVisible(element)
{
    while (element != null)
    {
        if (element.style)
            if (element.style.display == 'none') 
                return false;
                
        element = element.parentNode; 
    }
    return true;
}

window.onload = function()
{
//    var refText = unescape("_HOST="+GetReferalHost()+"_KEYWORDS="+GerReferalKeywords());
//    Set_Cookie('referal',refText,'','','','');
    var inputs = document.getElementsByTagName('input');
    for (var i = 0;i < document.getElementsByTagName('input').length - 1 ; i++)
    {
        if (inputs[i].id.indexOf('PF_') >= 0)
        {
            inputs[i].onkeyup =  validateLength;
        }
    }

    document.forms[0].onsubmit = function() 
    {        

        return false; 
    }
    //AttachEventsToValidatingControls();
}


