/*
Main Public Function : validates the form input values.
Returns true if ok, false if the first validatation field has an error
in case of error : displays anvalidation error message in the <span id=errormsg> part of the lcalHTML page
and also adds red border around the field who caused the error 
*/
function ValidateForm(frm)
{
    // Reset all red borders around form elements
    for (var i=0;i<frm.length;i++)
        ResetBorder(frm.elements[i]);

    // check each form element
    for (var i=0;i<frm.length;i++)
    {
        var item = frm.elements[i];
        // we use lang attribute (lang="string|number|email" to indicate it is a mandatory field typed
        // we use the title attribute to display an error message
        if (item.lang=='email' && isEmail(item.value)==false)
            return ShowError(item);
        else if (item.lang=='string' && isString(item.value)==false)
            return ShowError(item);
        else if (item.lang=='number' && isNumber(item.value)==false)
            return ShowError(item);
       // Use of lang=password validation: there are two input password fields with names XXX and XXX2.
       // The 1st field is set with lang=string,the 2nd field is set with lang=password.
       // The validation tests that the value of the second field is not empty and equal to the first field 
        else if (item.lang=='password' && (isString(item.value)==false || item.value != frm.elements[item.name.substr(0, item.name.length-1)].value))
            return ShowError(item);
    }
    return true;
}

/*
Checks the values of a form item. If not valid, replaces the value with a validValue
 Used e.g. in autosave
 returns either the original value or the replaced valid value
       // Use of lang=password validation: there are two input password fields with names XXX and XXX2.
       // The 1st field is set with lang=string,the 2nd field is set with lang=password.
       // The validation tests that the value of the second field is not empty and equal to the first field 
*/
function GetValidValue(item)
{
    // we use a proprietary validValue attribute to store a valid value for field, in case the value is not valid

    if (item.validValue == undefined) // no validValue was specified
        return item.value;
        
    if ( (item.lang =='email' && isEmail(item.value)==false)
         || (item.lang=='string' && isString(item.value)==false)
         || (item.lang=='number' && isNumber(item.value)==false)
         || (item.lang=='password' && (isString(item.value)==false || item.value != frm.elements[item.name.substr(0, item.name.length-1)].value))
       )
        return item.validValue;
    else
        return item.value;
}
 
 // Sets all the checkboxes with name "chboxID" in the current document to checked
function SelectAll(chkboxID)
{
    var chkboxes = document.getElementsByName(chkboxID);
    
    for (var i=0;i<chkboxes.length;i++)
    {
        chkboxes[i].checked = true;
        hlp(chkboxes[i].parentNode.parentNode, '');
    }
}

 // Sets all the checkboxes with name "chboxID" in the current document to unchecked
function SelectNone(chkboxID)
{
    var chkboxes = document.getElementsByName(chkboxID);
    
    for (var i=0;i<chkboxes.length;i++)
    {
        chkboxes[i].checked = false;
        uhlp(chkboxes[i].parentNode.parentNode, '');
    }
}

// Sets all the checkboxes with id in a string list of ids separated by , to checked, or unchecked
function SelectListById(chkboxIDlist, checked)
{
    var chkboxIDs = chkboxIDlist.split(",");
    
    if (chkboxIDs.length == 1 && chkboxIDs[0] == "") // ie the string list does not contain any ids
        return;
    
    for (var i=0;i<chkboxIDs.length;i++)
    {
        var chkbox = document.getElementById(chkboxIDs[i]);
        if (chkbox == null) // Checkbox does not exist on page (is a normal case, eg for edit wiki sharing UI with users who are admin)
            continue;
        chkbox.checked = checked;
        if (checked)
        {
            hlp(chkbox.parentNode.parentNode, '');
            chkbox.disabled = true;
        }
        else
        {
            uhlp(chkbox.parentNode.parentNode, '');
            chkbox.disabled = false;
        }
    }

}

// Simulates a click twice on all checkboxes with name "chkboxID" that are already checked
// used in shared settings when unchecking a group, to recheck contacts that may belong to other groups
// or to recheck boxes with default settings
function ReclickChecked(chkboxID)
{
    var chkboxes = document.getElementsByName(chkboxID);
    
    for (var i=0;i<chkboxes.length;i++)
    {
        if (chkboxes[i].checked)
        {
            chkboxes[i].click();
            chkboxes[i].click();
        }
    }
    
}

/*
*******************************************
private functions used in form validation
*/   
function isString(strValue)
{
    return (typeof strValue == 'string' && strValue != '');
}

function isNumber(strValue)
{
    return (!isNaN(strValue) && strValue != '');
}

function isEmail(strValue) {
    if (strValue == "") return false;
    
    var emailFilter=/^.+@.+\..{2,10}$/; // change from 3 to 10 to match new top domain such as .info
    //var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strValue))) return false;
       
    //test email for illegal characters
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
    if (strValue.match(illegalChars)) return false;
    
    // we reject blank spaces (permitted between " ", but " are too complicated so rarely used
    if (strValue.indexOf(' ') != -1) return false;
    
    // there should be only one @
    if (strValue.indexOf('@') != strValue.lastIndexOf('@')) return false;
    
    // the last character must be a-z A-Z (ie not . ! etc,..)
    var lastChar = strValue.charAt(strValue.length-1); 
    if (!((lastChar >= 'a' && lastChar <= 'z') || (lastChar >= 'A' && lastChar <= 'Z'))) return false;
    
    return true;
}

function ShowError(widget)
{
    var msg = widget.getAttribute("msg"); // the error msg is taken from the title attribute
    if (msg == '') msg = 'This field is mandatory!';
    
    return ShowError2(msg, widget);
}

function ShowError2(msg, widget)
{
    // Displays the error message
    ShowInfo(msg, 'red');
        
    // Set a red border around the widget
    if (widget.tagName=='SELECT') // set the SPAN parent tag border... IE does not work with SELECT directly
        widget.parentNode.className = 'error';
    else
         widget.className = 'error';

    // Set the focus on the widget
    widget.focus();
    return false;
}

// Display a message on the notification area
// className = 'red' for error, 'yellow' for warning and 'loading' to show an loading animation
// msg = the text to display
function ShowInfo(msg, className)
{
    var msg_span = document.getElementById('msg');
    
    if (msg_span == null)
        msg_span = document.getElementById('onemsg'); // we try the page header

    if (msg_span == null) // the message won't be displayed if there's no 'msg' element in the page
        return;
    
    if (className=='loading')
    {
        msg_span.className = '';
        msg_span.innerHTML = '<img src="../img/indicator.gif" /> Loading...';
        msg_span.style.display = 'inline';
    }
    else
    {
        msg_span.className = className;
        msg_span.innerHTML = msg;
        msg_span.style.display = (msg != '') ? 'inline' : 'none';
    }
}

// Hides the notificatin area
function HideInfo()
{
    var msg_span = document.getElementById('msg');
    
    if (msg_span == null)
        msg_span = document.getElementById('onemsg'); // we try the page header

    if (msg_span == null) // the message won't be displayed if there's no 'msg' element in the page
        return;

    msg_span.style.display = 'none';
}

function SetTitle(title) {
    document.getElementById('headertitle').innerHTML = title;
}

function ResetBorder(widget) {
    // set the SPAN parent tag border... IE does not work with SELECT directly, this is why BaseWriter.WriteComBoBox
    // adds a fake <span> around the <select> tag of the combo
    if (widget.tagName=='SELECT') 
        widget.parentNode.className='';
    else
        widget.className='';
    return true;
}
  
// Hyperlink with popup mesage to confirm, and if users clicks OK, go to URL, else cancel
function ConfirmOnClickLink(msg, url) {
    var go = confirm(msg);
    if (go)
        window.location = url; 
}

// Set the email of logged user on top of the screen
function SetEmail(email) {
    // see PageLayout.WriteHeader
    document.getElementById('loggedemail').innerHTML = email;
}


/////////////////////////////// For support

// Custom Support Form Validation : requires form.js
function ValidateSupport(frm)  {
    ResetBorder(frm.email);
    ResetBorder(frm.subject);
    ResetBorder(frm.topic);
    ResetBorder(frm.message);

    if(isEmail(frm.email.value)==false)
        return ShowError(frm.email);
    
    if (isNumber(frm.subject.value) == false)
        return ShowError(frm.subject);
    
    if (frm.subject.value==1 && frm.topic.value=='')
        return ShowError2('Please select a topic.', frm.topic);
    
    if (isString(frm.message.value) == false)
        return ShowError2('Please enter a message.', frm.message);
    
    return true;
}

///////////////////// Other utilities

// used in Renew Licenses form

function submitPurchase() {
    var frm = document.forms['frm'];
    
    for (var i=0;i<frm.length;i++) {
        var item = frm.elements[i];
        if (item.type == "checkbox" && item.checked) {
            frm.submit();
            return;
        }     
    }
    
    alert('Please check one or more users.');
}

function submitForm() {
    var frm = document.forms['frm'];
    if (ValidateForm(frm) == true) {
        frm.submit();
    }
}