// $Id: CheckForm.js,v 1.3 2006/03/07 10:23:01 mdaur Exp $
/**
 * Checks if an edit field has the allowed length
 */
function CheckLength(htmlField, length)
{
    if (htmlField.value.length > length)
    {   
        alert(textEntryTooLong + ": " + htmlField.value.length + 
              "\n" + textEntryCharsAllowed + ": " + length);
        htmlField.focus();
        return false;
    }
    else
    {
        return true;
    }

}

/**
 * check if the uploadfilename is in unix expressions
 * The text is checked against a regular expression
 * (default is "\w+" which stands for one or more occurances
 * of [A-Za-z0-9_])
 */
 
 /**
 * check if the uploadfilename is in unix expressions
 * The text is checked against a regular expression
 * (default is "\w+" which stands for one or more occurances
 * of [A-Za-z0-9_])
 */
function CheckUploadFile(textField, warnMessage)
{
   theResult = new Array();
   pattern = "/(\\\\|\\/)(\\w|\\.|-)*$/";
   
   // create the regular expression
   eval('theRegex=' + pattern);
   theResult = theRegex.exec(textField.value);
   
   if (theResult == null)
   {
 
      warnMessage = 
        warnMessage + "!\n" + 
        textFilenameCharsAllowed; 

      // pattern did not match. display warn message
      alert(warnMessage);
      textField.focus();
      return false;
   }

   return theResult[0];
}

/*
 *  old function
 *

function CheckUploadFile(textField, warnMessage)
{

	 		var checkOK = ". ()_-+ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
			var checkStr = textField.value;
			var allValid = true;
            
            strArr=checkStr.split("\\");

            checkStr = strArr[strArr.length-1];

			for (i = 0; i < checkStr.length; i++)
			{
				ch = checkStr.charAt(i);
				for (j = 0; j < checkOK.length; j++)
                {
                  //  alert (ch + "---" + checkOK.charAt(j));
					if (ch == checkOK.charAt(j))
                    {
					    break;
                    }
                }
                
                //alert (j + "***" + checkOK.length);
				if (j == checkOK.length)
				{
					allValid = false;
				    break;
				}
			}
			
			if (!allValid)
			{
				alert(warnMessage + "!\n" + textFilenameCharsAllowed);
				textField.focus();
				return (false);
			}
            else
            {
               // alert("OK");
                return (true)
            }
}
*/


/**
 * Check if a textfield or textarea contains at least
 * one alphanumeric character.
 * 
 */
function CheckText(textField, warnMessage, pattern)
{
   theResult = new Array();

   // check if a pattern has been pass. If not set the default
   // pattern /\S/ (all but whitespaces)
   if (typeof(pattern) == 'undefined' || pattern == '')
   {
      pattern = "/\\S/";
   }
         
   // create the regular expression
   eval('theRegex=' + pattern);
   theResult = theRegex.exec(textField.value);
   
   if (theResult == null)
   {
      // pattern did not match. display warn message
      alert(warnMessage);
      textField.focus();
      return false;
   }

   return theResult[0];
}

/**
 * Checks if a value from a select box is selected
 * The default value is assumed to be -1. So when the form is submitted
 * a value other than -1 is expected
 */
function CheckSelect(selectBox, warnMessage)
{
   if (selectBox.options[selectBox.selectedIndex].value == -1)
   {
      alert(warnMessage);
      selectBox.focus();
      return false;
   }

   return true;
}

/**
 * Checks if a value from a radio box is selected
 * size is number of radioBox-Buttons
 */
function CheckRadio(radioBox, size, warnMessage)
{
   check = 0;
   for (i = 0; i < size; i++)
   {
      check = check + radioBox[i].checked;
   }
   if (!check)
   {
      alert(warnMessage);
      radioBox[0].focus();
      return false;
   }

   return true;
}

/**
 * Resets a radio group to the default value
 * parameter radioButton should be the radio button object
 */
function radioResetter(radioButton) 
{
   for (i = 0; i < radioButton.length; i++) 
   {
      if (radioButton[i].defaultChecked==true) 
      {
         radioButton[i].checked=true;
      }
   }
}

/**
 * check the data set entry 
 * if the entry's = 0 the catergory can the category delete
 * parameter name the name of the category
 * parameter count the count of the appendant entry's
 */
function checkDelete(count, textConfirmCategoryDelete, textDeleteCategoryItemsFirst )
{  
    if (count > 0)
    {
        alert(textDeleteCategoryItemsFirst);
        return false;
    }
    else
    {
        return confirm(textConfirmCategoryDelete);
    }
}


var mandatoryArray 	= new Array();
mandatoryArray[0] 	= new Array();
var alreadyChecked  = new Array();

//TODO this is explorer Style.. netscape/mozilla need it 
//differently

/*********************************************************************/

//marks dependencies as mandatory
function markAsMandatory(type, trigger, fieldToMark)
{
    //0 = checkbox
    //1 = select
    //2 = radios

    
    if (trigger.name != fieldToMark)
    {
	    theField = document.getElementById("label_"+fieldToMark); 
        
	    if ((theField != null) && (typeof(theField) != 'undefined'))
	    {
	    	newText = "";
	    	//handle the checkboxes
		    if (type == 0)
		    {
		        if (trigger.checked == false)
		        {
		           //theField.name = theField.name;
		           theField.className = "";
		           mandatoryArray[0][fieldToMark] = "0";
		        }
		        else
		        {
                    //theField.innerText = theField.innerText + "*";
                    theField.className = "labelHighlight";
                    mandatoryArray[0][fieldToMark] = "1";
		        }
		    }
		    //handle the selectboxes
		    if (type == 1)
		    {
		        //first of all - reset the other dependencies to nothing
		    	kids = trigger.options;
		        
		        for (i =0; i < kids.length; i++)
		        {
		        	otherField = document.getElementById("label_"+trigger.options[i].name);
                    
		        	if (otherField != null)
		        	{
                        otherField.className="";
                        otherField.innerText = formNames[trigger.options[i].name];
                        mandatoryArray[0][trigger.options[i].name] = "0";
		        	}
                    
		        }
		        
		        //now select the selectedOne
		        theField.className="labelHighlight";
                theField.innerText = theField.innerText +"*";
		        mandatoryArray[0][fieldToMark] = "1";
		        
		    }
		    //handle the radios
		    if (type == 2)
		    {
		        
		    	theOtherRadios = document.getElementsByName(trigger.name);
		        
		        for (i =0; i < theOtherRadios.length; i++)
		        {
		        	otherField = document.getElementById("label_"+theOtherRadios[i].id);
		        	if (otherField != null)
		        	{
		        		otherField.className=""; 
		        		mandatoryArray[0][theOtherRadios[i].id] = "0";
		        	}
		        }
		        //now select the newly selected
		        theField.className="labelHighlight";
		        mandatoryArray[0][fieldToMark] = "1";
		        
		    }
		}
		else
		{
			if (type == 1)
		    {
		        //first of all - reset the other dependencies to nothing
		    	kids = trigger.options;
		        
		        for (i =0; i < kids.length; i++)
		        {
		        	otherField = document.getElementById("label_"+trigger.options[i].name);
		        	
		        	if (otherField != null)
		        	{
		        		otherField.className=""; 
                        
		        		mandatoryArray[0][trigger.options[i].name] = "0";
		        	}
		        }
		     }
             
             
		     if (type == 2)
		     {
		        theOtherRadios = document.getElementsByName(trigger.name);
		        
		        for (i =0; i < theOtherRadios.length; i++)
		        {
		        	otherField = document.getElementById("label_"+theOtherRadios[i].id);
		        	if (otherField != null)
		        	{
		        		otherField.className=""; 
		        		mandatoryArray[0][theOtherRadios[i].id] = "0";
		        	}
		        }
		     }
		}
	} 
}


/*********************************************************************/
//a function to handle the selectboxes
//takes the given selectbox and marks the
//dependencies as mandatory fields

function markAsMandatorySelect(type, trigger, selectedEntry)
{
	theField = trigger.options[selectedEntry].name;
	if ( (theField != null) && (typeof(theField) != 'undefined'))
	{
   		//we have no dependency, clear old ones!
        if (theField == "")
        {
            //run through all options
            kids = trigger.options;
            
            for (i =0; i < kids.length; i++)
            {
          	    otherField = document.getElementById("label_"+trigger.options[i].name);
                //if there is a dependency, reset the name
                //we get this from the form array. 
                if (otherField != null)
                {
                        otherField.innerText = formNames[trigger.options[i].name];
                        otherField.className="";
                        mandatoryArray[0][trigger.options[i].name] = "0";
          	    }
            }
        }
        else
        {
            markAsMandatory(1, trigger, theField)
        }
	}
}


/*********************************************************************/
//checks if the fields are filled correctly
var message = 		"";

function checkMyForm(checktheForm, theUrl)
{
	message =  TXT_PLEASE_CORRECT + ":\n\n";
	check = true;
    check2 = true;
    counter = 0;

    //check the mandatory fields defined in form generator
	for (z = 0; z < defaultMandatory.length; z++)
    {   
        for (var Eigenschaft in defaultMandatory[z])
        {
            if (Eigenschaft == "id")
        	{
        		
        		if (defaultMandatory[z]["type"] == "select")
        		{
        			theFieldArray = document.getElementsByName(defaultMandatory[z][Eigenschaft]); 
        			theField = theFieldArray[0];
        		}
        		else
        		{
        			theField = document.getElementById(defaultMandatory[z][Eigenschaft]); 
        		}

                if (theField.value == "")
		        {
                    message += (defaultMandatory[z]["label"] + "\n");
     	        	check = false;
                    counter++;
		        }
		        else
		        {
		        //check if its filled in right
		        	check = checkFormValue(theField.name, theField.value, defaultMandatory[z]['type']);
		        	//TODO: does not work in netscape
		        	alreadyChecked[alreadyChecked.length] = theField.name;
		        	if (check==false)
		        	{
		        		counter++;
		        	}
		        }
		    }
	    }
	}
	
    //check the dependency mandatory fields now.
    for (i = 0; i < mandatoryArray.length; i++)
    {
        for (var Eigenschaft in mandatoryArray[i])
        {
        	if (mandatoryArray[i][Eigenschaft] == "1")
        	{
        		theField = document.getElementById(Eigenschaft); 
        		
		        if (theField.value == "")
		        {
		        	message += (formNames[Eigenschaft] + "\n");
		        	check2 = false;
		        }
		    }
	    }
	}

//check if non mandatory fields have the right type too
	
	for (q=0;q < allFormFields.length; q++)
	{
		var doCheck = true;

		//checking if the field was already checked by a method
		//from above. if so: dont check again
		
		for (t=0; t < alreadyChecked.length; t++)
		{
			if (allFormFields[q]['id'] == alreadyChecked[t])
			{
				doCheck = false;
				break;
			}
		}
		if (doCheck)
		{	
	     	if (allFormFields[q]['type'] == "number")
	    	{
	    		theField = document.getElementById(allFormFields[q]['id']); 
	    		
	    		if (theField != null || typeof(theField) != 'undefined')
	    		{
	    			if (theField.value != "")
	    			{
	    				check2 = checkFormValue(theField.name, theField.value, allFormFields[q]['type']);
	    			}
	    		}
	    	}   
	    		
	    	if (allFormFields[q]['type'] == "email")
	    	{
	    		theField = document.getElementById(allFormFields[q]['id']); 
	    		
	    		if (theField != null || typeof(theField) != 'undefined')
	    		{
	    			if (theField.value != "")
	    			{
	    				check2 = checkFormValue(theField.name, theField.value, allFormFields[q]['type']);
	    			}
	    		}
	    	}
	    }
	}

    if (check && check2 && counter == 0 )
    {
       	document.form.action=theUrl;
    	document.form.submit();	
    }
    else
    {
    	alert (message);
    	return false;
    }
}

/*********************************************************************/
//checks the different types of form elements
//and returns false or true
//method ist Called from method "checkMyForm"

function checkFormValue(theName, theValue, type)
{
    var ergebnis = true;
	
    if (type == "email")
    {
        ergebnis =  checkEmail(theName,theValue);
    }
    if (type == "radio")
    {
        ergebnis =  checkRadios(theName, theValue, type);
    }
    if (type == "number")
    {
        ergebnis =  checkNumber(theName, theValue, type);
    }
	if (type == "select")
    {
    	ergebnis = checkFormSelect(theName, theValue, type);
    }
    
    if (type == "text")
    {
        ergebnis =  true;
    }
    if (type == "textline")
    {
        ergebnis =  true;
    }
    
    return ergebnis;
}


/****************************************************************************/
/** check for valid email address */
/****************************************************************************/

function checkEmail(theName, theValue, type)
{
    emails = true;
    if (theValue.search(/^\s*\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+\s*$/) != -1)
    {
        emails = true;
    }
    else
    {
        message += TXT_WRONG_EMAIL +"\n";
        emails =  false;
    }

    return emails;
}

/****************************************************************************/
/** check for at least one selected radio */
/****************************************************************************/

function checkRadios(theName, theValue, type)
{
    rCheck = 0;
    radios = true;
    theRadios = document.getElementsByName(theName);
    for (i = 0; i < theRadios.length; i++)
    {
        if (theRadios[i].checked == true)
        {
           rCheck++;
        }
    }
    if (rCheck == 0)
    {
        theParentName = formNames[theName];
        message += theParentName + "\n";
        radios = false;
    }
    
    return radios;
    
}

/****************************************************************************/
/** check for valid number format */
/****************************************************************************/

function checkNumber(theName, theValue, type)
{
	var ValidChars = "0123456789.,";
    var IsNumber=true;
    var Char;
    for (i = 0; i < theValue.length && IsNumber == true; i++) 
    { 
        Char = theValue.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }
    
    if (IsNumber == false)
    {
        theParentName = formNames[theName];
        message += (theParentName + TXT_IS_NOT_A_NUMBER + "\n");
    }
    return IsNumber;
}

/****************************************************************************/
/** check for valid selected selectBox */
/****************************************************************************/

function checkFormSelect(theName, theValue, type)
{
	
	
	theFieldArr = document.getElementsByName(theName);
	theField = theFieldArr[0];
	selectCheck = true;
	if (theField != null || typeof(theField) != 'undefined')
	{
		
		selectedValue = theField.options[theField.selectedIndex].value;
		
		if (selectedValue == "Choose" )
		{
			selectCheck = false;
			message += (formNames[theName]+ "\n");
		}
	}
	return selectCheck;
}



