var validator_Active = false;
var validator_message = "";
var validator_success = true;

function validator_OnLoad() 
{
	if (typeof(validator_PageValidators) == "undefined")
	{
		return;
	}
	var i, val;
	if (validator_PageValidators.length > 0)
	{
		validator_Active = true;
		validator_ClearControlsValidatedState();
	}
}

function validator_OnSubmit() 
{
//alert('val');
	if (!validator_Active)
	{
		return true;
	}

	var boolValidPage = true;
	validator_message = "";

	for (var i = 0; i < validator_PageValidators.length; i++ )
	{
		boolValid = validator_Validate(validator_PageValidators[i]);
		boolValidPage = boolValidPage && boolValid;
	}

    //  Set the global submit break
    if (typeof(__global_SubmitSuccess) != "undefined")
    {
	    __global_SubmitSuccess = boolValidPage;
	}
	
	//  Show the info about the error
	if (boolValidPage == false)
	{
        //  Restore watermarks, they should be cleared before
	    RestoreWatermarkedTextBoxes();

		window.event.cancelBubble = true;
		alert("Zadané údaje obsahují chyby\n" + validator_message + "\n\nProsím opravte chybné údaje ...");
		validator_message = "";
	}

	
//alert('val result' + boolValidPage);
	return boolValidPage;
}

// nastavi vsetkym validovanym kontrolkam priznak validated na false
function validator_ClearControlsValidatedState()
{
	for (var i = 0; i < validator_PageValidators.length; i++ )
	{
		var obj = document.getElementById(validator_PageValidators[i].getAttribute('control'));	
		
		// prida event handler na onchange event k uz zaregistrovanemu hanlderu
		AttachEvent(obj, 'onchange', validator_ClearControlValidatedState);
		obj.validated = false;
	}		
}

// nastavi priznak validated na false volajucej kontrolky
function validator_ClearControlValidatedState()
{
	event.srcElement.validated = false;		
}


function validator_Validate(objValidator) 
{    
	var boolSingleValidation = false;
	var strFieldLabel = "";
	var onSubmit = false;

	// run on event
	if (objValidator == null)
	{
		objValidator = document.getElementById(event.srcElement.id + '_val');
		boolSingleValidation = true;
		validator_message = "";
	}
	//run on submit
	else
	{
		onSubmit = true;
		var controlId = objValidator.getAttribute('control');
    	var objControl = document.getElementById(controlId);
		
		if (document.getElementById(controlId + "_label") != null)
		{
			strFieldLabel = document.getElementById(controlId + "_label").innerText;
		}
		if ((strFieldLabel.length == 0) && (objControl.getAttribute('WatermarkText') != null))
		{
		    strFieldLabel = objControl.getAttribute('WatermarkText');
		}
	}
		
	// set validator to invalid state
	objValidator.isvalid = true;		

	var controlId = objValidator.getAttribute('control');
   	var objControl = document.getElementById(controlId);

	
	//  remove watermarks
    if (objControl.isWatermarked)
	{
//	alert(objControl.id + ' isWm');
		ClearWatermarkText(objControl);
	}
	
	if (!objControl.validated)
	{		
		// do all requested validation for this validator
		for (var i = 0; i < objValidator.getAttribute("count"); i++)
		{								
			attr = objValidator.getAttribute("" + i + "_val");
			if (onSubmit && (attr == 'validator_AjaxValidator'))
			{
				continue;
			}
			if (typeof(attr) == "string")
			{
				eval("attr = " + attr + ";");				
				if (! attr(objValidator, i))
				{
					objValidator.isvalid = objValidator.isvalid && false;
					if (strFieldLabel != "")
					{
						validator_message += "\n" + strFieldLabel;
						strFieldLabel = "";
					}
//					validator_message += "\n - " + objValidator.getAttribute("" + i + "_msg");
					validator_message += " - " + objValidator.getAttribute("" + i + "_msg");
				 }
				 else
				 {
					objValidator.isvalid = objValidator.isvalid && true;
				 }
			 }
		}
		
		objControl.validated = objValidator.isvalid;
	}		
	
	if (boolSingleValidation && (objValidator.isvalid == false))
	{
		alert("Zadaný údaj obsahuje chyby \n" + validator_message + "\n \n Prosím opravte chybný údaj ...");
		validator_message = "";
		document.getElementById(objValidator.control).focus();
	}
	
	//  Get the watermark back
	if (objControl.isWatermarked)
    {
        RestoreWatermarkText(objControl);
    }

	return objValidator.isvalid;
}


function validator_GetValue(id)
{
	var objControl;
	objControl = document.getElementById(id);
	if (typeof(objControl.value) == "string")
	{
		return objControl.value;
	}
  return "";
}



/*
 * Validation methods
 */


// field has to be filled in
function validator_Required(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	return validator_GetValue(controlId) != "";
}

// only number
function validator_NumberOnly(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	return !isNaN(validator_GetValue(controlId).replace(',','.'))
}

// number interval
function validator_NumberInterval(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	var intMin = objValidator.getAttribute("" + ID + "_min") * 1;
	var intMax = objValidator.getAttribute("" + ID + "_max") * 1;
	var intValue = validator_GetValue(controlId) * 1;
	
	return ((intValue >= intMin) && (intValue <= intMax));
}

// number interval or empty value
function validator_NumberIntervalOrEmpty(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	var intMin = objValidator.getAttribute("" + ID + "_min") * 1;
	var intMax = objValidator.getAttribute("" + ID + "_max") * 1;
	var value = validator_GetValue(controlId);
	if (value != "")
	{
		if (!isNaN(value.replace(',','.')))
			return ((intValue >= intMin) && (intValue <= intMax));
		else
			return false;
	}
	else
		return true;	
}

// regular expression
function validator_RegExp(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	var Value = validator_GetValue(controlId);
	var Expression = objValidator.getAttribute("" + ID + "_exp");
	

  if (Value.length == 0)
  {
		return true;
	}
	var rx = new RegExp(Expression);
	var matches = rx.exec(Value);
	return (matches != null && Value == matches[0]);
}

// max length
function validator_MaxLength(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	var Value = validator_GetValue(controlId);
	var Length = objValidator.getAttribute("" + ID + "_len") * 1;

  if (Value.length > Length)
  {
		return false;
	}
	return true;
}

// min length
function validator_MinLength(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	var Value = validator_GetValue(controlId);
	var Length = objValidator.getAttribute("" + ID + "_len") * 1;

  if (Value.length < Length)
  {
		return false;
	}
	return true;
}

//
// Ajax validator
function validator_AjaxValidator(objValidator, ID)
{
	var controlId = objValidator.getAttribute('control');
	var value = validator_GetValue(controlId);		
	var serverMethod = objValidator.getAttribute("" + ID + "_fnc");	

	document.getElementById(controlId + '_validationicon').style.display = 'none';
	document.getElementById(controlId + '_ajaxicon').style.visibility = 'visible';
	
	eval(serverMethod + "('" + controlId + "', value, validator_AjaxValidator_callback);");	
	
	return true;
}

function validator_AjaxValidator_callback(result)
{	
	document.getElementById(result.value.ControlId + '_ajaxicon').style.visibility = 'hidden';
	
	// chybova hlaska nie je nastavena validacia je ok
	if (result.value.Message.length == 0)
	{
		document.getElementById(result.value.ControlId + '_validationicon').style.display = 'none';
	}
	// chyba
	else
	{
		document.getElementById(result.value.ControlId + '_validationicon').style.display = 'inline';
		document.getElementById(result.value.ControlId + '_validationicon').alt = result.value.Message;
	}
}
