/* ---------------------------------------------------------------
  ui-validation routines.

  Purpose: Provide consistent form validation routines for use 
           across all form dialogs in the Control Panel.

  Params:
      ele_id    (required ele or ele id)
			The ID of the form element to validate
      required  (optional string)
			The name of the branding string or the message to display
            to the user when a value has not been supplied.
            This can also be set to 'false'
      validate  (optional string)
            A string indicating what type of validation should be performed
            in the supplied value.
            Valid Values:
            - string
            - alphanumeric
            - number
            - email
            - domain
            - domain_or_email
            - ip
            - userid
            - filename
            - alias
            - webalias
            - zip

      valid_msg (optional string, required if validate is enabled)
			The name of the branding string or the message to display
            when the value provided does not validate.

  Date        : 2/1/07
  Author      : Charles Hunt <cchunt@verio.net>

  Notes       : This is for use specifically with the Form validation
                templates in use in ui-forms.xsl.

  Usage   : 
  ui_field_validate( 'ele_id', 'msg_required_val', 'string', 'msg_invalid' );

     
------------------------------------------------------------------
*/
function ui_field_validate ( id, required, validate, msg, real_field )
{
  if(document.pressed == 'cancel') { return true; }
  if(document.validation == 'false') { return true; }

  if ( ((required == '') || (required == undefined)) && (validate == '') )
  {
    return true;
  }


  var present = true;
  var valid   = true;
  // This is done in order to support passing the string directly in.
  var valid_msg    = document.js_strings[ msg ] || msg;  
  var required_msg = document.js_strings[ required ] || required;

  var ele     = document.getElementById( id );

  real_field = real_field != null ? real_field : id;
  real_ele = document.getElementById( real_field );

  // Is ele a valid form element?
  if (ele == null) {
    throw("Undefined element '" + id + "'");
  }

  if (ele.type == null) {
    throw("Attempt to validate a non-form element '" + id + "'");
  }

  if ( (required != undefined) && (required != 'false') )
  {
    if ( ele.type == 'checkbox' && ele.checked == false)
    {
      present = false;
    }
    else if ( ele.type == 'text' && ele.value == '' )
    {
      present = false;
    }
    else if ( ele.type == 'hidden' && ele.value == '' )
    {
      present = false;
    }
    else if ( ele.type == 'file' && ele.value == '' )
    {
      present = false;
    }
    else if ( ele.type == 'password' && ele.value == '' )
    {
      present = false;
    }
    else if ( ele.type == 'select' && ele.selected == '' )
    {
      present = false;
    }
    else if ( ele.type == 'textarea' && ele.value == '' )
    {
      present = false;
    }
  }

  if ( validate != '' && ele.value != '' )
  {
    switch ( validate )
    {
      case 'string':
        valid = is_string(ele.value.replace(/^\s*|\s*$/g, ''));
        break;
      case 'alphanumeric':
        valid = is_alphanumeric(ele.value);
		break;
      case 'number' :
        valid = is_number(ele.value);
        break;
      case 'email' :
        valid = is_email(ele.value);
        break;
      case 'domain' :
        valid = is_domain(ele.value);
        break;
      case 'domain_or_email' :
        valid = is_domain(ele.value) || is_email(ele.value);
        break;
      case 'ip' :
        valid = is_ip(ele.value);
        break;
      case 'userid' :
        valid = is_userid(ele.value);
        break;
      case 'filename' :
        valid = is_filename(ele.value);
        break;
      case 'alias' :
        valid = is_alias(ele.value);
        break;
      case 'webalias' :
        valid = is_webalias(ele.value);
        break;
      case 'zip' :
        valid = is_zip(ele.value);
        break;
      default:
        valid = true;
    }
  }


  if (present == false)
  {
    validation_highlight( real_ele );
    alert( required_msg );
    return false;
  }
  else if ( valid == false )
  {
    validation_highlight( real_ele );
    alert( valid_msg );
    return false;
  }
  else
  {
    Element.removeClassName( real_ele, 'input_error' );
  }
  return true;

} // END ui_field_validate


function ui_field_checkChange(orig_data, new_data, validation_type )
{
	if ( document.pressed == 'cancel' )
	{
    
		var changesFound = 0;

		if ( validation_type == 'data_table' )
		{
			var oData = eval(orig_data);
			var oDataArray = oData.data_array;
			var oDataSource;
			var nDataSource;
			var found;
			if ( oDataArray.length != new_data.length )
			{
				changesFound = 1;
			}
			else
			{
				for ( var x=0; x < oDataArray.length; x++)
				{
					found = 0;
					oDataSource = oDataArray[x].columns.toSource().toLowerCase();

					for ( var y=0; y < new_data.length; y++ )
					{
						nDataSource = new_data[y].columns.toSource().toLowerCase();
						if ( nDataSource == oDataSource )
						{
							found = 1;
							break;
						}
					}
					if ( !found )
					{
						changesFound = 1;
						break;
					}
				}
			}
		}
		else if ( validation_type == 'checkbox' )
		{
			var checkObj = document.getElementById(orig_data);
			if 
			( 
				( new_data == '' && checkObj.checked == true ) 
				  || ( new_data != '' && checkObj.checked == false ) 
			)
			{
				changesFound = 1;
			}
		}
		else if ( validation_type == 'radio' )
		{
			var checkObj = document.getElementsByName(orig_data);
			for ( var x=0; x < checkObj.length; x++)
			{
				if ( checkObj[x].checked )
				{
					if ( checkObj[x].value != new_data )
					{
						changesFound = 1;
					}
				}
			}
		}
		else
		{
          // text input field.
			var checkObj = document.getElementById(orig_data).value.replace(/\n/g,'');
			if ( checkObj != new_data )
			{
				changesFound = 1;
			}
		}

		if ( changesFound )
		{
            var confirm_msg = document.js_strings[ 'msg_confirm_cancel' ] || 'msg_confirm_cancel';
           
			if ( confirm( confirm_msg ) )
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	}

} // END ui_field_checkChange


/* ---------------------------------------------------------------
  Name      : confirmAction

  Purpose: confirm the action.

  Parameters:
      msg     -   (required value) confirm message when button is pressed.
------------------------------------------------------------------
*/
function confirmAction( msg )
{
  var message = document.js_strings[ msg ] || msg;

  if(document.pressed == 'reinstall')
  {
    if( confirm( message ) ) {
      return true;
    } else {
      return false;
    }
  }
}


/* ---------------------------------------------------------------
  Name      :  passwordCompare

  Purpose: Compare the value in two password fields.

  Parameters:
      id, id2 -   (required value) ids of the two password fields
      msg     -   (required value) alert message when the value in two password fields don't match.
------------------------------------------------------------------
*/
function passwordCompare(id, id2, msg)
{
  if(document.pressed == 'cancel') { return true; }
  if(document.validation == 'false') { return true; }
  if ( $(id) == undefined || $(id2) == undefined ) {return true;}

  var message = document.js_strings[ msg ] || msg;

  if ( $(id).value != $(id2).value ) 
  {
    validation_highlight( id2 );
    alert( message );
    return false;  
  }

  return true;
}


/* ---------------------------------------------------------------
  Name      : is_string

  Purpose: Validate a form input value. Make sure its a string 
           and not a number.

  Parameters: 
      string -   (required value)
        The value of the form input to be tested.

------------------------------------------------------------------
*/
function is_string(str)
{
  return (typeof str == 'string' && str != '' && isNaN(str));
} // END is_string


function is_alphanumeric(str)
{
	if ((is_string(str.replace(/^\s*|\s*$/g, ''))) || (is_number(str)))
	{
		return true;
	}
	else
	{
		return false;
	}	
}

/* ---------------------------------------------------------------
  Name      :  is_number

  Purpose: Validate a form input value. Make sure its a number

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_number(str)
{
  return (!isNaN(str) && str != '');
} // END is_number

/* ---------------------------------------------------------------
  Name      :  is_email

  Purpose: Validate a form input value. Make sure its a valid 
           email addy

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_email(str)
{
  var objRE = /^(?:[\w-\'\!\#\$\%\&\*\+\-\/\=\?\^\`\{\|\}\~\_]+(([\.]|[\.][\.])(?![\@])){0,1})+([\.]{0,1})\@([\d\_a-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;

  return (str != '' && objRE.test(str));
} // END is_email


/* ---------------------------------------------------------------
  Name      :  is_filename

  Purpose: Validate a form input value. Make sure its a valid 
           filename

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_filename(str)
{
  var reBadChars = /[\/\\\:\*\?"<>|]/;
  if ((reBadChars.test(str)) || (str == '')) 
  {
    return false;
  } 

  return true;
} // END is_filename

/* ---------------------------------------------------------------
  Name      :  is_zip

  Purpose: Validate a form input value. Make sure its a valid
           zip code 

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_zip(str)
{
  var objRE = /^[0-9]{5}(-[0-9]{4})?$/;

  return (str != '' && objRE.test(str));
} // END is_zip


/* ---------------------------------------------------------------
  Name      :  is_domain

  Purpose: Validate a form input value. Make sure its a valid
           domain name

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_domain(str)
{
  var objRE = /^([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;

  return (str != '' && objRE.test(str));
} // END is_domain

/* ---------------------------------------------------------------
  Name      :  is_ip

  Purpose: Validate a form input value. Make sure its a valid
           ip address

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_ip(str)
{
  var objRE = /^([1]?\d\d?|2[0-4]\d|25[0-5])\.([1]?\d\d?|2[0-4]\d|25[0-5])\.([1]?\d\d?|2[0-4]\d|25[0-5])\.([1]?\d\d?|2[0-4]\d|25[0-5])$/;

  return (str != '' && objRE.test(str));
} // END is_ip

/* ---------------------------------------------------------------
  Name      :  is_alias_

  Purpose: Validate a form input value. Make sure its a valid
           alias format

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_alias(str)
{
  var objRE = /^[a-zA-Z0-9_.-]*$/;

  return (objRE.test(str));
} // END is_alias

/* ---------------------------------------------------------------
  Name      :  is_userid

  Purpose: Validate a form input value. Make sure its a valid
           userid

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_userid(str)
{
  var objRE = (/^(?:[a-z][a-z0-9\._-]*|[0-9][a-z0-9\._-]*[a-z][a-z0-9\._-]*)$/i);

  return (str != '' && objRE.test(str));
} // END is_userid

/* ---------------------------------------------------------------
  Name      :  is_webalias

  Purpose: Validate a form input value. Make sure its a valid
           webalias format

  Parameters:
      string -   (required value)
        The value of the form input to be tested.
------------------------------------------------------------------
*/
function is_webalias(str)
{
  var objRE = /[\/\\\:\*\?"<>|]/;

  return (! objRE.test(str));
} // END is_webalias

/* ---------------------------------------------------------------
  Name      :  stringCompare

  Purpose: Compare two strings for equality.

  Parameters:
      string -   (required value)
        The value of the first string to compare.
      string -   (required value)
        The value of the second string to compare.
------------------------------------------------------------------
*/
function stringCompare(str1,str2)
{
  if (str1 == str2)
  {
    return true;
  }

  return false;
}

/* ---------------------------------------------------------------
  Name      :  validation_highlight

  Purpose: highlight a field indicating an error. 

  Parameters:
      fieldId -   (the id of the field which to hightlight)
        The value of the first string to compare.
------------------------------------------------------------------
*/
function validation_highlight( id )
{
   $(id).addClassName('input_error');
   // Some complex fields are not form fields
   try {
       $(id).select();
       $(id).focus();
   } catch (e) {
   }
} // END validation_highlight 

/* ---------------------------------------------------------------
  Name      :  validatePassword 

  Purpose: Validates the Password rules.  Rules are currently
           Password <> Userid
           Password must contain 1 numeric
	   Password must be > 7 characters.

  Parameters:
      password - password
------------------------------------------------------------------ 
*/
function validatePassword(password)
{
	if(document.pressed == 'cancel') { return true; }
	if ($(password).value == '') { return true; }
	if (($(password).value.length) < 6)
	{
		alert(document.js_strings.error_password_length);
		return false;
	}
	if ($(password).value == document.js_strings.userid)
	{
		alert(document.js_strings.error_password_userid);
		return false;
	}
	var myRe= /[0-9]/;
	if (!(myRe.exec($(password).value)))
	{
		alert(document.js_strings.error_password_number_req);
		return false;
	} 
  return true; 
}

