﻿// 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 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.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;
			}
        }
    }
//    var newInput=document.createElement('input');
//    newInput.name='Referals';
//    newInput.value = unescape(Get_Cookie('referal'));
//    Delete_Cookie('referal');
//    document.forms[0].appendChild(newInput);
    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 AttachEventsToValidatingControls()
//{
//    for (var i = 0; i < document.forms[0].elements.length; i++)
//    {
//        var el = document.forms[0].elements[i];
//        var val = GetValidatorAttribute(el);
//        
//        if (val)
//        {
//            el.onfocus = OnValidatorFocus;
//            el.onblur = OnValidatorBlur;
//        }
//    }    
//}


//function OnValidatorFocus(event)
//{
//    var el = (typeof(event) != 'undefined') ? event.target : window.event.srcElement;
//    
//    // all previous fields valid we can validate next field
//    if (isAllChecked) 
//    {
//        focusElements.push(el);
//        isAllChecked = false;
//    }
//}


//function OnValidatorBlur(event)
//{
//    var e = (typeof(event) != 'undefined') ? event.target : window.event.srcElement;
//    var el;
//    
//    while(el = focusElements.pop())
//    {
//        // if element is not valid - remove all elements in array and focus on it
//        if (!tplValidator.Validate(el))
//        {
//            focusElements.push(el); // push it again, until it will be valid
//            elementToFocus = el;
//            
//            if (e == elementToFocus) 
//                tplValidator.Alert(el); // displaing error to user
//                
//            setTimeout(function(){ elementToFocus.focus(); }, 5);
//            return;
//        }
//    }
//    
//    // all elements are valid
//    isAllChecked = true;
//}

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,'','','','');
    document.forms[0].onsubmit = function() 
    {        
    //Gerring referals, setting cookies.
//        if (!isDoSubmitUsed)
//        {
//            try { 
//                ValidateForm(); 
//            } 
//            catch(e) {
//                alert(e); return false;
//            }
//            
//            if (!isFormValid) DisplayError();
//        }
      //  Delete_Cookie('referal');
        return false; 
    }
    //AttachEventsToValidatingControls();
}


//function Get_Cookie( check_name ) {
//	// first we'll split this cookie up into name/value pairs
//	// note: document.cookie only returns name=value, not the other components
//	var a_all_cookies = document.cookie.split( ';' );
//	var a_temp_cookie = '';
//	var cookie_name = '';
//	var cookie_value = '';
//	var b_cookie_found = false; // set boolean t/f default f
//	
//	for ( i = 0; i < a_all_cookies.length; i++ )
//	{
//		// now we'll split apart each name=value pair
//		a_temp_cookie = a_all_cookies[i].split( '=' );
//		
//		
//		// and trim left/right whitespace while we're at it
//		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
//	
//		// if the extracted name matches passed check_name
//		if ( cookie_name == check_name )
//		{
//			b_cookie_found = true;
//			// we need to handle case where cookie has no value but exists (no = sign, that is):
//			if ( a_temp_cookie.length > 1 )
//			{
//				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
//			}
//			// note that in cases where cookie is initialized but no value, null is returned
//			return cookie_value;
//			break;
//		}
//		a_temp_cookie = null;
//		cookie_name = '';
//	}
//	if ( !b_cookie_found ) 
//	{
//		return null;
//	}
//}

//function Set_Cookie( name, value, expires, path, domain, secure ) {
//	// set time, it's in milliseconds
//	var today = new Date();
//	today.setTime( today.getTime() );
//	// if the expires variable is set, make the correct expires time, the
//	// current script below will set it for x number of days, to make it
//	// for hours, delete * 24, for minutes, delete * 60 * 24
//	if ( expires )
//	{
//		expires = expires * 1000 * 60 * 60 * 24;
//	}
//	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
//	var expires_date = new Date( today.getTime() + (expires) );
//	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

//	document.cookie = name + "=" +escape( value ) +
//		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
//		( ( path ) ? ";path=" + path : "" ) + 
//		( ( domain ) ? ";domain=" + domain : "" ) +
//		( ( secure ) ? ";secure" : "" );
//}

//// this deletes the cookie when called
//function Delete_Cookie( name, path, domain ) {
//	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
//			( ( path ) ? ";path=" + path : "") +
//			( ( domain ) ? ";domain=" + domain : "" ) +
//			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
//}
