/*******************************************************************
*
* Filename: customScripts.js
* Created by: aneeson
* Date created: 07/02/2006
* Version: 1.0
*******************************************************************/

/********************************************************************
 * THIS FUNCTION IS USED TO INCLUDE OTHER JS FILES
 ********************************************************************/

//this function includes all necessary js files for the application   
function include(file)   
{   
  
  var script  = document.createElement('script');   
  script.src  = file;   
  script.type = 'text/javascript';   
  script.defer = true;   
  
  document.getElementsByTagName('head').item(0).appendChild(script);   
  
}

/* include any js files here */  
include("selectGroup.js");


/********************************************/
function updateURLFromLocalToShare(el1, el2){
    replaceDriveTo = 'file://guww.net/dfs.root.Global%20Shared%20Data$/';
    //try to replace i:\ to shared path
    var newStr = el2.value.replace(/(?:i:\\)/ig, replaceDriveTo);
    // if changes were made - apply another changes
    if(newStr != el2.value){
        el1.value = newStr.replace(/\\/g,"/").replace(/\s/g,"%20");
    }else{
        el1.value = el2.value;
    }
    if(el1.value.length > 254){
        alert("The URL you have chosen is longer than 254 characters. Please reduce your URL length.");
    }
}


/******************* NOTIFICATIONS **************************/
// On load split up body
// extracting values for from, reply to and body
// on submit put them back together.

var gEwebFirstname = '%user.firstname%';
var gEwebLastname = '%user.lastname%';
var gEwebRealname = '%user.realname%';
var gEwebUsername = "%right(user.username,user.username.length()-(user.username.indexOf('_')+1))%";
var gEwebURL = 'http://%find(68,rule.extrainfo.xinf_companygroupid).extrainfo.url%';
var gEwebPassword = '%user.extrainfo.xinf_pwd1%';
var gEwebEnrollments = '%options.templates.ListEnrollments.eval()%';

var gELTFirstname = '$FIRSTNAME$';
var gELTLastname  = '$LASTNAME$';
var gELTRealname  = '$FULLNAME$';
var gELTUsername  = '$USERNAME$';
var gELTPassword  = '$PASSWORD$';
var gELTURL       = '$LOGIN_URL$';
var gELTEnrollments = '$LIST_ENROLLMENTS$';


function splitUpBody()
  {
    //alert( "splitUpBody" );
    var bodyItem = document.getElementById( "body" );
    var subjItem = document.getElementById( "subj" );
    if ( !bodyItem )
      {
        alert( "couldn't find bodyItem" );
      }
    else
      {
        var bodyText = bodyItem.value;
        var replyTo = "";
        var from = "";
        var contentType = "text/plain";
        hstart = "<header name=\"From\">";
        hend = "<\/header>";
        p = bodyText.indexOf( hstart );
        if ( p != -1 )
          {
            p += hstart.length;
            from = bodyText.substring( p );
            p = from.indexOf( hend );
            from = from.substring( 0, p );
          }
        hstart = "<header name=\"Reply-To\">";
        hend = "<\/header>";
        p = bodyText.indexOf( hstart );
        if ( p != -1 )
          {
            p += hstart.length;
            replyTo = bodyText.substring( p );
            p = replyTo.indexOf( hend );
            replyTo = replyTo.substring( 0, p );
          }
        hstart = "<header name=\"Content-Type\">";
        hend = "<\/header>";
        p = bodyText.indexOf( hstart );
        if ( p != -1 )
          {
            p += hstart.length;
            contentType = bodyText.substring( p );
            p = contentType.indexOf( hend );
            contentType = contentType.substring( 0, p );
          }
        p = bodyText.indexOf( hend );
        while ( p > -1 )
          {
            bodyText = bodyText.substring( p + hend.length );
            p = bodyText.indexOf( hend );
          }

//        document.getElementById( "temp_replyTo" ).value = replyTo;
//        document.getElementById( "temp_from" ).value = from;

        document.getElementById( "temp_contentType" ).value = contentType;


  /* Replace $ variables with ewebscript equivalent values */
  var strText = bodyText;
  var strSubject = subjItem.value;

  var regFirstName = /%user\.firstname%/gi;
  var regLastName = /%user\.lastname%/gi;
  var regFullName = /%user\.realname%/gi;
  var regUserName = /%right\(user\.username,user\.username\.length\(\)-\(user\.username.indexOf\('_'\)\+1\)\)%/gi;
  var regUserNameOld = /%user\.username%/gi;
  var regPassword = /%user\.extrainfo\.xinf_pwd1%/gi;
  var regLoginURL = /http:\/\/%find\(68,rule\.extrainfo\.xinf_companygroupid\)\.extrainfo\.url%/gi;
  var regListEnrollments = /%options\.templates\.ListEnrollments\.eval\(\)%/gi;

  strReplacedText = strText.replace(regFirstName,gELTFirstname);
  strSubject = strSubject.replace(regFirstName,gELTFirstname);
  strReplacedText = strReplacedText.replace(regLastName,gELTLastname);
  strSubject = strSubject.replace(regLastName,gELTLastname);
  strReplacedText = strReplacedText.replace(regFullName,gELTRealname);
  strSubject = strSubject.replace(regFullName,gELTRealname);
  strReplacedText = strReplacedText.replace(regUserName,gELTUsername);
  strSubject = strSubject.replace(regUserName,gELTUsername);
  strReplacedText = strReplacedText.replace(regUserNameOld,gELTUsername);
  strSubject = strSubject.replace(regUserNameOld,gELTUsername);
  strReplacedText = strReplacedText.replace(regPassword,gELTPassword);
  strSubject = strSubject.replace(regPassword,gELTPassword);
  strReplacedText = strReplacedText.replace(regLoginURL,gELTURL);
  strSubject = strSubject.replace(regLoginURL,gELTURL);
  strReplacedText = strReplacedText.replace(regListEnrollments,gELTEnrollments);
  strSubject = strSubject.replace(regListEnrollments,gELTEnrollments);

  document.getElementById( 'temp_body' ).value = strReplacedText;
  document.getElementById( 'temp_subj' ).value = strSubject;
      }
  }

function joinUpBody()
  {


  /* Replace $ variables with ewebscript equivalent values */
  var strText = document.getElementById( 'temp_body' ).value;
  var strSubj = document.getElementById( 'temp_subj' ).value;
  var regFirstName = /\$FIRSTNAME\$/gi;
  var regLastName = /\$LASTNAME\$/gi;
  var regFullName = /\$FULLNAME\$/gi;
  var regUserName = /\$USERNAME\$/gi;
  var regPassword = /\$PASSWORD\$/gi;
  var regLoginURL = /\$LOGIN_URL\$/gi;
  var regListEnrollments = /\$LIST_ENROLLMENTS\$/gi;

  strReplacedText = strText.replace(regFirstName,gEwebFirstname);
  strSubj = strSubj.replace(regFirstName,gEwebFirstname);
  strReplacedText = strReplacedText.replace(regLastName,gEwebLastname);
  strSubj = strSubj.replace(regLastName,gEwebLastname);
  strReplacedText = strReplacedText.replace(regFullName,gEwebRealname);
  strSubj = strSubj.replace(regFullName,gEwebRealname);
  strReplacedText = strReplacedText.replace(regUserName,gEwebUsername);
  strSubj = strSubj.replace(regUserName,gEwebUsername);
  strReplacedText = strReplacedText.replace(regPassword,gEwebPassword);
  strSubj = strSubj.replace(regPassword,gEwebPassword);
  strReplacedText = strReplacedText.replace(regLoginURL,gEwebURL);
  strSubj = strSubj.replace(regLoginURL,gEwebURL);
  strReplacedText = strReplacedText.replace(regListEnrollments,gEwebEnrollments);
  strSubj = strSubj.replace(regListEnrollments,gEwebEnrollments);

 document.getElementById( 'subj' ).value = strSubj;



    /* Check that a from and replyto field have been specified
    if( document.getElementById( "temp_from" ).value.length == 0 )
    {
      alert( "You need to specify a From email address" );
      return false;
    }

    */

    /*

    Commented out due to TIQs request 370

    if( document.getElementById( "temp_replyTo" ).value.length == 0 )
    {
      alert( "You need to specify a Reply email address" );
      return false;
    }*/

    var bodyItem = document.getElementById( "body" );
    if ( !bodyItem )
      {
        alert( "couldn't find bodyItem" );
      }
    else
      {
        var theContentType = document.getElementById( "temp_contentType" );
        var theContentTypeValue = theContentType.options[theContentType.selectedIndex].value;


        document.getElementById( 'temp_body' ).value = strReplacedText;

/*        bodyText = "<header name=\"From\">" + document.getElementById( "temp_from" ).value + "<\/header>"
                 + "<header name=\"Reply-To\">" + document.getElementById( "temp_replyTo" ).value + "<\/header>"
                 //+ "<header name=\"Content-Type\">" + theContentTypeValue + "<\/header>"
                 + document.getElementById( "temp_body" ).value; */
        bodyText = document.getElementById( "temp_body" ).value;
        document.getElementById( "body" ).value = bodyText;
      }

  }

function setPlainText(aCurrentValue)
{
  var theContentType = document.getElementById( "temp_contentType" );

  if( aCurrentValue == 1 || aCurrentValue == -1)
  {
    document.getElementById( "ptxt" ).value = 1;
    theContentType.selectedIndex = 0;
  }
  else
  {
    document.getElementById( "ptxt" ).value = 0;
    theContentType.selectedIndex = 1;
  }

  return;
}

function selectPlainText()
{
  var theContentType = document.getElementById( "temp_contentType" );
  var theContentTypeValue = theContentType.options[theContentType.selectedIndex].value;

  if( theContentTypeValue == "text\/plain" )
  {
    document.getElementById( "ptxt" ).value = 1;
  }
  else
  {
    document.getElementById( "ptxt" ).value = 0;
  }

  return;
}

var subjHasFocus = false;
var bodyHasFocus = true;

function setSubjectFocus()
{
  //alert( "Subject has focus" );

  subjHasFocus = true;
  bodyHasFocus = false;

  return;
}

function setBodyFocus()
{
    //alert( "Body has focus" );

  subjHasFocus = false;
  bodyHasFocus = true;

  return;
}

function insertText( item, text )
  {
    var textBox = document.getElementById( 'temp_body' );

    if( subjHasFocus == true )
        textBox = document.getElementById( 'temp_subj' );

        if (window.getSelection)
          {
            textBox.value = textBox.value.substring(0, textBox.selectionStart) + text + textBox.value.substring(textBox.selectionEnd, textBox.value.length);
          }
        else if (document.getSelection)
          {
            textBox.value = textBox.value.substring(0, textBox.selectionStart) + text + textBox.value.substring(textBox.selectionEnd, textBox.value.length);
          }
        else if (document.selection)
          {
            textBox.focus();
            document.selection.createRange().text =  text;
          }
        else
          {
            alert("Not browser supported!");
            textBox.value = textBox.value + text;
          }

          return;
  }

    var rxName = '.+';
    var rxEmail = '^[a-zA-Z0-9\.\_\-]+\@[a-zA-Z0-9\.\_\-]+';
    var rxNumbers = '^[\\d]+$';

    function setInvalid(el){
        if(el){
            el.style.background = '#fcc';
        }
    }
    function setValid(el){
        if(el){
            el.style.background = '#ff9';
        }
    }

    function validateFocus(el, msg){
        if(( el )&&( msg == el.value)){
            el.value = '';
        }
    }

    function validate(el, regVal, msg){
        if(el){
            var re = new RegExp(regVal);
            var elVal = trim(el.value);
            if((elVal.match(re))&&(elVal != msg)){
                setValid(el);
                return true;
            }else{
                setInvalid(el);
                if('' == elVal ){
                    el.value = msg;
                }
                return false;
            }
        }else{
            return true;
        }
    }

    function checkOther(el,elID,focusID){
        if('other' == el.value){
            document.getElementById(elID).style.visibility = "visible";
            var foc = document.getElementById(focusID);
            if(foc){
                foc.focus();
            }
        }else{
            document.getElementById(elID).style.visibility = "hidden";
        }
    }

    function checkEmail(email, msg){
        email.value = email.value.replace(/\'/g,"-");
        if(validate(email, rxEmail, msg)){
            return true;
        }else{
            return false;
        }
    }

    function trim(stringToTrim) {
        return stringToTrim.replace(/^\s+|\s+$/g,"");
    }
    function ltrim(stringToTrim) {
        return stringToTrim.replace(/^\s+/,"");
    }
    function rtrim(stringToTrim) {
        return stringToTrim.replace(/\s+$/,"");
    }

    function isArray(obj) {
       if (obj.constructor.toString().indexOf("Array") == -1)
          return false;
       else
          return true;
    }

    function copySelect(copyFrom, copyTo, selected){
        if(!copyFrom || !copyTo || !copyFrom.options || !copyTo.options){
            return;
        }
        var selectedValue = null;
        if(selected){
            selectedValue = trim(selected.toLowerCase());
        }
        var maxCount = copyFrom.options.length;
        for(i=0;i<maxCount;i++){
            copyTo[i] = new Option(copyFrom.options[i].text, copyFrom.options[i].value);
            if(selectedValue && (selectedValue == copyFrom.options[i].value.toLowerCase() || selectedValue == copyFrom.options[i].text.toLowerCase())){
                copyTo.options[i].selected = true;
            }
        }
    }

      // Deesy: compare string function, convert into string, lower it, trim it and then compare
      function strCompare(str1, str2){
          var result = false;
          //Deesy: convert to string!!! otherwise rased error on numbers 
          var cStr1 = "" + str1;
          var cStr2 = "" + str2;
          try{
              result = (trim(cStr1.toLowerCase()) == trim(cStr2.toLowerCase()));
          }catch(err){
              if(!errorshown){
                  alert("Error " + err.description + " on *" + cStr1 + "* and *" + cStr2 + "*");
                  errorshown = true;
              }
          }
          return result;
      }  

      //Deesy: find element id in array with format [[id,name,code],[id,name,code],..]
      // and return id                                 
      function findId(arr, strToFind, fastArr){
          var result = -1;
          var smallArr;
          var str2F = trim("" + strToFind).toLowerCase();
          //check on fast array (ids only)
          if(fastArr && fastArr.length >0){ 
              result = fastArr.indexOf(strToFind);
              if(-1 != result && arr[result][0] == strToFind){
                  return result;
              }
          }
          if(arr && arr.length >0){
              for(i=0;i<arr.length;i++){
                  smallArr = arr[i];
                  if(smallArr && smallArr.length == 3){
                      //if id, or name or code match - stop it!
                      if(strCompare(smallArr[0], str2F) || strCompare(smallArr[1], str2F) || strCompare(smallArr[2], str2F)){
                          result = i;
                          break;
                      }
                  }
              }
          }
          return result;
      }       
