function searchAttributeRecursive(oNode, oAttributeKeys, oAttributeValues)
{
  /* 
     this is a helper function
     
     it iterates through a node structure until it finds a
     node where a number of attribute keys match a number of
     attribute values
     
     in order to explicitly test for an attribute not to be
     set, test for a match with null
     
     returns a node object in case of a match
     returns null in case of no match
     
     
     
     parameters
     ----------
     
     oNode - a document object model (DOM) node to be rummaged
     oAttributeKeys - an array of keys / attribute names (strings)
     oAttributeValues - an array of values (strings)
     
     
     
     return value
     ------------
     
     node object / null
     
     
     
     version history
     ---------------
     
     )x(  24.04.2008 - anpl - initial implementation
     
  */
     
  var bIsMatch = true; // it is a match unless proven otherwise
  var iFinalIteration = oAttributeKeys.length; // final iteration will be the number of keys
  
  if(oAttributeValues.length != iFinalIteration) // if the number of keys does not match the number of values
  {
    return(null); // search fails
  }
  else // otherwise
  {
    
    for(var i = 0; i < iFinalIteration; i++) // iterate through the attributes array
    {
      
      try
      {
        var oAttributeNode = oNode.getAttributeNode(oAttributeKeys[i]); // get the attribute with the specified key
      }
      catch(e) // in case there is no such attribute
      {
        var oAttributeNode = null; // test for a match with null
      }
      
      try
      {
        
        if(oAttributeNode.nodeValue != oAttributeValues[i]) // if the values don't match
        {
          bIsMatch = false; // no match
        }
        
      }
      catch(e) // in case the attribute node is null (attribute does not exist)
      {
        
        if(oAttributeValues[i] != null) // unless it is not EXPECTED to be null
        {
          bIsMatch = false; // no match
        }
        
      }
      
    }
    
    if(bIsMatch) // in case of a match
    {
      return(oNode); // return the node object
    }
    else if(oNode.hasChildNodes) // if no match, but the node has child nodes
    {
      
      for(var i = 0; i < oNode.childNodes.length; i++) // iterate through the child nodes
      {
        // and do the same to them
        var oResult = searchAttributeRecursive(oNode.childNodes[i], oAttributeKeys, oAttributeValues);
        
        if(oResult != null) // if there is a result object
        {
          return(oResult); // return it
        }
        
      }
      
    }
    
    return(null); // return null in case of no match
  }
}

// copied from template: basket_content_partserver.html
function AddAcc(sUrl, cookieid, lina, path, sSettings){
  LoadLinkPos();
  document.getElementById('loadbar').style.display = "block";
//   loadbar.style.display = "block";
//   LoadLink(sUrl + sSettings +'&addacc=' + path + '&cookieid=' + cookieid)
  AjaxRequest(sUrl + sSettings +'&addacc=' + path + '&cookieid=' + cookieid);
}


function AddAccToCookie(id,acc)
{
  c = ReadCookieByName(prefix + "[" + id + "]");
  // alert("c :" + c)
  w = c + acc;
  // alert("w :" + w) 
  
  if (cookieWriteAllowed()==true){
    WriteCookie(prefix + "[" + id + "]",w,ExpirationTime)   // Fügt dem Cookie die Zubehörteile zu.
  }else{
    writeCookiePopup(prefix + "[" + id + "]",w,ExpirationTime)   // Fügt dem Cookie die Zubehörteile zu.
  }
  
  // alert("document.cookie :" + document.cookie)
}

function UpdateCountProject(sErrorMessage)
{
  /*
    
    this function is a completely new implementation
    of the old UpdateCountProject() function
    
    it's supposed to work with the same type of cookies, but the
    workflow is quite different
    
    the function steps through the basket form and creates an
    updated cookie string, which is then stored into a cookie
    
    
    
    parameters
    ----------
    
    sErrorMessage - error message to be displayed in case the
                    user entered invalid values, will not display
                    a message when empty
    
    
    
    return value
    ------------
    
    (none)
    
    
    
    version history
    ---------------
    
    )x(  25.04.2008 - anpl - initial implementation
    
  */
  if (typeof sErrorMessage=='undefined'){sErrorMessage='Please enter valid values. Invalid values will be restored to their last entered valid value.'};
  
  // 1. initialisation
  var bInvalidValues = false; // invalid values entered by user?
  var bDontStoreThis = false; // don't store this item
  var oBasketTable = document.getElementById('basket_summary_table'); // basket table
  var oKeys = new Array(); // create key array
  var oValues = new Array(); // create value array
  oKeys[0] = 'basketid'; // key 1
  oValues[0] = 0; // start with the first main node
  oKeys[1] = 'basketsubid'; // key 2
  oValues[1] = null; // no sub node (start with main node)
  
  //2. action
  var oCookie = new ReadAllPrjFromCookies(); // read cookie
  
  if(oCookie['CountPrj'] > 0) // if there are projects
  {
    
    for(var i = 0; i < oCookie['CountPrj']; i++) // iterate through the projects
    { 
      oValues[0] = i; // select main node with id 'i'
      oValues[1] = null; // yes, it's really a main node
      
      // get the correct node
      var oMainNode = searchAttributeRecursive(oBasketTable, oKeys, oValues);
      
      var sCookieName = oCookie[i]['CookieName']; // get the cookie name
      var sCookie = ReadCookieByName(sCookieName); // get the cookie string
      var sNewCookie = ''; // new (updated) cookie string
      var sMainNode = sCookie.split('|||')[0]; // main node string
      
      // cut the old value off the main node string
      sMainNode = sMainNode.substring(0, sMainNode.lastIndexOf('|'));
      
      // if it is not a finite number
      if(!isFinite(oMainNode.value))
      {
        bInvalidValues = true; // it is an invalid value
        bDontStoreThis = true; // don't store it
      }
      
      // and add the new one
      sMainNode += '|' + parseInt(oMainNode.value, 10);
      
      // add main node to new cookie string
      sNewCookie += sMainNode;
      
      if(oCookie[i]['HasAcc']) // if there are accessories
      {
        
        sNewCookie += '|||'; // separator between main and sub nodes
        
        for(var j = 0; j < oCookie[i]['CountAcc']; j++) // iterate through the accessories
        {
          oValues[0] = i; // select main node with id 'i'
          oValues[1] = j; // select sub node with id 'j'
          
          // get the correct node
          var oSubNode = searchAttributeRecursive(oBasketTable, oKeys, oValues);
          
          var sSubNode = sCookie.split('|||')[1].split('||')[j]; // sub node string
          
          // cut the old value off the sub node string
          sSubNode = sSubNode.substring(0, sSubNode.lastIndexOf('|'));
          
          // if the value is not a finite number
          if(!isFinite(oSubNode.value))
          {
            bInvalidValues = true; // it is an invalid value
            bDontStoreThis = true; // don't store it
          }
          
          // and add the new one
          sSubNode += '|' + parseInt(oSubNode.value, 10);
          
          if(j > 0) // if it's not the first sub node
          {
            sNewCookie += '||'; // separator between sub nodes
          }
          
          // add sub node to new cookie string
          sNewCookie += sSubNode;
          
        }
        
      }
      
      if(!bDontStoreThis) // if we should store it
      {
        // write the updated cookie string
        if (cookieWriteAllowed()==true){
          WriteCookie(sCookieName, sNewCookie, ExpirationTime);
        }else{
          writeCookiePopup(sCookieName, sNewCookie, ExpirationTime);
        }
        
      }
      bDontStoreThis = false; // we might store the next one
        
    }
    
    if(bInvalidValues) // if invalid values have been enteres
    {
      if(sErrorMessage != '') // if error message is not empty
      {
        alert(sErrorMessage); // warn the user
      }
    }
    
  }
  
}

// function UpdateCountProject()
// {
//   var CookieObj = new ReadAllPrjFromCookies();  
//   // var CookieCnt = CookieObj.length;  
//   var input = document.getElementsByTagName("input")
//   // counter for input fields:
//   var j = 0;
//   // counter for cookies:
//   var i = 0;
//   for(j=0;j<input.length;j++){
//     // if ( input[j].id.indexOf("PrjCnt") != -1)    
//     if ( input[j].id.indexOf("PrjCnt") != -1)
//     {
//       // CookieID:
//       // alert("input["+j+"].value :" + input[j].value);
//   
//       var Name = CookieObj[i]['CookieName'];
//       // alert("CookieObj["+i+"]['CookieName'] :" + CookieObj[i]['CookieName'])
//       // Name = rightTrim(leftTrim(Name));
//       // alert("Name :" + Name);
// 
//       var c = ReadCookieByName(Name);
//       d = c.split("|||");
//       oldCookie = d[0];
//       // alert("oldCookie :\n" + oldCookie);
//       var NewCookie = "";            
//       // NewCookie = Name + "=";
//       var posLastPipe = oldCookie.lastIndexOf("|");
//       var oldCount  = oldCookie.substring(posLastPipe + 1,oldCookie.length)
//       // alert("oldCount : " + oldCount)
//       var oldVal    = oldCookie.substring(0,posLastPipe)
//       // alert("oldVal : "+ oldVal);      
//       // alert("oldCount : "+ oldCount);
//       NewCookie += oldVal;
//       NewCookie += "|";
//       NewCookie += input[j].value;       
// 
//       // go through the Accessories:
//       if(CookieObj[i]['HasAcc'] == true){
// 
//         var newAcc = "|";
//         for(k=0;k<CookieObj[i]['CountAcc'];k++){
//             AccName = CookieObj[i][k]['AccName'];
//             OldAccCount = CookieObj[i][k]['AccVal']; 
//             AccCount = "AccCnt_" + i + "_" + k;
//             newAccCount = document.getElementById(AccCount).value;
//             // alert("newAccCount : "+ newAccCount);
//             newAcc += "||" + AccName + "|" + newAccCount;
//             // alert("AccName :" + AccName)           
//             // alert("OldAccCount :" + OldAccCount)    
//         
//         } 
//         // alert("newAcc :" + newAcc);    
//         NewCookie += newAcc;
//       }      
//       // alert("NewCookie :" + NewCookie)
//       // overwrite existing cookie:
//       WriteCookie(Name,NewCookie,ExpirationTime);            
//       i++;
//     }
//   }
// 
// }
//---------------------------------------------

function DeleteCompleteBasket()
{
  /*
    
    this function is a completely new implementation
    of the old DeleteCompleteBasket() function
    
    the function empties the complete basket on the partserver
    
    
    
    parameters
    ----------
    
    none
    
    
    
    return value
    ------------
    
    none
    
    
    
    version history
    ---------------
    
    )x(  02.06.2008 - anpl - initial implementation
    
  */
  
  var oCookie = new ReadAllPrjFromCookies();
  if(oCookie['CountPrj'] > 0) // if there are projects
  {
    for(var i = 0; i < oCookie['CountPrj']; i++) // iterate through the projects
    {
      deletebasket(oCookie[i]['CookieID']); // delete every project in the basket
    }
  }

  var oDiv=document.getElementById('basket_summary');
  oDiv.innerHTML=''; // clean up basket div
}


// function DeleteCompleteBasket()
// {
//   var table = document.getElementById("div_basket");
//   table.innerHTML = "&nbsp;";
//   var cookie = decodeCookie(document.cookie).split(";");  
//   for(i=0;i<cookie.length;i++){
//     var CookieName = cookie[i].split("=")[0];
//     // alert("CookieName :" + CookieName);
//     if ( CookieName.indexOf(prefix) != -1 || CookieName.indexOf("PSOLProject") != -1 || CookieName.indexOf("PSOLProjectaccessorie") != -1)    
//     {
//       // alert("CookieName to delete :" + CookieName);
//       DeleteCookieByName(CookieName);
//     } 
//   }
//   doit(); 
// 
// }

function dopreview(sPath,sSettings)
{ 
  var oData = getUserData(); // the user data
  var oForm = document.preview_form; // the preview form
  
  // let's fill in the part
  oForm.part.value = '{$CADENAS_DATA/23d-libs/' + sPath + '},' + sSettings;
  
  // let's fill in the user data
  oForm.email.value = oData.email;
  oForm.userid.value = oData.userid;
  oForm.name.value = oData.firstname+' '+oData.lastname;
  oForm.phone.value = oData.phone;
  oForm.fax.value = oData.fax;
  oForm.city.value = oData.city;
  oForm.state.value = oData.state;
  oForm.country.value = oData.country;
  oForm.emailsize.value = oData.emailsize;
  oForm.normsystem.value = oData.normsystem;
  oForm.erpsystem.value = oData.erpsystem;
  oForm.plmsystem.value = oData.plmsystem;
  
  // submit the form
  oForm.submit();
}

function deletebasket(sCookieId)
{
//   prefix is out of cookies.js
  sCookieName=prefix+'['+sCookieId+']';
  DeleteCookieByName(sCookieName);
  
  var oDiv=document.getElementById('basket_summary');
  oDiv.innerHTML='';
  
  displaybasketFromCookie();
}

function goToConfig(){
    var loc = "/frame.asp?firm=ahp&language=" + language + "&dtlanguage=" + language;
//     var loc = "../../frame.asp?firm=ahp&language=" + language + "&dtlanguage=" + language;
    MeinFenster = window.open(loc, "Zweitfenster", "width=1000,height=700,scrollbars=yes,resizable=yes");
    MeinFenster.focus();

}

function getUserId(){
  var user_id = ReadCookieByName("user_id");
  user_id     = rightTrim(leftTrim(user_id));
  return user_id;
}
//-----------------------------------------------

//   $STGU removed
// var timeoutobj = "";
// function checkUserID(partvalues){
//     // alert("partvalues :" + partvalues)
//     user_id = getUserId();
//     if (user_id != "")
//       {
//         document.getElementById('IFrameBasket').src = '../ahp/23d-libs/guide/database.asp?language='+language+'&firm=ahp&user_id='+user_id+'&partvalues='+partvalues;    
//         window.clearInterval(timeoutobj);    
//       }
// }
//-----------------------------------------------

function goToConfig(){
    var loc = "../../frame.asp?firm=ahp&language=" + gsLanguage + "&dtlanguage=" + gsLanguage;
    // var loc = "../../login.asp?firm=ahp&language=" + language + "&dtlanguage=" + language;
    // var loc = http://www.partserver.de/login.asp?firm=ahp&language=german&dtlanguage=german
    MeinFenster = window.open(loc, "Zweitfenster", "width=1000,height=700,scrollbars=yes,resizable=yes");
    MeinFenster.focus();

}

//-----------------------------------------------
function getPartsListFromCookie(){
  var CookieArrForOrder = "";
  var CookieObj = new ReadAllPrjFromCookies();  
  for(i=0;i<CookieObj['CountPrj'];i++){    
    temp = "{$CADENAS_DATA/23d-libs/" + CookieObj[i]['PrjVal']['RelPath'] + "}," + CookieObj[i]['PrjVal']['ParamList']
    i==0? CookieArrForOrder += temp : CookieArrForOrder += "|" + temp;

  }
  return CookieArrForOrder;
}
function ds(firm, email, formats, userid, firstname, lastname, phone, fax, street, city, state, country, emailsize, normsystem, erpsystem, plmsystem){
  this.firm = firm;
  this.email = email;
  this.formats = formats;
  this.userid = userid;
  this.firstname = firstname;
  this.lastname = lastname;
  this.phone = phone;
  this.fax = fax;
  this.street = street;
  this.city = city;
  this.state = state;
  this.country = country;
  this.emailsize = emailsize;
  this.normsystem = normsystem;
  this.erpsystem = erpsystem;
  this.plmsystem = plmsystem;
  return this;
}


/* sample out of database.asp:
============================================================
<?xml version="1.0" ?>
<user>
  <firm><%=firma%></firm>
  <email><%=email%></email>
  <formats><%=Formate%></formats>
  <userid><%=idnr%></userid>
  <firstname><%=vorname%></firstname>
  <lastname><%=nachname%></lastname>
  <telephone><%=telefon%></telephone>
  <fax><%=fax%></fax>
  <street><%=strasse%></street>

  <zip><%=plz%></zip>
  <city><%=ort%></city>
  <state><%=land%></state>
  <country><%=landid%></country>
  <emailsize><%=emailsize%></emailsize>
  <normsystem><%=normsystem%></normsystem>
  <erpsystem><%=erpsystem%></erpsystem>
  <plmsystem><%=plmsystem%></plmsystem>
</user>
============================================================
*/

// function getUserData(url){
//   xmlhttp=null;
// //   code for Mozilla, etc.
//   if (window.XMLHttpRequest){
//     xmlhttp=new XMLHttpRequest();
//   }
// //   code for IE
//   else if (window.ActiveXObject){
// //     IE7 (and newer)
//     try
//     {
//       if ( ActiveXObject("Msxml2.XMLHTTP") ){
//         xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
// //     IE6 and older
//       }else{
//         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
//       }
//     } catch(e) {
//       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
//     }
//     
//   }
//   
//   var obj = ds();
//   if (xmlhttp.overrideMimeType){
//     xmlhttp.overrideMimeType("text/xml");
//   }else{
// //     xmlhttp.setRequestHeader('Content-Type', 'text/xml');
//   }
//   xmlhttp.open("GET", url, false);
//   xmlhttp.onreadystatechange = function(obj){
// 
//     if (xmlhttp.readyState==4 && xmlhttp.status==200){
//       if (xmlhttp.responseXML){
//         var xml = xmlhttp.responseXML;
//         
//         var firm = '';
//         var email = '';
//         var formats = '';
//         var userid = '';
//         var firstname = '';
//         var lastname = '';
//         var phone = '';
//         var fax = '';
//         
//         var street = '';
//         var city = '';
//         var state = '';
//         
//         var state = '';
//         var country = '';
//         var emailsize = '';
//         var normsystem = '';
//         var erpsystem = '';
//         var plmsystem = '';
//         
//         
//         if (xml.getElementsByTagName('firm')[0].firstChild)       {var firm = xml.getElementsByTagName('firm')[0].firstChild.data;};
//         if (xml.getElementsByTagName('email')[0].firstChild)      {var email = xml.getElementsByTagName('email')[0].firstChild.data;};
//         if (xml.getElementsByTagName('formats')[0].firstChild)    {var formats = xml.getElementsByTagName('formats')[0].firstChild.data;};
//         if (xml.getElementsByTagName('userid')[0].firstChild)     {var userid = xml.getElementsByTagName('userid')[0].firstChild.data;};
//         if (xml.getElementsByTagName('firstname')[0].firstChild)  {var firstname = xml.getElementsByTagName('firstname')[0].firstChild.data;};
//         if (xml.getElementsByTagName('lastname')[0].firstChild)   {var lastname = xml.getElementsByTagName('lastname')[0].firstChild.data;};
//         if (xml.getElementsByTagName('telephone')[0].firstChild)  {var phone = xml.getElementsByTagName('telephone')[0].firstChild.data};
//         if (xml.getElementsByTagName('fax')[0].firstChild)        {var fax = xml.getElementsByTagName('fax')[0].firstChild.data;};
//         
//         if (xml.getElementsByTagName('street')[0].firstChild)     {var street = xml.getElementsByTagName('street')[0].firstChild.data;};
//         if (xml.getElementsByTagName('city')[0].firstChild)       {var city = xml.getElementsByTagName('city')[0].firstChild.data;};
//         if (xml.getElementsByTagName('state')[0].firstChild)      {var state = xml.getElementsByTagName('state')[0].firstChild.data;};
//         
//         if (xml.getElementsByTagName('state')[0].firstChild)      {var state = xml.getElementsByTagName('state')[0].firstChild.data;};
//         if (xml.getElementsByTagName('country')[0].firstChild)    {var country = xml.getElementsByTagName('country')[0].firstChild.data;};
//         if (xml.getElementsByTagName('emailsize')[0].firstChild)  {var emailsize = xml.getElementsByTagName('emailsize')[0].firstChild.data;};
//         if (xml.getElementsByTagName('normsystem')[0].firstChild) {var normsystem = xml.getElementsByTagName('normsystem')[0].firstChild.data;};
//         if (xml.getElementsByTagName('erpsystem')[0].firstChild)  {var erpsystem = xml.getElementsByTagName('erpsystem')[0].firstChild.data;};
//         if (xml.getElementsByTagName('plmsystem')[0].firstChild)  {var plmsystem = xml.getElementsByTagName('plmsystem')[0].firstChild.data;};
//         
//         obj = ds(firm, email, formats, userid, firstname, lastname, phone, fax, street, city, state, country, emailsize, normsystem, erpsystem, plmsystem);
//       }
//     }
//   };
//   
//   xmlhttp.send(null);
//   return obj;
// }


function getUserData(){
  var userid = '';
  var emailsize = '';
  var normsystem = '';
  var erpsystem = '';
  var plmsystem = '';
  
  var company   = ReadCookieByName('cad_company');
  var email     = ReadCookieByName('cad_email');
  var firstname = ReadCookieByName('cad_firstname');
  var lastname  = ReadCookieByName('cad_lastname');
  var street    = ReadCookieByName('cad_street');
  var zipcode   = ReadCookieByName('cad_zipcode');
  var city      = ReadCookieByName('cad_city');
  var country   = ReadCookieByName('cad_country');
  var state     = ReadCookieByName('cad_state');
  var phone     = ReadCookieByName('cad_phone');
  var fax       = ReadCookieByName('cad_fax');
  
  var formats   = ReadCookieByName('cad_formats').split('|').join(',');
      
  obj = ds(company, email, formats, userid, firstname, lastname, phone, fax, street, city, state, country, emailsize, normsystem, erpsystem, plmsystem);
  return obj;
}


// function orderFromCadenas(partvalues){
function orderFromCadenas(sMessage){
  if (typeof sMessage=='undefined'){sMessage = "It seems you are not registered on PARTserver. A new window opens where you can register. You don't need to click the Button 'Send CAD-Data per Mail' again."}  
  
  var sPartValues = getPartsListFromCookie();
//   user_id = getUserId();
// 
//   if (user_id != ""){

//     var url = '/ahp/23d-libs/guide/database.asp?user_id='+user_id +'&firm=ahp'
//     var userData = getUserData(url);

    var userData = getUserData();

    var firm = 'ahp';
//     if (userData.firm){var firm = userData.firm;};
    var email = userData.email;
    var formats = userData.formats;
    var userid = userData.userid;
    var firstname = userData.firstname;
    var lastname = userData.lastname;
    var phone = userData.phone;
    var fax = userData.fax;
    var street = userData.street;
    var city = userData.city;
    var state = userData.state;
    var country = userData.country;
    var emailsize = userData.emailsize;
    var normsystem = userData.normsystem;
    var erpsystem = userData.erpsystem;
    var plmsystem = userData.plmsystem;
    
    var basket = document.getElementById('basket_orderparts'); // get existing order form
    
    if(basket == null) // if no order form exists
    {
      basket = document.createElement('form'); // create one
      modifyAttribute(basket, 'id', 'basket_orderparts'); // and give an id
      var bFirstOrder = true; // seems to be the first order
    }
    else // if one existed
    {
      while(basket.hasChildNodes()) // as long as it has child nodes (contains data from former orders)
      {
        basket.removeChild(basket.lastChild); // remove last child node
      }
      var bFirstOrder = false; // seems not to be the first order (since an order form existed yet)
    }

      modifyAttribute(basket, 'target', '_blank');
//       modifyAttribute(basket, 'target', 'IFrameBasket');
      
      modifyAttribute(basket, 'action', '/cgi-bin/cgi2pview.cgi');
      modifyAttribute(basket, 'method', 'GET');
      

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'language');
        modifyAttribute(input, 'value', 'english');
      basket.appendChild(input);
      
      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'firm');
        modifyAttribute(input, 'value', firm);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'email');
        modifyAttribute(input, 'value', email);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'format');
        modifyAttribute(input, 'value', formats);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'userid');
        modifyAttribute(input, 'value', userid);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'name');
        modifyAttribute(input, 'value', (firstname + ' ' + lastname));
//         modifyAttribute(input, 'name', 'lastname');
//         modifyAttribute(input, 'value', lastname);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'phone');
        modifyAttribute(input, 'value', phone);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'fax');
        modifyAttribute(input, 'value', fax);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'street');
        modifyAttribute(input, 'value', street);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'city');
        modifyAttribute(input, 'value', city);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'state');
        modifyAttribute(input, 'value', state);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'country');
        modifyAttribute(input, 'value', country);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'emailsize');
        modifyAttribute(input, 'value', emailsize);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'normsystem');
        modifyAttribute(input, 'value', normsystem);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'erpsystem');
        modifyAttribute(input, 'value', erpsystem);
      basket.appendChild(input);

      var input = document.createElement('input');
        modifyAttribute(input, 'type', 'hidden');
        modifyAttribute(input, 'name', 'plmsystem');
        modifyAttribute(input, 'value', plmsystem);
      basket.appendChild(input);
    
    if(bFirstOrder == true) // if it is the first order
    {
      document.getElementsByTagName('body')[0].appendChild(basket); // put node into dom
    }
    
    
    var parts = sPartValues.split('|');
    for(i=0;i<parts.length;i++){
      if ( parts[i].indexOf('{') != -1){
//         var temp = document.getElementById('basket_orderparts');
        var input = document.createElement('input');
          input.setAttribute('type', 'hidden');
          input.setAttribute('name', 'part');         
          input.id = 'part' + i; 
          input.value = parts[i]; 
        basket.appendChild(input);
      }
    } 
    basket.submit();
//     document.basket_orderparts.submit();   
    
//     var _user = user('s.guenter@cadenas.de', 'ahp','Stefan','Günter','Berliner Allee 28 b+c');
//     var _wkb = wkb('BMPFILE','','',sPartsListFromCookie);
//     orderPart(_user, _wkb);
    
//     document.getElementById('IFrameBasket').src = '../ahp/23d-libs/guide/database.asp?language='+language+'&firm=ahp&user_id='+user_id+'&partvalues='+partvalues;
//   }
//   // user_id could not found:
//   else
//   {
//     alert(sMessage);
//     goToConfig()
//   }
}



function WriteBasket(sLina, sSettings, sPath, sInfoMsg){
//   alert("writebasket");
  if ( typeof sInfoMsg=='undefined' ){
    sInfoMsg = 'The part / assembly has been added to basket: ';
  }
  sInfoMsg += ' '+sLina;
  
  if (cookieWriteAllowed()==true){
    
    var obj1 = ReadAllPrjFromCookies();  
    // evtl. Funktion für Prüfung welche IDs schon vergeben sind!!!!!!!!!!!!!!!!!!!!!
    var count = obj1['CountPrj'];
    
    if(count > 0)
    {
      var highestId = parseInt(obj1[count - 1].CookieID); // id of highest cookie (would be 4 if highest cookie was 'AHP_PRJ[4]')
    }
    else
    {
      var highestId = 0;
    }
    
//     alert('WriteCookie();');
    WriteCookie("AHP_PRJ[" + (highestId+1) + "]",""+sLina+"|"+sSettings+"|"+sPath+"|1",ExpirationTime);
    alert(convertHTML(sInfoMsg));
    
  }else{
//     alert('no cookie writing allowed within iframe');
//     alert('assistant URL: \n'+document.URL);
    var obj1 = ReadAllPrjFromCookies();  
//     // evtl. Funktion für Prüfung welche IDs schon vergeben sind!!!!!!!!!!!!!!!!!!!!!
    var count = obj1['CountPrj'];
    
    if(count > 0)
    {
      var highestId = parseInt(obj1[count - 1].CookieID); // id of highest cookie (would be 4 if highest cookie was 'AHP_PRJ[4]')
    }
    else
    {
      var highestId = 0;
    }
    
    var name = 'AHP_PRJ[' + (highestId+1) + ']';
    var value = sLina+'|'+sSettings+'|'+sPath+'|1';
//     var a = new Date();
//     a = new Date(a.getTime() +ExpirationTime);
    
    var bSuccess = writeCookiePopup(name, value, ExpirationTime);
    if(bSuccess)
    {
      alert(convertHTML(sInfoMsg)); // ".. part has been added to basket .."
    }
    
  }
}


// function WriteBasket(sLina, sSettings, sPath, sInfoMsg){
//   if ( typeof sInfoMsg=='undefined' ){
//     sInfoMsg = 'The part / assembly has been added to basket: ';
//   }
//   sInfoMsg += ' '+sLina;
//   var obj1 = ReadAllPrjFromCookies();  
//   // evtl. Funktion für Prüfung welche IDs schon vergeben sind!!!!!!!!!!!!!!!!!!!!!
//   var count = obj1['CountPrj'];
//   count++;
//   alert('WriteCookie();');
//   WriteCookie("AHP_PRJ[" + count + "]",""+sLina+"|"+sSettings+"|"+sPath+"|1",ExpirationTime);
//   alert(sInfoMsg);
// }

// function CallBasketPARTserver()
// {
// //     LoadLink("/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/ahp_assistant.vbb&option=basket&path=ahp&settings=&partserver=1&language=german&root=&beta=0");
// //   LoadLink("/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/ahp_assistant.vbb&option=basket&path=ahp&settings=&partserver=1&language=german&root=");
// //   AjaxRequest("/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/ahp_assistant.vbb&option=basket&path=ahp&settings=&partserver=1&language=german&root=");
// }

function GoToBasket(sUrl){
  AjaxRequest(sUrl);
}


function encode_utf8(rohtext){
  // dient der Normalisierung des Zeilenumbruchs
  rohtext = rohtext.replace(/\r\n/g,"\n");
  var utftext = "";
  for (var n=0; n<rohtext.length; n++){
    // ermitteln des Unicodes des  aktuellen Zeichens
    var c=rohtext.charCodeAt(n);
    // alle Zeichen von 0-127 => 1byte
    if (c<128){
      utftext += String.fromCharCode(c);
    
    // alle Zeichen von 127 bis 2047 => 2byte
    }else if ((c>127) && (c<2048)) {
      utftext += String.fromCharCode((c>>6)|192);
      utftext += String.fromCharCode((c&63)|128);
    }
    // alle Zeichen von 2048 bis 66536 => 3byte
    else{
      utftext += String.fromCharCode((c>>12)|224);
      utftext += String.fromCharCode(((c>>6)&63)|128);
      utftext += String.fromCharCode((c&63)|128);
    }
  }
  return utftext;
}

function decode_utf8(utftext){
  var plaintext = ""; var i=0; var c=c1=c2=0;
  // while-Schleife, weil einige Zeichen uebersprungen werden
  while(i<utftext.length)
     {
     c = utftext.charCodeAt(i);
     if (c<128) {
         plaintext += String.fromCharCode(c);
         i++;}
     else if((c>191) && (c<224)) {
         c2 = utftext.charCodeAt(i+1);
         plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
         i+=2;}
     else {
         c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2);
         plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
         i+=3;}
     }
  return plaintext;
}

UTF8 = {
  encode: function(s){
    for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
      s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
    );
    return s.join("");
  },
  decode: function(s){
    for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
      ((a = s[i][c](0)) & 0x80) &&
      (s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
      o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
    );
    return s.join("");
  }
};

function UpdateValuesAndSubmit(todo, root){

  if( document.userdata.input_0.value   == "" || //company
      document.userdata.input_2.value   == "" || //email
      document.userdata.input_4.value   == "" || //firstname
      document.userdata.input_5.value   == "" || //lastname
      document.userdata.input_6.value   == "" || //street
      document.userdata.input_7.value   == "" || //zip
      document.userdata.input_8.value   == "" || //city
      document.userdata.input_9.value   == "" || //country
      document.userdata.input_11.value  == "" || //phone
      document.userdata.input_12.value  == "" || //fax
      document.userdata.ordertype.value == "" )
  {
    alert('userdata incomplete'); //alt
    return;
  }


  sResult  = "{company=" + escape(document.userdata.input_0.value) + "},"
  sResult += "{email=" + escape(document.userdata.input_2.value) + "},"
  sResult += "{firstname=" + escape(document.userdata.input_4.value) + "},"
  sResult += "{lastname=" + escape(document.userdata.input_5.value) + "},"
  
  sResult += "{knr=" + escape(document.userdata.input_3.value) + "},"
  sResult += "{ordertype=" + escape(document.userdata.ordertype.value) + "},"
  sResult += "{street=" + escape(document.userdata.input_6.value) + "},"
  sResult += "{zip=" + escape(document.userdata.input_7.value) + "},"
  sResult += "{city=" + escape(document.userdata.input_8.value) + "},"
  sResult += "{country=" + escape(document.userdata.input_9.value) + "},"
//   sResult += "{state=" + escape(document.userdata.input_10.value) + "},"
  sResult += "{phone=" + escape(document.userdata.input_11.value) + "},"
  sResult += "{division=" + escape(document.userdata.input_1.value) + "},"
  sResult += "{comments=" + escape(document.userdata.comments.value) + "},"
  sResult += "{fax=" + escape(document.userdata.input_12.value) + "}"
  
//   document.write(sResult);
//   return;

  
  if(todo == "") // Save only
  {
    // in Cookies speichern!
    WriteInAllCookies();
  }
  else if(todo == "print") // print
  {
    WriteInAllCookies();
 
    LoadLinkNewWindow('/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/ahp_assistant.vbb&option=basketprint&path=ahp&settings=&partserver=' + gbPartserver + '&language=german&root=' +root+ '&userdata=' +sResult);
//     AjaxRequest('/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/ahp_assistant.vbb&option=basketprint&path=ahp&settings=&partserver=1&language=german&root=' +root+ '&userdata=' +sResult);
  }
}

function UpdateValues(sErrorMessage)
{
  /*
    
    this function is a completely new implementation
    of the old UpdateValues() function
    
    the result string is of the same format, but the workflow is quite
    different
    
    the function steps through the basket form and builds a string with
    the following format
    
    {<mainItem(0)Count>=<subItem(0)(0)Count>-<subItem(0)(1)Count>-[..]-<subItem(0)(n)Count>},
    {<mainItem(1)Count>=<subItem(1)(0)Count>-<subItem(1)(1)Count>-[..]-<subItem(1)(n)Count>},
    {<mainItem(2)Count>=<subItem(2)(0)Count>-<subItem(2)(1)Count>-[..]-<subItem(2)(n)Count>},
    [..]
    {<mainItem(m)Count>=<subItem(m)(0)Count>-<subItem(m)(1)Count>-[..]-<subItem(m)(n)Count>}
    
    
    
    parameters
    ----------
    
    sErrorMessage - error message to be displayed in case the
                    user entered invalid values, will not display
                    a message when empty
    
    
    
    return value
    ------------
    
    formatted string
    
    
    
    version history
    ---------------
    
    )x(  24.04.2008 - anpl - initial implementation
    
  */
  if (typeof sErrorMessage=='undefined'){sErrorMessage='Please enter valid values. Invalid values will be restored to their last entered valid value.'};

  // 1. initialisation
  var bInvalidValues = false; // invalid values entered by user?
  var sResult = ''; // result string
  var bSkip = false; // temporary boolean (skip one cycle of the main node loop)
  var oBasketTable = document.getElementById('basket_summary_table'); // basket table
  var oKeys = new Array(); // create key array
  var oValues = new Array(); // create value array
  oKeys[0] = 'basketid'; // key 1
  oValues[0] = 0; // start with the first main node
  oKeys[1] = 'basketsubid'; // key 2
  oValues[1] = null; // no sub node (start with main node)
  
  // 2. action
  do // iterate through the main nodes
  { 
    
    try // will throw an error if we go past the last main node
    {
      // get the correct main node
      var oMainNode = searchAttributeRecursive(oBasketTable, oKeys, oValues);
      var iMainValue = oMainNode.value; // get main node value (= item count)
      
      // if it is not a finite number
      if (!isFinite(iMainValue))
      {
        bInvalidValues = true; // invalid values found
        iMainValue = ''; // set it to empty string
      }
      
    }
    catch(e) // if we went beyond the limit
    {
      bSkip = true; // skip this pass since the object will be invalid
    }
    
    if(!bSkip) // if there are still main nodes which are valid
    {
      
      if(oValues[0] != 0) // if it's not the first main node
      {
        sResult += ','; // we need a comma as a separator
      }
      
      if(iMainValue != '') // if it's not an empty string
      {
        iMainValue = parseInt(iMainValue, 10); // parse it into an integer
      }
      
      // insert curly brace, main node value and an equal sign as a seperator
      sResult += '{' + iMainValue + '=';
      
        // ********************************
        // * now we are on sub node level *
        // ********************************
        
        oValues[1] = 0; // start with the first sub node (index 0)
        
        do // iterate through the sub nodes
        { 
          // get the correct sub node
          var oSubNode = searchAttributeRecursive(oBasketTable, oKeys, oValues);
          
          try // will throw an error if we go past the last sub node
          {
            var iSubValue = oSubNode.value; // get sub node value (= item count)
            
            // if it is not a finite number
            if(!isFinite(iSubValue))
            {
              bInvalidValues = true; // invalid values found
              iSubValue = ''; // set it to empty string
            }
            
            if(oValues[1] != 0) // if it's not the first sub node
            {
              sResult += '-'; // we need a minus as a separator
            }
            
            if(iSubValue != '') // if it's not an empty string
            {
              iSubValue = parseInt(iSubValue, 10); // parse it into an integer
            }
            
            sResult += iSubValue; // insert sub node value
          }
          catch(e) // if there are no more sub nodes
          {
            oSubNode = null; // set the sub node object to null
          }
          
          oValues[1]++; // continue with next sub node in the basket
        }
        while(oSubNode != null); // continue until no sub nodes are left
        
        oValues[1] = null; // continue with the next main node (so sub node = null)
        
        // *************************************
        // * let's get back to main node level *
        // *************************************
      
      sResult = sResult+'}'; // close the curly brace for the main node
    }
    else // if there is no more main node
    {
      oSubNode = null; // set the sub node object to null
      oMainNode = null; // set the main node object to null
    }
    
    oValues[0]++; // continue with next main node in the basket
  }
  while(oMainNode != null); // continue until no main nodes are left
  
  if(bInvalidValues) // if invalid values have been found
  {
    if(sErrorMessage != '') // if error message is not empty
    {
      alert(sErrorMessage); // warn the user
    }
  }
  
  sResult = escape(sResult); // escape the string
  
  oValues = null; // destroy instance of value array
  oKeys = null; // destroy instance of key array
  return(sResult); // return result string
}

// function UpdateValues(){
//   var sResult = "";
//   var iKidsCount = 0;
//   
//   // Alle Gruppen durchgehen
//   var iMax = 0;
//   for(var iCount = 0; iCount < iMax; iCount++){
//     if(sResult != "") sResult += ",";
//     sResult += "{";
//   
//     var countInp = eval("document.form_" + iCount + ".countinp");
//     sResult += countInp.value + "=";
//     
//     // Alle Kinder durchgehen
//     var sKid = ""
//     var countKids = eval("document.form_" + iCount + ".countkids");
//     for(var k = 0; k < countKids.value; k++){
//       if(sKid != "") sKid += "-";
//       
//       var kidscountInp = eval("document.kidform_" + iKidsCount + ".countinp");
//       iKidsCount ++;
//       
//       sKid += kidscountInp.value;
//     }
//     
//     sResult += sKid + "}";
//   }
//   
//   return sResult;
// }

