/**
 *  Copyright 2005 - 2009 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 menu_active(flag,id) {
   if (flag == 1) {
    id.className = "menu_active";
   } else {
    id.className = "nl_menu_row";
   }
   var items = id.getElementsByTagName( "a" );
   for (var i = 0; i < items.length; i++) {
     if (flag == 1) {
       items[i].className = "menu_text_active";
     } else {
       items[i].className = "nodeco";
     }
   }
 }

 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";
 }


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

        // private property
        _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

        // public method for encoding
        encode : function (input) {
                var output = "";
                var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                var i = 0;

                input = Base64._utf8_encode(input);

                while (i < input.length) {

                        chr1 = input.charCodeAt(i++);
                        chr2 = input.charCodeAt(i++);
                        chr3 = input.charCodeAt(i++);

                        enc1 = chr1 >> 2;
                        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                        enc4 = chr3 & 63;

                        if (isNaN(chr2)) {
                                enc3 = enc4 = 64;
                        } else if (isNaN(chr3)) {
                                enc4 = 64;
                        }

                        output = output +
                        this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                        this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

                }

                return output;
        },

        // public method for decoding
        decode : function (input) {
                var output = "";
                var chr1, chr2, chr3;
                var enc1, enc2, enc3, enc4;
                var i = 0;

                input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

                while (i < input.length) {

                        enc1 = this._keyStr.indexOf(input.charAt(i++));
                        enc2 = this._keyStr.indexOf(input.charAt(i++));
                        enc3 = this._keyStr.indexOf(input.charAt(i++));
                        enc4 = this._keyStr.indexOf(input.charAt(i++));

                        chr1 = (enc1 << 2) | (enc2 >> 4);
                        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                        chr3 = ((enc3 & 3) << 6) | enc4;

                        output = output + String.fromCharCode(chr1);

                        if (enc3 != 64) {
                                output = output + String.fromCharCode(chr2);
                        }
                        if (enc4 != 64) {
                                output = output + String.fromCharCode(chr3);
                        }

                }

                output = Base64._utf8_decode(output);

                return output;

        },

        // private method for UTF-8 encoding
        _utf8_encode : function (string) {
                string = string.replace(/\r\n/g,"\n");
                var utftext = "";

                for (var n = 0; n < string.length; n++) {

                        var c = string.charCodeAt(n);

                        if (c < 128) {
                                utftext += String.fromCharCode(c);
                        }
                        else if((c > 127) && (c < 2048)) {
                                utftext += String.fromCharCode((c >> 6) | 192);
                                utftext += String.fromCharCode((c & 63) | 128);
                        }
                        else {
                                utftext += String.fromCharCode((c >> 12) | 224);
                                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                                utftext += String.fromCharCode((c & 63) | 128);
                        }

                }

                return utftext;
        },

        // private method for UTF-8 decoding
        _utf8_decode : function (utftext) {
                var string = "";
                var i = 0;
                var c = c1 = c2 = 0;

                while ( i < utftext.length ) {

                        c = utftext.charCodeAt(i);

                        if (c < 128) {
                                string += String.fromCharCode(c);
                                i++;
                        }
                        else if((c > 191) && (c < 224)) {
                                c2 = utftext.charCodeAt(i+1);
                                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                                i += 2;
                        }
                        else {
                                c2 = utftext.charCodeAt(i+1);
                                c3 = utftext.charCodeAt(i+2);
                                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                                i += 3;
                        }

                }

                return string;
        }

}



/**
 * some AJAX stuff
 */
 function load_TUTOS_dir_list(base,name,filter) {
  // Obtain an XMLHttpRequest instance
  var req = newXMLHttpRequest();

  // Set the handler function to receive callback notifications
  // from the request object
  var handlerFunction = getReadyStateHandler(name,req, updateDirInput);
  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 display list.
  req.send("action=search&grp=f&filter="+filter);
 }
/**
 * some AJAX stuff
 */
function load_TUTOS_List(base,name,fld,grp,objid) {
   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 display list.
    req.send("action=search&item="+fld+"&grp="+grp+"&id="+objid);
   }
 }


/**
 * use the ajax results for a file selection list
 */
 function updateDirInput(name,TUTOSxml) {
   var all = TUTOSxml.getElementsByTagName("tutos")[0];


   // 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 list items
     var contents = document.getElementById(name);
     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 s = item.getElementsByTagName("size")[0].firstChild.nodeValue;
       var n = item.getElementsByTagName("name")[0].firstChild.nodeValue;
       

       // Create and add a list item HTML element for this item
       var op = document.createElement("option");

       if (Base64.decode(n) == "-") {
         op.setAttribute("value","");
         fn = document.createTextNode("");
       } else {                                               
         op.setAttribute("value",Base64.decode(n));
         var kb = s/(1024);
         fn = document.createTextNode(Base64.decode(n) + " ("+ kb.toFixed(2) +" KB) " );
       }
       op.appendChild(fn);
       contents.appendChild(op);
     }
   }
 }
/**
 * use the ajax results for selection lists
 */
 function updateInput(name,TUTOSxml) {

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


   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 list 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 t = item.getElementsByTagName("type")[0].firstChild.nodeValue;
       var n = item.getElementsByTagName("name")[0].firstChild.nodeValue;
                                               
       // Create and add a list item HTML element for this list item
       var li = document.createElement("li");
       // li.appendChild(document.createTextNode(b1.decode()));
       li = document.createTextNode(Base64.decode(t) + " ");
       contents.appendChild(li);

       li = document.createElement("a");
       td = Base64.decode(n);
//       li.setAttribute("onclick", "document.getElementById('"+ name +"').value = '" + td +"';");
       li.setAttribute("onclick","setInputField('"+name+"','" + td +"');");
       li.appendChild(document.createTextNode( td ));
       contents.appendChild(li);

       li = document.createElement("br");
       contents.appendChild(li);
     }
   }
 }

 function setInputField(field,val) {
    var f = document.getElementById(field);
    f.value = val;;
 } 
/*
 * 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 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);
}