/* resize textarea depending on the data the user enters */
function resizeTextArea(txtBox){
 var   nCols = txtBox.cols;
 var    sVal = txtBox.value;
 var    nVal = sVal.length;
 var nRowCnt = 1;

 for (i=0;i<nVal;i++){ if (sVal.charAt(i).charCodeAt(0) == 13) { nRowCnt +=1; } }
 if (nRowCnt < (nVal / nCols)) { nRowCnt = 1 + (nVal / nCols); }
 txtBox.rows = nRowCnt+1;
}

/* used to mark a input element as changed if data has entered */
function markAsChanged(oE){
  $(oE).addClassName('changed');
}

/* acForm is the formname to be serialized or a array of form-variables 
 * to be serialized only.
 */
function AjaxUpdater(cUpdateArea,cUrl,acForm){
  var cParams;
  var n;
  var nLen;

  $('busy').show();
  if( typeof( acForm ) == 'string'){

   new Ajax.Updater({success: cUpdateArea},cUrl,
                    {method    :'get', 
                     parameters:Form.serialize(acForm),
                     onComplete: function(){ $('busy').hide(); }
                     });
  }else{
     cParams = '';
     nLen    = acForm.length;
     for( n=0; n<nLen; ++n ){
       /* the escape is needed as CRLF are not preserved from text areas by default */
       cParams = cParams + acForm[n] + '=' + escape( $F(acForm[n]) );
       if(n!=nLen) cParams = cParams + '&' ;
     }

     new Ajax.Updater({success: cUpdateArea},cUrl,
                      {method    : 'get', 
                       parameters: cParams,
                       onComplete: function(){ $('busy').hide(); }
                       });
   }

}

/*
 * Synchronous Ajax request for downloading a file.
 * "cUrlCheck" is the server script for checking
 * access rights. Only if this returns "Success"
 * (and no error information) does the download 
 * commence via "cUrlDownload". "cErrElement" 
 * defines a div to display the response supplied 
 * by the server in. "cOKElement" is a HTML 
 * element that is shown if the download is begun.
 * The can be used to display a (success) check
 * mark or the like.
 *
 * Notes: o This function can be used in dynamic 
 *          forms 
 *        o The script creates an IFrame named 
 *          "HiddenDLFrame" to reside on the page
 *          to initiate the actual download. Ajax 
 *          doesn't handle complex content-types 
 *          such as application/zip!
 */
function AjaxDownloadFile( cUrlCheck, cUrlDownload, cOKElement, cErrElement ) {

 var lRet = false;

  $(cErrElement).hide();

  new Ajax.Request(cUrlCheck, 
    {method:     'get', 
     asynchronous: false,
     onSuccess: function test(transport) {
      if( transport.status == 200 ) {
         if( transport.responseText.length > 8 ) {

            if( $(cErrElement).hasChildNodes() ){
                if( $(cErrElement).down() != null ) {
                   $(cErrElement).down().remove();
                }
            }

            $(cErrElement).show();

            new Insertion.Top(document.getElementById(cErrElement), '<div class="error"><p class="error">'+transport.responseText+'</p></div>' );
         }
         else {
            var ifrm;

            if( $(cOKElement) ) {
                $(cOKElement).show();
            }
            
            if( $("HiddenDLFrame") ) {
                $("HiddenDLFrame").remove();
            }

            ifrm = document.createElement("iframe");
            ifrm.id = "HiddenDLFrame";
            ifrm.style.display = "none";
            ifrm.src = cUrlDownload;
            document.body.appendChild(ifrm);

            lRet = true;
        }
     }
    }
   }); 

   return lRet;
}


function hov(loc,cls){
   if(loc.className)
      loc.className=cls;}

/* query the error section according to css classname */
function FindErrorSection(cElement){
  var oErr;

  oErr = $(cElement).up('.required');
  if(oErr != undefined ) return(oErr);

  oErr = $(cElement).up('.required error');
  if(oErr != undefined ) return(oErr);

  oErr = $(cElement).up('.optional');
  if(oErr != undefined ) return(oErr);

  oErr = $(cElement).up('.optional error');
  if(oErr != undefined ) return(oErr);

  return(undefined);
}

/* error is set by adding a error classname to the required div
 * and by insertion of a error p tag with the error message
 */
function AddErrorToValidationElement(cElement,cTxt){
  var oErr = FindErrorSection(cElement);
  if(oErr == undefined ){
    alert("#form does not conform to cxp form structure, error-section not found");
  }
  if(oErr.hasClassName('error')){
    oErr.down().remove();
  }else{
    oErr.addClassName('error');
  }
  new Insertion.Top(oErr, '<p class="error">'+cTxt+'</p>' );
}

/* error is removed by classname and added p tag at top of error div
 */
function RemoveErrorFromValidationElement(cElement){
  var oErr = FindErrorSection(cElement);
  if(oErr == undefined ){
    alert("#form does not conform to cxp form structure, error-section not found");
  }
  if(oErr.hasClassName('error')){
    oErr.down().remove();
    oErr.removeClassName('error');
  }
}

/*
 * dedicated client side validation helpers they get concatenated
 * by AND in the onblur event handler of a input element
 */

/* checks for field required constraint */
function ValidateRequired(cName){
  var cVal;

  cVal = $F(cName);
  if( cVal.empty() ){
    AddErrorToValidationElement(cName,"Field is required");
    return(false);
  }

  RemoveErrorFromValidationElement(cName);
  return(true);
}

/* checks for field length constraint */
function ValidateLength(cName,nMin){
  var cVal;

  cVal = $F(cName);
  if( cVal.length<nMin){
    AddErrorToValidationElement(cName,"Field length must be at least " + nMin + " characters." );
    return(false);
  }

  RemoveErrorFromValidationElement(cName);
  return(true);
}

/* the idea of this function is to verify of all errors from the
 * client side validation have been resolved. however as the remote
 * validation results and errors are posted back also we can not
 * distinguish betweem them so this function is remarked for now
 */
function ValidateFormRules(cName){
/*
  var aErrors = $(cName).getElementsByClassName('error');
  if(aErrors.length>0){
    alert("we still have form errors");
    return(false);
  }
 */
  return(true);
}

function __ApplyValidationResult(oResp,cEle){
  var cResult;
  if(oResp.status == 200 ){
    cResult = eval(oResp.responseText);
    if(cResult.length == 0){
      RemoveErrorFromValidationElement(cEle);
      return;
    }
    AddErrorToValidationElement(cEle,cResult);
    return;
  }

  AddErrorToValidationElement(cName,"Ajax error status-code:"+oResp.status+". This error is not serious as the forms gets validated on the server again" );
  return;
}

function ValidateByController( cName, cPath ){
  new Ajax.Request( cPath, { onSuccess: function(transport){ __ApplyValidationResult(transport,cName); } , method: 'get', parameters: $(cName).serialize() ,requestHeaders: ['Accept','bobi/json']}); 
  return;
}

