/**
 *  Copyright 2005 by Gero Kohnert
 *
 *  This program is free software; you can redistribute it and/or modify it 
 *  under the terms of the GNU General Public License as published by the   
 *  Free Software Foundation; version 2 of the License.                     
 *
 * Collection of Javascript functions used all over TUTOS
 */

 function fld_clear(id) {
   var el = document.getElementById(id);
   el.value = '';
 }


 /**
  * Checkall in actionforms
  */
 function CheckAll2() {
   for (var i=0; i < document.forms['actionform'].elements.length; i++) {
     var e = document.forms['actionform'].elements[i];
     if (e.name != 'checkit')
       e.checked = document.forms['actionform'].checkit.checked;
   }
 }

 /**
  * set badfield (missing or bad input in forms
  */
 function setBadField(fld) {
   document.getElementById(fld).className = "note";
 }


/**
 * some AJAX stuff
 */
 function load_TUTOS_List(base,name,fld,grp) {
   if (fld != "") {
    // Obtain an XMLHttpRequest instance
    var req = newXMLHttpRequest();

    // Set the handler function to receive callback notifications
    // from the request object
    var handlerFunction = getReadyStateHandler(name,req, updateInput);
    req.onreadystatechange = handlerFunction;
  
    // Open an HTTP POST connection to the TUTOS server.
    // Third parameter specifies request is asynchronous.
    req.open("POST", base + "/php/ajax.php", true);

    // Specify that the body of the request contains form data
    req.setRequestHeader("Content-Type", 
                       "application/x-www-form-urlencoded");

    // Send form encoded data stating that I want to add the 
    // specified item to the cart.
    req.send("action=search&item="+fld+"&grp="+grp);
   }
 }


/**
 *
 */
 function updateInput(name,TUTOSxml) {


   var base64 = new Base64;
   var all = TUTOSxml.getElementsByTagName("tutos")[0];

   base64.Base64("");
   document.getElementById(name+"-popup").innerHTML = name +"..."+ all + "..."; 

   // Check that a more recent document hasn't been processed
   // already
   var generated = all.getAttribute("generated");
   if (true) {
     lastUpdate = generated;

     // Clear the HTML list used to display the cart contents
     var contents = document.getElementById(name+"-popup");
     contents.innerHTML = "";

     // Loop over the result items in the xml
     var items = all.getElementsByTagName("result");
     for (var I = 0 ; I < items.length ; I++) {

       var item = items[I];

       // Extract the text nodes from the name and quantity elements
       var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
                                               
       // Create and add a list item HTML element for this cart item
       var li = document.createElement("li");
       base64.string = name;
       li.appendChild(document.createTextNode(base64.decode()));
       contents.appendChild(li);
     }
   }


 }

/*
 * Returns a new XMLHttpRequest object, or false if this browser
 * doesn't support it
 * from http://www-128.ibm.com/developerworks/library/j-ajax1/
 */
 function newXMLHttpRequest() {
 
   var xmlreq = false;

   if (window.XMLHttpRequest) {
     // Create XMLHttpRequest object in non-Microsoft browsers
     xmlreq = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
     // Create XMLHttpRequest via MS ActiveX
     try {
       // Try to create XMLHttpRequest in later versions
       // of Internet Explorer
       xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e1) {
       // Failed to create required ActiveXObject
       try {
        // Try version supported by older versions
        // of Internet Explorer
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

       } catch (e2) {

        // Unable to create an XMLHttpRequest with ActiveX
       }
     }
   }

   return xmlreq;
 }


/*
 * Returns a function that waits for the specified XMLHttpRequest
 * to complete, then passes its XML response
 * to the given handler function.
 * req - The XMLHttpRequest whose state is changing
 * responseXmlHandler - Function to pass the XML response to
 */
 function getReadyStateHandler(name,req, responseXmlHandler) {

   // Return an anonymous function that listens to the 
   // XMLHttpRequest instance
   return function () {

     // If the request's status is "complete"
     if (req.readyState == 4) {
       
       // Check that a successful server response was received
       if (req.status == 200) {

         // Pass the XML payload of the response to the 
         // handler function
         responseXmlHandler(name,req.responseXML);
 
       } else {
 
         // An HTTP problem has occurred
         alert("HTTP error: "+req.status);
       }
     }
   }
 }


function Base64()
{
    var string;
    var base64;

    this.Base64 = function(string)
    {
        this.string = new String(string);
        this.base64 = new Array('A','B','C','D','E','F','G','H',
                                'I','J','K','L','M','N','O','P',
                                'Q','R','S','T','U','V','W','X',
                                'Y','Z','a','b','c','d','e','f',
                                'g','h','i','j','k','l','m','n',
                                'o','p','q','r','s','t','u','v',
                                'w','x','y','z','0','1','2','3',
                                '4','5','6','7','8','9','*','/');
    }
    
    this.encode = function()
    {
        var binary = new String();
        var result = new String();
        for(i = 0; i < this.string.length; i++)
        {
            binary += String("00000000" + this.string.charCodeAt(i).toString(2)).substring(this.string.charCodeAt(i).toString(2).length);
        }
        for(i = 0; i < binary.length; i+=6)
        {
            var number = new Number();
            var counter = new Number();
            for(j = 0; j < binary.substring(i, i+6).length; j++)
            {
                for(k = 32; k >= 1; k-=(k/2))
                {
                    if(binary.substring(i, i+6).charAt(counter++) == "1")
                    {
                        number += k;
                    }
                }
            }
            result += this.base64[number];
        }
        return result;
    }

    this.decode = function()
    {
        var binary = new String();
        var result = new String();
        for(i = 0; i < this.string.length; i++)
        {
            for(j = 0; j < this.base64.length; j++)
            {
                if(this.string.charAt(i) == this.base64[j])
                {
                    binary += String("000000" + j.toString(2)).substring(j.toString(2).length);
                }
            }
        }
        for(i = 0; i < binary.length; i+=8)
        {
            var number = new Number();
            var counter = new Number();
            for(j = 0; j < binary.substring(i, i+8).length; j++)
            {
                for(k = 128; k >= 1; k-=(k/2))
                {
                    if(binary.substring(i, i+8).charAt(counter++) == "1")
                    {
                        number += k;
                    }
                }
            }
            result += String.fromCharCode(number);
        }
        return result;
    }
}

function openWindow(ourl,oname,owidth,oheight) {
	window.open(ourl,oname,'toolbar=no,menubar=no,location=no,personalbar=no,scrollbars=no,directories=no,status=no,resizable=no,fullscreen=no,width='+owidth+',height='+oheight);
}
