﻿function Validation() { }
//----------------------------------------------------------------------------------
Validation.IsSubmit = false;
//----------------------------------------------------------------------------------
Validation.validate = function(source, args)
{
    if(source.exectrim == '1')
        args.Value = Validation._trim(args.Value);
    Validation._updateErrorMessage(source, args);
    Validation._validate(source, args);
    Validation._runCustomFunction(source, args);
    
    Validation._updateLabel(source, args);
    if(!args.IsValid && Validation.IsSubmit)
        Validation._displaySubmitErrorMessage(source);
    
    return args.IsValid;
}
//------------------------------------
Validation.compare = function(source)
{
    function ArgsEmul(bIsValid)
    {
        this.IsValid = bIsValid; 
    }
    
    var bIsValid = CompareValidatorEvaluateIsValid(source);
    var args = new ArgsEmul(bIsValid);
    Validation._updateLabel(source, args);    
    return args.IsValid;
}
//------------------------------------
Validation.validateCheckboxes = function(source, args)
{
    Validation._validateCheckboxes(source, args);
    Validation._runCustomFunction(source, args);
    
    Validation._updateLabel(source, args);
    return args.IsValid;
}
//------------------------------------
Validation.hookupAdditionalControls = function(source)
{
    if(source == null || typeof(source.controlstovalidate) != 'string' || source.controlstovalidate == '')
        return;
        
    var aControlIds = source.controlstovalidate.split(";");
    for (var i=1; i<aControlIds.length; i++)
        ValidatorHookupControlID(aControlIds[i], source);
}
//------------------------------------
//------------------------------------
Validation._validate = function(source, args)
{
    if(args.Value.length == 0)
        return args.IsValid = source.attributes["requiredfield"] == null || source.attributes["requiredfield"].value == "False";
    
    var iMinimalSymCount = source.attributes["checkminimalsymcount"] == null ? 0 : parseInt(source.attributes["checkminimalsymcount"].value);
    if(args.Value.length < iMinimalSymCount)
        return args.IsValid = false;
        
    if(source.attributes["autovalidate"] == null)
        return args.IsValid = true;
        
    switch (source.attributes["autovalidate"].value)
    {
        case "Integer":
            return args.IsValid = Validation.checkInt(args.Value);
        case "UnsignedInteger":
            return args.IsValid = Validation.checkUInt(args.Value);
        case "MailAddress":
            return args.IsValid = Validation.checkMailAddress(args.Value);
        case "UnsignedDouble":
            return args.IsValid = Validation.checkUDouble(args.Value);            
        case "ZipCode":
            return args.IsValid = Validation.checkZipCode(args.Value);                        
        case "Url":
            return args.IsValid = Validation.checkUrl(args.Value);
        case "Date":
            return args.IsValid = Validation.checkDate(args.Value);
        case "UnsignedIntegerList":
            return args.IsValid = Validation.chkeckUinlList(args.Value);
        default:
            return args.IsValid = true;
    }    
}
//------------------------------------
Validation._validateCheckboxes = function(source, args)
{
    var aControlIds = source.controlstovalidate.split(";");
    var bIsAll = source.validatetype == "All";
    var bCommonRetVal = true;
    
    for (var i=0; i<aControlIds.length; i++)
    {
        var obj = document.getElementById(aControlIds[i]);
        if(obj.checked && !bIsAll)
            return args.IsValid = true;
        else if(!obj.checked && bIsAll)
            return args.IsValid = false;
        if(!obj.checked)
            bCommonRetVal = false;
    }
    return args.IsValid = bCommonRetVal;
}
//------------------------------------
Validation._updateLabel = function(source, args)
{
    //Getting Label Object
    if (source.attributes["labelcontrol"] == null) return;
    var sLabelID = source.attributes["labelcontrol"].value;
    var oLabel = document.getElementById(sLabelID);
    if (oLabel == null) return;
    
    //Getting Error Validator ID
    var errValidateID = source.attributes["errValidateID"] != null && source.attributes["errValidateID"].value != ""
        ? source.attributes["errValidateID"].value : source.id;
    
    //Updating Title For Label
    if(args.IsValid)
    {
        var errValidates = oLabel.attributes["ErrorValidates"] == null ? "" : oLabel.attributes["ErrorValidates"].value.replace(errValidateID + ";", "");
        oLabel.setAttribute("ErrorValidates", errValidates);
        
        if(errValidates == "" && oLabel.attributes["CustomClassName"] != null)
            oLabel.className = oLabel.attributes["CustomClassName"].value;        
    }
    else
    {
        var errValidates = oLabel.attributes["ErrorValidates"] == null ? "" : oLabel.attributes["ErrorValidates"].value;
        
        if(errValidates == "")
        {
            if(oLabel.className != "textHighlighted")
                oLabel.setAttribute("CustomClassName", oLabel.className);
            oLabel.className = "textHighlighted";
        }
        
        errValidates = errValidates.replace(errValidateID + ";", "") + errValidateID + ";";
        oLabel.setAttribute("ErrorValidates", errValidates);
    }
}
//------------------------------------
Validation._displaySubmitErrorMessage = function(source)
{
    //Getting Error Message Object
    if(source.attributes["submiterrormessage"] == null) return;
    var sMessageID = source.attributes["submiterrormessage"].value;
    var oMessage = document.getElementById(sMessageID);
    if (oMessage == null) return;
    
    //Displaying Error Message
    oMessage.style.visibility = oMessage.style.display = "";
}
//------------------------------------
Validation._runCustomFunction = function(source, args)
{
    if(source.attributes["customclientvalidationfunction"] == null || source.attributes["customclientvalidationfunction"].value == "")
        return args.IsValid;
    
    var pHandler = null;
    try
    {
        pHandler = eval(source.attributes["customclientvalidationfunction"].value);
        if (typeof(pHandler) != 'function')
            throw "non function";
    }
    catch (ex)
    {
        alert("SYSTEM ERROR!\nFile: /Scripts/Validation.js\nFUNCTION: Validation.validate.\n" 
        + "Client Validation Function: " + source.attributes["customclientvalidationfunction"].value 
        + "\n\n Client Validation Function does not found. Its call has been skipped.");
        return args.IsValid;
    }
    return pHandler(source, args);
}
//------------------------------------
Validation._updateErrorMessage = function(source, args)
{
    if(args.Value.length == 0 && source.attributes["requiredfield"] != null && source.attributes["requiredfield"].value != "False"
        && typeof(source.requirederrormessage) == 'string')
        source.errormessage = source.requirederrormessage;
    else if(typeof(source.invaliderrormessage) == 'string')
        source.errormessage = source.invaliderrormessage;  
    else if(typeof(source.requirederrormessage) == 'string')
        source.errormessage = null;
}
//------------------------------------
Validation._trim = function(value)
{
    var ltrim = /\s*((\S+\s*)*)/;
    var rtrim = /((\s*\S+)*)\s*/;
    return value.replace(ltrim, "$1").replace(rtrim, "$1");
}
//----------------------------------------------------------------------------------
Validation.checkUInt = function(sValue)
{
    return new RegExp(/^\d+$/).test(sValue);			
}
//----------------------------------------------------------------------------------
Validation.checkInt = function(sValue)
{
    return new RegExp(/^-?\d+$/).test(sValue);			
}
//----------------------------------------------------------------------------------
Validation.checkMailAddress = function(sValue)
{
    return new RegExp("^([0-9a-zA-Z]([-._\\w]*[0-9a-zA-Z_])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$").test(sValue);
}
//----------------------------------------------------------------------------------
Validation.checkUDouble = function(sValue)
{
    return new RegExp("^\\d*(\\.\\d*)?$").test(sValue);
}
//----------------------------------------------------------------------------------
Validation.checkZipCode = function(sValue)
{
   return true;// return new RegExp("^\\d{5}((-\\d{4})|(\\d{4}))?$").test(sValue);
}
//----------------------------------------------------------------------------------
Validation.checkUrl = function(sValue)
{
    return new RegExp("^(https?://)?(([0-9a-z_!~*'().&=+$%\-]+: )?[0-9a-z_!~*'().&=+$%\-]+@)?(([0-9]{1,3}\\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\\.)*([0-9a-z][0-9a-z\-]{0,61})?[0-9a-z]\\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#\-]+)+/?)$").test(sValue);
    //return new RegExp("^((([hH][tT][tT][pP][sS]?|[fF][tT][pP])\\:\\/\\/)?((([_a-zA-Z0-9%]+)(\\.[_a-zA-Z0-9%]+)*(\\.[a-zA-Z]{2,4}))|((([01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d{1,2}|2[0-4]\\d|25[0-5])))(\\b\\:(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)\\b)?((?:[\\/\\.][_a-zA-Z0-9%]+)*)((?:(?:\\?[_a-zA-Z0-9%]+=[_a-zA-Z0-9%]*)(?:(&[_a-zA-Z0-9%]+=[_a-zA-Z0-9%]*)*|&))|\\?)?)$").test(sValue);
}
//----------------------------------------------------------------------------------
Validation.checkDate = function(sValue)
{
    var d = null;
    try { d = new Date(Date.parse(sValue)); }
    catch (ex) { return false; }
    return d.getFullYear() > 1910;
}
//----------------------------------------------------------------------------------
Validation.chkeckUinlList = function(sValue)
{
    return new RegExp("^(\\s*(\\d+)\\s*,)*(\\s*\\d+\\s*)$").test(sValue);
}
//----------------------------------------------------------------------------------        
  
