//javascript functions library used into capoeira Nago Site
//---------------------------------------------------------
// Version     : 1.0
// Author      : Fabrizio Parlani
// E-Mail      : fabrizio.parlani@gmail.com
// MSN Contact : fabermaster@hotmail.com
// Skype       : fabermaster73
//---------------------------------------------------------

      //add a trim function to String object
      String.prototype.trim = function() 
                              {
                                a = this.replace(/^\s+/, '');
                                return a.replace(/\s+$/, '');
                              };

      function highlightRow(objRef, color)
      { objRef.bgColor = color; }

      function render(displayObject, page)
      {
        //create instance of XMLHttp Object
        var oXmlHttp = zXmlHttp.createRequest();
            //cancel any hanging requests 
            if (oXmlHttp.readyState != 0) 
            { oXmlHttp.abort(); }
            //create a new request
            oXmlHttp.open("get", page, true);  
            //create event handler for response
            oXmlHttp.onreadystatechange = function () 
                                          {
                                            if (oXmlHttp.readyState == 4) 
                                            {
                                              if (oXmlHttp.status == 200) 
                                              { 
                                                displayText(displayObject, oXmlHttp.responseText);
                                              } 
                                              else 
                                              { displayText(displayObject, "An error occurred during request operation [GET] : " + oXmlHttp.statusText); /*statusText is not always accurate*/  }
                                            }            
                                          };
        //send request
        oXmlHttp.send(null);
      }

      function sendAction(displayObject, formObject, returnPage) 
      {
        //get form object reference
        var oForm = formObject;
        //compose query string from existing form objects
        var sBody = getRequestBody(oForm);
        //create instance of XMLHttp Object
        var oXmlHttp = zXmlHttp.createRequest();
        
        //clear eventually previous written signals
        displayText(displayObject, '');

            //cancel any hanging requests 
            if (oXmlHttp.readyState != 0) 
            { oXmlHttp.abort(); }
            //create request
            oXmlHttp.open("post", oForm.action, true);
            //set appropriate header for the request
            oXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //create event handler for response
            oXmlHttp.onreadystatechange = function () 
                                          {
                                            if (oXmlHttp.readyState == 4) 
                                            {
                                              if (oXmlHttp.status == 200) 
                                              { 
                                                //show eventually ruturned message from executed operation
                                                displayText(displayObject, oXmlHttp.responseText); 
                                                //check for a returning page to display
                                                if (returnPage != '')
                                                {
                                                  //go to operation return page
                                                  render(displayObject, returnPage);
                                                }
                                              } 
                                              else 
                                              { displayText(displayObject, "An error occurred during requested operation [POST] : " + oXmlHttp.statusText + " - " + returnPage); }
                                            }            
                                          };
        //send request                                          
        oXmlHttp.send(sBody);        
      }

      function getRequestBody(oForm) 
      {
        //create an Array object
        var aParams = new Array();
        //cycle across passed form objects    
        for (var i = 0 ; i < oForm.elements.length; i++) 
        {
          //compose each parameter as shown : { name=value }
          var sParam  = encodeURIComponent(oForm.elements[i].name);
              sParam += "=";
              sParam += encodeURIComponent(oForm.elements[i].value);
              //add composed parameter to array
              aParams.push(sParam);
        } 
        //link array objects with passed char... so we have composed the query string {name1=value1}&{name2=value2}&... and so on
        return aParams.join("&");        
      }

      function displayText(elementName, text2Render)
      {
        var targetObject       = document.getElementById(elementName);
        targetObject.innerHTML = text2Render;
      }

      function setCmd(commandName, commandValue)
      {
        try
        {
          //get object to set
          var obj2Set   = eval('document.runner.' + commandName);
          //set value for obtained object
          obj2Set.value =  commandValue ; 
        }
        catch (Exception)
        { /*Nothing to do... silent error*/ alert('Errore nell\'impostazione del valore associato a ' + commandName +  ' : ' + commandValue);}
      }
      
      function runForm()
      { document.runner.submit(); }

      function hndPaging(pagingSel, pageToGo, direction, boundId)
      {
        //save passed data
        eval('document.runner.' + pagingSel + 'NumPage.value    = ' + pageToGo);
        eval('document.runner.' + pagingSel + 'Scrolling.value  = \'' + direction + '\'');
        eval('document.runner.' + pagingSel + 'BoundId.value    = ' + boundId);
  
        //run command
        document.runner.submit();
      }
      
      function addMessage(renderObject, formObject, returnPage)
      {
        //get message text
        var text2Write  = new String(formObject.msgTxt.value);
        //check for inserted message
        if (text2Write.trim() != '')
        {
          //save message text into an hidden field
          formObject.saveMsg.value = text2Write;
          //clear wrote message
          formObject.msgTxt.value  = '';
          //add passed message
          sendAction(renderObject, formObject, returnPage);
        }
        else
        {
          //show error
          alert('Attenzione : \nNon si può inserire un messaggio vuoto!');
          //set focus to text area
          formObject.msgTxt.focus();
        }
      }
      
      function addComment(renderObject, formObject, returnPage)
      {
        //get message from
        var commentFrom    = new String(formObject.cmtFrom.value)
        //get message text
        var comment2Write  = new String(formObject.cmtText.value);
        //check for inserted 'from' name
        if (commentFrom.trim() != '')
        {
          //check for inserted message
          if (comment2Write.trim() != '')
          {
            //save from info into an hidden field
            formObject.saveFrom.value = commentFrom;
            //save message text into an hidden field
            formObject.saveText.value = comment2Write;
            //clear from info
            formObject.cmtFrom.value  = '';
            //clear wrote comment
            formObject.cmtText.value  = '';
            //add passed comment
            sendAction(renderObject, formObject, returnPage);
          }
          else
          {
            //show error
            alert('Oooooooooooops : \nForse ti sei scordato di scrivere il saluto!');
            //set focus to text area
            formObject.cmtText.focus();
          }
        }
        else
        {
          //show error
          alert('Mmmmmmmmmmmmmm : \nNon vuoi lasciari detto chi sei?\nPotresti sembrare scortese no?');
          //set focus to from field
          formObject.cmtFrom.focus();
        }
      }
      
      function openLink(pageName, parameterString, targetName, pageWidth, pageHeight, modalType)
      {
        /*Save passed parameters*/
        var popUpWidth  = new Number(pageWidth);
        var popUpHeight = new Number(pageHeight);
        /*Calculate position to center pop-up*/
        var leftCorner  = new Number(screen.width)
            leftCorner  = ((leftCorner - popUpWidth) / 2)
        var topCorner   = new Number(screen.height)
            topCorner   = ((topCorner - popUpHeight) / 2)
        //check to create a modal pop-up
        if (modalType == 'modal')
        {
          //check for showModalDialog method existance
          if (window.showModalDialog) 
          {
            /*Open the modal pop-up*/
            window.showModalDialog(pageName + '?' + parameterString,
                                   targetName,
                                   'directories=0,modal=1,dialogHeight=' + pageHeight + ',dialogWidth=' + pageWidth + ',location=0,menubar=0,resizable=0,scrollbars=1,status=0,toolbar=0,left=' + leftCorner.toString(10) + ',top=' + topCorner.toString(10) + '\'');
          } 
          else 
          {
            /*Open the pop-up making it modal with attribute modal=[ yes | 1 ]*/
            window.open(pageName + '?' + parameterString, 
                        targetName, 
                        'directories=0,modal=1,height=' + pageHeight + ',width=' + pageWidth + ',location=0,menubar=0,resizable=0,scrollbars=1,status=0,toolbar=0,left=' + leftCorner.toString(10) + ',top=' + topCorner.toString(10) + '\'');
          }
        }
        else
        {
          /*Open the pop-up*/
          window.open(pageName + '?' + parameterString, 
                      targetName, 
                      'directories=0,height=' + pageHeight + ',width=' + pageWidth + ',location=0,menubar=0,resizable=0,scrollbars=1,status=0,toolbar=0,left=' + leftCorner.toString(10) + ',top=' + topCorner.toString(10) + '\'');
        }
      }

      /*Functions used to get client sysdate*/
      function lPadDayMonth(x) 
      { return (x < 0 || x > 9 ? "" : "0") + x }

      function getDateTime(date) 
      { with (date) return lPadDayMonth(getDate()) + '/' + lPadDayMonth(getMonth()+1) + '/' + getFullYear() + ' ' + getHours() + ':' + getMinutes() }
      /*End functions used to get client sysdate*/


      /* ------------------------------------------------------------------------------------------ */
      /* Here start a set of functions to limit input characters into form fields  */
      /* ------------------------------------------------------------------------------------------ */
      function limitString(e) 
      {
        var ev  = e ? e : event; // Gecko  receive the event as parameter into variable e
                                 // IE initialize the  event  object
        var key = ev.charCode ? ev.charCode : ev.keyCode; // IE hasn't charCode 
  
        //check for key pressed
        if ( ((key > 47) && (key < 58)) ||   // from '0' to '9'
             (key == 8)   ||                 // backspace
             (key == 9)   ||                 // canc
             (key == 13)  ||                 // return
             (key == 32)  ||                 // space
             (key == 33)  ||                 // !
             (key == 35)  ||                 // #
             (key == 39)  ||                 // '
             (key == 40)  ||                 // (
             (key == 41)  ||                 // )
             (key == 42)  ||                 // *
             (key == 43)  ||                 // +
             (key == 44)  ||                 // ,
             (key == 45)  ||                 // -
             (key == 46)  ||                 // .
             (key == 47)  ||                 // /
             (key == 58)  ||                 // :
             (key == 59)  ||                 // ;
             (key == 60)  ||                 // <
             (key == 61)  ||                 // =
             (key == 62)  ||                 // >
             (key == 63)  ||                 // ?
             (key == 64)  ||                 // @
             (key == 92)  ||                 // \
             (key == 95)  ||                 // _
//             (key == 224) ||                 // à
//             (key == 232) ||                 // è
//             (key == 233) ||                 // é
//             (key == 236) ||                 // ì
//             (key == 242) ||                 // ò
//             (key == 249) ||                 // ù
             ((key > 64) && (key < 91)) ||   // from 'A' to 'Z'
             ((key > 96) && (key < 123))     // from 'a' to 'z'
           ) 
        { 
          //Nothing to do... write passed char
        }
        else 
        {
          //When an unaccepted character has been pressed , we must avoid  event handling
          if (ev.preventDefault) 
          { 
            e.preventDefault(); // Gecko use preventDefault  to avoid event handling
          } 
          else if ('returnValue' in ev ) 
          { 
            ev.returnValue = false; // IE use returnValue  to avoid event handling
          }
        }
      }
      
      function limitNumber(e) 
      {
        var ev  = e ? e : event; // Gecko  receive the event as parameter into variable e
                                 // IE initialize the  event  object
        var key = ev.charCode ? ev.charCode : ev.keyCode; // IE hasn't charCode 
  
        //check for key pressed
        if ( ((key > 47) && (key < 58)) ||   // from '0' to '9'
             (key == 8)   ||                 // backspace
             (key == 9)   ||                 // canc
             (key == 43)  ||                 // +
             (key == 44)  ||                 // ,
             (key == 45)  ||                 // -
             (key == 46)                     //.
           ) 
        { 
          //Nothing to do... write passed char
        }
        else 
        {
          //When an unaccepted character has been pressed , we must avoid  event handling
          if (ev.preventDefault) 
          { 
            e.preventDefault(); // Gecko use preventDefault  to avoid event handling
          } 
          else if ('returnValue' in ev ) 
          { 
            ev.returnValue = false; // IE use returnValue  to avoid event handling
          }
        }
      }
      
      function limitDate(e) 
      {
        var ev  = e ? e : event; // Gecko  receive the event as parameter into variable e
                                 // IE initialize the  event  object
        var key = ev.charCode ? ev.charCode : ev.keyCode; // IE hasn't charCode 
  
        //check for key pressed
        if ( ((key > 47) && (key < 58)) ||   // from '0' to '9'
             (key == 8)   ||                 // backspace
             (key == 9)   ||                 // canc
             (key == 45)  ||                 // -
             (key == 47)                     // /
           ) 
        { 
          //Nothing to do... write passed char
        }
        else 
        {
          //When an unaccepted character has been pressed , we must avoid  event handling
          if (ev.preventDefault) 
          { 
            e.preventDefault(); // Gecko use preventDefault  to avoid event handling
          } 
          else if ('returnValue' in ev ) 
          { 
            ev.returnValue = false; // IE use returnValue  to avoid event handling
          }
        }
      }
      
      function limitCredential(e) 
      {
        var ev  = e ? e : event; // Gecko  receive the event as parameter into variable e
                                 // IE initialize the  event  object
        var key = ev.charCode ? ev.charCode : ev.keyCode; // IE hasn't charCode 
  
        //check for key pressed
        if ( ((key > 47) && (key < 58)) ||   // from '0' to '9'
             (key == 8)   ||                 // backspace
             (key == 9)   ||                 // canc
             (key == 33)  ||                 // !
             (key == 35)  ||                 // #
             (key == 39)  ||                 // '
             (key == 40)  ||                 // (
             (key == 41)  ||                 // )
             (key == 42)  ||                 // *
             (key == 43)  ||                 // +
             (key == 44)  ||                 // ,
             (key == 45)  ||                 // -
             (key == 46)  ||                 // .
             (key == 47)  ||                 // /
             (key == 58)  ||                 // :
             (key == 59)  ||                 // ;
             (key == 60)  ||                 // <
             (key == 61)  ||                 // =
             (key == 62)  ||                 // >
             (key == 63)  ||                 // ?
             (key == 64)  ||                 // @
             (key == 92)  ||                 // \
             (key == 95)  ||                 // _
             ((key > 64) && (key < 91)) ||   // from 'A' to 'Z'
             ((key > 96) && (key < 123))     // from 'a' to 'z'
           ) 
        { 
          //Nothing to do... write passed char
        }
        else 
        {
          //When an unaccepted character has been pressed , we must avoid  event handling
          if (ev.preventDefault) 
          { 
            e.preventDefault(); // Gecko use preventDefault  to avoid event handling
          } 
          else if ('returnValue' in ev ) 
          { 
            ev.returnValue = false; // IE use returnValue  to avoid event handling
          }
        }
      }
      /* End form fields limitation input functions  */
      
      
      /* ------------------------------------------------------------------------------ */
      /* Here start a set of functions to perform form data validation  */
      /* ------------------------------------------------------------------------------ */
      // Set of defined regular expressions to check field value
      var isempty    = /^.{0}$/;
      var isnotempty = /^.{1,}/;
      var ismail     = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
      var istext     = /^[a-zA-Z]+$/;
      var isnumeric  = /^\d+$/;
      var isdate     = 'isdate';  //We use a custom function to check inserted data format;
      
      //Set variables to compose header and footer for error messages
      var errHead    = 'Attenzione : \n\n';
      var errFoot    = '\n';

      function validation(formObject)
      {
        //declare variable where to store validation result
        var valReturn = false;
        
        //cycle across passed form object
        for (var i = 0; i < formObject.elements.length; i++)
        {
          //save current cycled element
          var currElem = formObject.elements[i];
          
          //check for which  kind of element it is
            /*All Text fields kind except hidden type*/
          if ((currElem.type == 'text')     || 
              (currElem.type == 'password') || 
              (currElem.type == 'textarea') || 
              (currElem.type == 'file')) 
          {
            //check for 'mandatory' clause or filled field
            if ((currElem.mandatory == 'yes') || (currElem.value != ''))
            {  
              //check for a not empty value inserted
              valReturn = execCheck(isnotempty, currElem.value);
              //check test result
              if (!valReturn)
              {
                //check for a custom error message inserted when field is mandatory
                if (currElem.message) { alert(errHead + currElem.message + errFoot) }
                else                  { alert(errHead + 'Il campo ' + currElem.name + ' e\' obbligatorio.' + errFoot) }
                //return validation result
                return (valReturn);
              }
              else
              {
                //check for a test to do over current field value when mandatory field is not empty
                if ((currElem.check) && (currElem.check != '') && (currElem.check != 'none')) 
                {
                  //perform required test
                  valReturn = execCheck(currElem.check, currElem.value);
                  if (!valReturn)
                  {
                    //check for a custom error message inserted when field value must do a test
                    if (currElem.checkmessage) { alert(errHead + currElem.checkmessage + errFoot) }
                    else                       { alert(errHead + 'Il campo ' + currElem.name + ' non ha superato il controllo di validazione previsto.'  + errFoot) }
                    //return validation result
                    return (valReturn);
                  }
                }
                else //field value is valid
                { valReturn = true;}
              }
            }
            else
            {  
              //check for a test to do over current field value
              if ((currElem.value != '') && (currElem.check != 'none')) 
              {
                //perform required chek over field value
                valReturn = execCheck(currElem.check, currElem.value);
                if (!valReturn)
                {
                  //check for a custom error message inserted when field value must do a test
                  if (currElem.checkmessage) { alert(errHead + currElem.checkmessage + errFoot) }
                  else                       { alert(errHead + 'Il campo ' + currElem.name + ' non ha superato il controllo di validazione previsto.'  + errFoot) }
                  //return validation result
                  return (valReturn);
                }
              }
              else //field value is valid
              { valReturn = true; }
            }
          }
            /*picklists or values list*/
          if (currElem.type == 'select-one')
          {
            //check for mandatory selection list 
            if (currElem.mandatory == 'yes') 
            {
              //set variable to check no item selected
              var noSelection = -1;
              //check for a combo or a list to set no selection index well
              if (currElem.size == 1) { noSelection = 0; }
              //perform selection test
              if (currElem.selectedIndex == noSelection)
              {
                //check for a custom error message inserted when no selection has been made for current list
                if (currElem.message) { alert(errHead + currElem.message + errFoot) }
                else                  { alert(errHead + 'E\' necessario selezionare un valore dalla lista ' + currElem.name + '.' + errFoot) }
                //test is invalid... return validation result
                return (false);
              }
              else //a value has been selected, so test is passed
              { valReturn = true;}
            }
            else //list is not mandatory
            { valReturn = true; }
          }
            /*radio button*/
          if (currElem.type == 'radio')
          {
            //check for mandatory choice
            if (currElem.mandatory == 'yes')
            {
              //declare variable used to check a radio options group
              var valChkGrpReturn = false;
              //inside cycle across all form object... redundancy
              for (var j = i; j < formObject.elements.length; j++)
              {
                var radioObj = formObject.elements[j];
                //Check for radio options of the same group
                if (radioObj.name == currElem.name)
                  //calculate total response for this radio option group
                  valChkGrpReturn = valChkGrpReturn || ((radioObj.checked == false) ? false : true);
              }
              //check radio group choice test
              if (!valChkGrpReturn) //(currElem.checked == false)
              {
                //check for a custom error message inserted when no selection has been made for current list
                if (currElem.message) { alert(errHead + currElem.message + errFoot) }
                else                  { alert(errHead + 'E\' necessario effettuare una scelta per il gruppo di opzioni ' + currElem.name + '.' + errFoot) }
                //test is invalid... return validation result
                return (false);
              }
              else //a choice has been made, so test is passed
              { valReturn = true;}
            }
            else //choice is not mandatory
            { valReturn = true; }
          }
        }
        
        //return validation result
        return (valReturn);
      }

      function execCheck(test2Do, fieldValue)
      {
        //declare variable where to store passed test to do
        var regExpr;
        //declare returning variable containing test result [True | False] 
        var retValue;
        //perform right check over passed field
        switch (test2Do)
	      {
		      case 'none' :
            //resolved in the case below
          case '' :
            //this case means we have nothing to to, so we return check validation return as true
            retValue = true;
            break;

          case 'isdate' :
            //for dates, we must call a custom function to validate
			      retValue = checkDate(fieldValue);
			      break;

          default :
            //assign passed test
            regExpr  = eval(test2Do);
            //verify field value
            retValue = regExpr.test(fieldValue);
        }
        
        //return test result
        return (retValue);
      }

      function checkDate(dtValue)
      {
        //save passed value
        var dtVal = dtValue;

        //check value length
        if (dtVal.length > 10) { return (false); }

        //Split data string into a structure
        var structData = dtVal.split("/");

        //Check number of elements in structure
        if (structData.length != 3) { return (false); }

        //Formatting days and months for values minor than 10
        if (structData[0].charAt(0) == "0" && structData[0].length == 2)
          { structData[0] = structData[0].charAt(1); }
        if (structData[1].charAt(0) == "0" && structData[1].length == 2)
          { structData[1] = structData[1].charAt(1); }

        //return numeric values from filled structure containing data
        dayVal = parseInt(structData[0]);
        monVal = parseInt(structData[1]);
        yeaVal = parseInt(structData[2]);

        //Check for numeric values into loaded variables
        if (isNaN(dayVal) || isNaN(monVal) || isNaN(yeaVal)) { return (false); }

        //Check about stored values
          //Day
          if (dayVal.toString().length != structData[0].length && structData[0].charAt(0) != "0") { return (false); }
          //Month
          if (monVal.toString().length != structData[1].length && structData[1].charAt(0) != "0") { return (false); }
          //Year
          if (yeaVal.toString().length != structData[2].length && structData[2].charAt(0) != "0") { return (false); }
          if (structData[2].length != 4)  { return (false); }
        //End check about stored values

        //Check for a valid month inserted
        if (monVal < 1 || monVal > 12) { return (false); }

        //Check for a leap year
        leapYear = false;
        if ((yeaVal / 4) == Math.floor(yeaVal / 4)) { leapYear = true; }

        //Check day range for Febrary in a leap year
        if (monVal == 2 && leapYear)
        {
          if (dayVal < 1 || dayVal > 29) { return (false); }
        }

        //Check day range for Febrary in a normal year
        if (monVal == 2 && (!(leapYear)))
        {
          if (dayVal < 1 || dayVal >28) { return (false); }
        }

        //Check day range for months with 31 days
        if (monVal == 1 || monVal == 3 || monVal == 5 || monVal == 7 || monVal == 8 || monVal == 10 || monVal == 12)
        {
          if (dayVal < 1 || dayVal > 31) { return (false); }
        }

        //Check day range for months with 31 days
        if (monVal == 4 || monVal == 6 || monVal == 9 || monVal == 11)
        {
          if (dayVal < 1 || dayVal > 30) { return (false); }
        }

        //Data check OK
        return (true);
      }
      /* End form data validation functions */