/* ===============================================
 * AUTHOR:      Sebastian Junghanns, Grintec GmbH
 * DATE:        2004-04-30
 * DESCR:       this file contains a collection
 *              of handy helper functions.
 * ===============================================
 */

// == WINDOW HANDLING ============================

// -- function to open a new window in a restricted way
function GtSwlOpenWindow(theURL,winName,features) {
    window.open(theURL,winName,features);
}

// -- function to dynamically assign a new document title
function GtSwlSetDocTitle (newTitle) {
    document.title = newTitle;
}



// === FORM HANDLING ==============================

// -- function to set focus to a particular form element
function GtSwlSetFocus(frm, focusItem) {
                
    document.forms[frm].elements[focusItem].focus();
}
        
// -- function to use enter/return for form submission
function GtSwlCheckEnter(event,frm)
{   //alert('checkEnter' + frm);
    var NS4 = (document.layers) ? true : false;
    var code = 0;
    if (NS4){
        code = event.which;
    }else{
        code = event.keyCode;
    }
    if (code==13){ 
    //alert('hit enter');
    document.forms[frm].submit() };
}


// -- function to check whether a form field is empty
// -- Note, there are two possibile types of 'emptiness',
// -- a form can return - a zero length string, or a null value.
// -- Both option are checked in this function.
function GtSwlIsEmpty(aTextField) {
   
   if ( (aTextField.value.length==0) || (aTextField.value==null) ) { return true;
   } else { return false; }
}	


// -- function to retrieve the innerHTML string from a currently selected 
// -- option of a drop down list (== select)

function GtSwlGetCurrentOptionInnerHTML(selList){
        
    var i = 0;
    var optionStr = "";
        
    with (selList){
          
        for (i = 0; i < length; i++){
                    
            if (options[i].selected){
                        
                optionStr = options[i].innerHTML;
                break;
            }
        }
    }   

    //alert(optionStr);
    return optionStr;
} 


// == STRING VALIDATION ===========================

// -- function to validate a string for conformity with an email address string
// --
// -- Coding is courtesy of Sandeep V. Tamhankar (stamhankar@hotmail.com).
// -- This script and many more are available free online at
// -- The JavaScript Source!! http://javascript.internet.com
// -- Script slightly modified for the purpose of internationalisation.
// --
// -- NOTA BENE: YOU MUST INCLUDE ./scripts/gt_swl_messages.js INTO YOUR HTML FILE
// -- IN ORDER TO GET ERROR MESSAGES DISPLAYED CORRECTLY. ERROR MESSAGE STRINGS WERE
// -- EXTRACTED AS STRING CONSTANTS AND ARE HELD IN THE AFOREMENTIONED FILE.

function GtSwlEmailAddressIsFine (emailStr) {

            /* The following pattern is used to check if the entered e-mail address
               fits the user@domain format.  It also is used to separate the username
               from the domain. */
            var emailPat=/^(.+)@(.+)$/
            /* The following string represents the pattern for matching all special
               characters.  We don't want to allow special characters in the address. 
               These characters include ( ) < > @ , ; : \ " . [ ]    */
            var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
            /* The following string represents the range of characters allowed in a 
               username or domainname.  It really states which chars aren't allowed. */
            var validChars="\[^\\s" + specialChars + "\]"
            /* The following pattern applies if the "user" is a quoted string (in
               which case, there are no rules about which characters are allowed
               and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
               is a legal e-mail address. */
            var quotedUser="(\"[^\"]*\")"
            /* The following pattern applies for domains that are IP addresses,
               rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
               e-mail address. NOTE: The square brackets are required. */
            var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
            /* The following string represents an atom (basically a series of
               non-special characters.) */
            var atom=validChars + '+'
            /* The following string represents one word in the typical username.
               For example, in john.doe@somewhere.com, john and doe are words.
               Basically, a word is either an atom or quoted string. */
            var word="(" + atom + "|" + quotedUser + ")"
            // The following pattern describes the structure of the user
            var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
            /* The following pattern describes the structure of a normal symbolic
               domain, as opposed to ipDomainPat, shown above. */
            var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
            
            
            /* Finally, let's start trying to figure out if the supplied address is
               valid. */
            
            /* Begin with the coarse pattern to simply break up user@domain into
               different pieces that are easy to analyze. */
            var matchArray=emailStr.match(emailPat)
            if (matchArray==null) {
              /* Too many/few @'s or something; basically, this address doesn't
                 even fit the general mould of a valid e-mail address. */
                    // --  GT-JUS(SWL): alert("Email address seems incorrect (check @ and .'s)")
                    alert(GT_SWL_REG_EMAIL_ADDR_SEEMS_INCORRECT)
                    return false
            }
            var user=matchArray[1]
            var domain=matchArray[2]
            
            // See if "user" is valid 
            if (user.match(userPat)==null) {
                // user is not valid
                // GT-JUS(SWL): alert("The username doesn't seem to be valid.")
                alert(GT_SWL_REG_EMAIL_USER_NAME_SEEMS_INVALID);
                return false
            }
            
            /* if the e-mail address is at an IP address (as opposed to a symbolic
               host name) make sure the IP address is valid. */
            var IPArray=domain.match(ipDomainPat)
            if (IPArray!=null) {
                // this is an IP address
                      for (var i=1;i<=4;i++) {
                        if (IPArray[i]>255) {
                            // GT-JUS(SWL): alert("Destination IP address is invalid!")
                            alert(GT_SWL_REG_EMAIL_DEST_IP_INVALID);
                            return false
                        }
                }
                return true
            }
            
            // Domain is symbolic name
            var domainArray=domain.match(domainPat)
            if (domainArray==null) {
                    // GT-JUS(SWL): alert("The domain name doesn't seem to be valid.")
                    alert(GT_SWL_REG_EMAIL_DOMAIN_SEEMS_INVALID);
                return false
            }
            
            /* domain name seems valid, but now make sure that it ends in a
               three-letter word (like com, edu, gov) or a two-letter word,
               representing country (uk, nl), and that there's a hostname preceding 
               the domain or country. 
            GT-JUS(SWL): changed this to 2..4 chars to comply with new top level domains such as .info   
            */
            
            /* Now we need to break up the domain to get a count of how many atoms
               it consists of. */
            var atomPat=new RegExp(atom,"g")
            var domArr=domain.match(atomPat)
            var len=domArr.length
            if (domArr[domArr.length-1].length<2 || 
                domArr[domArr.length-1].length>4) {
               // the address must end in a two letter or three letter word.
               // GT-JUS(SWL): alert("The address must end in a three-letter domain, or two letter country.")
               alert(GT_SWL_REG_EMAIL_TOP_LEVEL_DOMAIN_INVALID);
               return false
            }
            
            // Make sure there's a host name preceding the domain.
            if (len<2) {
               // GT-JUS(SWL): var errStr="This address is missing a hostname!"
               var errStr = GT_SWL_REG_EMAIL_HOST_NAME_MISSING;
               alert(errStr)
               return false
            }
            
            // If we've gotten this far, everything's valid!
            return true;
}


// -- function to check whether a passed string 
// -- only contains characters that are provided
// -- in a reference string. 

function GtSwlValueIsFine (string, validChars) {

    var aChar;
    var isFine = true;

    // -- empty string ?
    if (string.length == 0) { 
    
        isFine = false;
        
    } else {
      
        // -- test that string consists of valid characters listed above
        for (i = 0; i < string.length && isFine; i++)
        {
            aChar = string.charAt(i);
            if (validChars.indexOf(aChar) == -1) { isFine = false; }
        }
    }
    
    return isFine;
}

// == DATE / TIME STRING GENERATION ===========================


// -- function to ensure that the browser dependent output from today.getYear()
// -- delivers a 4 digit year value
// --
// -- PARAMS: none

function GtSwlGetYearFullLength(){

    var year = ""
    var today = new Date();
    var yearRaw = today.getYear();
    
    if (navigator.product == "Gecko"){ 
                        
        year = (parseInt(yearRaw) + 1900).toString()
                        
    } else { year = yearRaw; }

    return year;
}


// -- functions returns timestamps in different formats
// --
// -- PARAMS:   dataStyle       string  -> "dateShort"  		produces a date/time string like     	"Thu May 27 2004"
// --                                   -> "dateTime"           		-- " --                 		"Donnerstag, 27. Mai 2004 13:23:22" (local settings)
// --                                   -> "date"               		-- " --                 		"Donnerstag, 27. Mai 2004" (local settings)
// --                                   -> "time"               		-- " --                 		"13:23:22" (local settings)
// --                                   -> "dateTimeNumeric"    		-- " --                 		"20040527132322" (YYYYMMDDHHMMSS)

function GtSwlGetDateTime(dateStyle)
{

    var aDateStyle = new Array();
    aDateStyle["dateShort"]                     = 1;
    aDateStyle["date"]                          = 2;
    aDateStyle["dateTime"]                      = 3;
    aDateStyle["time"]                          = 4;
    aDateStyle["dateTimeNumeric"]               = 5;
    aDateStyle["dateShortGermanNotation"]       = 6;
    aDateStyle["dateTimeShortGermanNotation"]	= 7;

    var today = new Date();
    var dStr = "";
	
    switch (aDateStyle[dateStyle])
    {
        case 1:
			dStr = today.toDateString();
			break;
        case 2:
                        dStr = today.toLocaleDateString();
                        break;
        case 3:
			dStr = today.toLocaleString();
			break;
        case 4:
			dStr = today.toLocaleTimeString();
			break;
        case 5:
                        var year        = GtSwlGetYearFullLength();                        
                        var month       = today.getMonth() + 1;
                        var day         = today.getDate();
                        var hours       = today.getHours();
                        var mins        = today.getMinutes();
                        var secs        = today.getSeconds();
                        
                        dStr += year;
                        dStr += (month < 10) ? ('0' + month) : month;
                        dStr += (day < 10) ? ('0' + day) : day;
                        dStr += (hours < 10) ? ('0' + hours) : hours;
                        dStr += (mins < 10) ? ('0' + mins) : mins;
                        dStr += (secs < 10) ? ('0' + secs) : secs;
                        break;
        case 6:
                        var year        = GtSwlGetYearFullLength();
                        var month       = today.getMonth() + 1;
                        var day         = today.getDate();
                        
                        dStr = day + '.' + month + '.' + year;
                        break;
        case 7:
                        var year        = GtSwlGetYearFullLength();
                        var month       = today.getMonth() + 1;
                        var day         = today.getDate();
                        var hours       = today.getHours();
                        var mins        = today.getMinutes();
                        var secs        = today.getSeconds();

                        dStr = day + '.' + month + '.' + year;
                        dStr += " ";
                        dStr += (hours < 10) ? ('0' + hours) : hours;
                        dStr += ":";
                        dStr += (mins < 10) ? ('0' + mins) : mins;
                        dStr += ":";
                        dStr += (secs < 10) ? ('0' + secs) : secs;
                        break;
        default:
			break;
    }
    
    // -- debug
    //alert(dStr);
    return dStr;
}



// ==== STRING PROCESSING ==========================================================

// ==== Encoding of strings for incorporation in XML structures (complex parameters)
// ==== PAC 5.6.2004
function GtSwlEncodeXML(textString, useCDATA) {
	
	var changed = false;
	var sText = textString;
	
	if (sText == undefined) 
      sText = "";
	
	if (sText.indexOf("&") != -1) {
		sText = GtSwlStringReplace(sText, "&", "&amp;");
		changed = true;
	}
      
	if (sText.indexOf("<") != -1) {
		sText = GtSwlStringReplace(sText, "<", "&lt;");
		changed = true;
	}

	if (sText.indexOf(">") != -1) {
		sText = GtSwlStringReplace(sText, ">", "&gt;");
		changed = true;
	}

	if (sText.indexOf(",") != -1){
		sText = GtSwlStringReplace(sText, ",", ";");
		changed = true;
	}
	
	if (changed && useCDATA)
		sText = "<![CDATA[" + sText + "]]>";

	return sText;
}

// ==== Encoding of strings for incorporation in XML structures (complex parameters)
// ==== PAC 5.6.2004
function GtSwlStringReplace(originalString, findText, replaceText) {
   /* This function replaces all occurrences of a substring
      in the given string with the specfied value.
      
      Parameters:
         originalString: string - The string to modify.
         findText: string - The substring to replace.
         replaceText: string - The new value for the substring.
         
      Return: string - The escaped string.
   */

	var re = new RegExp(findText, "g");
	return originalString.replace(re, replaceText);
}


// -- function to remove leading white spaces
function GtSwlLeftTrim(argvalue) {

  while (1) {
    if (argvalue.substring(0, 1) != " ")
      break;
    argvalue = argvalue.substring(1, argvalue.length);
  }

  return argvalue;
}


// -- function to remove trailing white spaces
function GtSwlRightTrim(argvalue) {

  while (1) {
    if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
      break;
    argvalue = argvalue.substring(0, argvalue.length - 1);
  }

  return argvalue;
}


// -- function to trim both leading and trailing spaces
function GtSwlTrim(argvalue) {
  var tmpstr = GtSwlLeftTrim(argvalue);

  return GtSwlRightTrim(tmpstr);

}


// -- function to remove white spaces from a string
function GtSwlRemoveSpaces(string) {
	
    var cleanString = "";
    var inputString = string;
    var subStrings = new Array();
    
    subStrings = inputString.split(" ");
    
    var i;
    for(i = 0; i < subStrings.length; i++){
	cleanString += subStrings[i];
    }
    
    return cleanString;
}
