﻿
if (navigator.cookieEnabled)
  {
  // alert('Cookies are activated.')
  }
else
  {
  alert('Cookies are deactivated!');
  }
//--------------------------------------------- 

// first signs of the cookies:
var prefix        = "AHP_PRJ";
var prefix_basket = "AHP_BASKET_";
var ExpirationTime  = 1000 * 60 * 60 * 24 * 365; //365 Tage
var bAlertCookieShown=false;
var bAlertPopupShown=false;

function transmute(oParam)
{
  //
  // transmute strings and objects
  //
  // converts strings and objects into a two-character-format
  // this function is used by convertCookieDate
  //
  
  var sParam = oParam + ''; // convert parameter to string (serialize)
  
  while(sParam.length < 2) // as long as it's shorter than two characters
  {
    sParam = '0' + sParam; // append leading zeroes
  }
  
  while(sParam.length > 2) // as long as it's longer than two characters
  {
    sParam = sParam.substring(1); // strip characters off the front
  }
  
  return(sParam); // return value
}

function convertCookieDate(oDate)
{
  //
  // convert date object to a string which may be used for storing a cookie in Internet Explorer 7
  //
  // .toGMTString() or standard serialization of the Date() object does NOT work with IE7, since
  // it doesn't format the date for IE to understand
  //
  // Standard serialization: Sat Jan 10 02:00:00 UTC+0200 2009
  // .toGMTString():         Sat, 10 Jan 2009 00:00:00 UTC
  // this function:          Saturday, 10-Jan-09 00:00:00 GMT
  //
  //
  // this was tested in:
  //
  // Firefox 3.0.1
  // Firefox 2.0.16
  // Internet Explorer 7.0.5730.13
  // Opera 9.52
  // Safari 3.0.4.523.12.9
  //
  // and is functional with all these browsers 
  //
  
  // prepare arrays
  var oWeekdays = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
  var oMonths = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
  
  // convert
  var sWeekday = oWeekdays[oDate.getDay()];
  var sDay = transmute(oDate.getUTCDate());
  var sMonth = oMonths[oDate.getUTCMonth()];
  var sYear = transmute(oDate.getUTCFullYear());
  var sHour = transmute(oDate.getUTCHours());
  var sMinute = transmute(oDate.getMinutes());
  var sSecond = transmute(oDate.getSeconds());
  
  var sCookieDate = sWeekday + ', ' + sDay + '-' + sMonth + '-' + sYear + ' ' + sHour + ':' + sMinute + ':' + sSecond + ' GMT'; 
  
  // return value
  return(sCookieDate);
}

function encodeCookie(sCookieString)
{
  // encodes 'critical' characters, such as a comma, which causes unwanted behaviour
  // when stored in a cookie in Safari browser, to a format like '§comma'
  //
  // the paragraph sign '§' itself must be encoded FIRST and decoded LAST
  //
  // at last, escape the string, in order to prevent Opera from malfunctioning
  
  sCookieString = sCookieString.replace(/§/g,'§paragraph');
  sCookieString = sCookieString.replace(/,/g,'§comma');
  sCookieString = sCookieString.replace(/;/g,"");
  sCookieString = escape(sCookieString);
  sCookieString = sCookieString.replace(/;/g,"");
  
  return(sCookieString);
}

function decodeCookie(sCookieString)
{
  // decodes a string which has been encoded by encodeCookie
  
  sCookieString = unescape(sCookieString);
  sCookieString = sCookieString.replace(/§comma/g,',');
  sCookieString = sCookieString.replace(/§paragraph/g,'§');
  
  return(sCookieString);
}

function cookieWriteAllowed(){
  if (navigator.cookieEnabled == true){
//     expiration date 10 seconds
    var a = new Date();
    a = new Date(a.getTime() + 10000);
    
//     document.cookie = 'AHP_cookie_test='+encodeCookie('1')+'; expires=' +a.toGMTString()+ ';';
    document.cookie = 'AHP_cookie_test='+encodeCookie('1')+'; expires=' +convertCookieDate(a)+ ';';
    var pos = decodeCookie(document.cookie).search(/AHP_cookie_test.+/);
    
    if (pos != -1){
      return true;
    }
  }
  return false;
}


// check if cookies may be written
function checkUserCookies(gsPopupForbiddenMessage){
  
//   $STGU; all fallback / default values at the top of a method -> easier to understand for "non-origin" developers ;)
  if ( typeof(gsPopupForbiddenMessage) == 'undefined' ){
    gsPopupForbiddenMessage = 'Your browser prevents cookies from being written and popup windows from being displayed. Please disable your popup blocker, since this may prevent the assistant from working properly.';
  }
  
  if(!cookieWriteAllowed()){
    
    var oWindow = window.open('', 'PopupTestWindow', 'dependent=yes,height=1,hotkeys=no,left=-10,location=no,menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no,top=-10,width=1');
//     var oWindow = null;
    
    if(oWindow == null)
    {
      bThisMsgDisplayed = true;
      alert(gsPopupForbiddenMessage);
    }
    else if(oWindow.closed == true)
    {
      bThisMsgDisplayed = true;
      alert(gsPopupForbiddenMessage);
    }
    else
    {
      try
      {
        oWindow.close();
      }
      catch(e)
      {}
    
    } // oWindow == null
  } //cookieWriteAllowed()
}

//---------------------------------------------
function leftTrim(sString) 
  {
  while (sString.substring(0,1) == ' ')
    {
      sString = sString.substring(1, sString.length);
    }
  return sString;
}
//---------------------------------------------
function rightTrim(sString) 
  {
  while (sString.substring(sString.length-1, sString.length) == ' ')
    {
      sString = sString.substring(0,sString.length-1);
    }
  return sString;
}


function writeCookiePopup(name, value, exp, verbose, sErrorMsg){
  if (typeof verbose=='undefined'){
    verbose=0;
  }

  if(typeof sErrorMsg=='undefined')
  {
    sErrorMsg='Your browser prevents popup windows from being opened. Changes to the basket could not be completed. They may have been performed partially or not at all. Please disable your popup blocker and try again.';
  }

  var a = new Date();
  a = new Date(a.getTime() +exp);

//   alert('name: \n'+name);
//   alert('value: \n'+value);
//   alert('exp: \n'+exp);
  if (bAlertCookieShown!=true){
    alert(sCookieWritingNotAllowed);
    bAlertCookieShown=true;
  }
  
  var sIEDate = convertCookieDate(a); // convert to internet explorer cookie date format
  
  var oWindow = window.open('/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/create.vbb&method=writecookie&verbose=' +verbose+ '&cookiename=' +name+ '&cookievalue=' +value+ '&cookieexpiration=' +sIEDate);
  
  if(oWindow == null) // if window object is null
  {
    if(!bAlertPopupShown) // if it was not displayed recently
    {
      bAlertPopupShown = true; // prevent multiple alerts from being shown when updating multiple items in basket
      alert(sErrorMsg); // display error message
      window.setTimeout('bAlertPopupShown=false;','500'); // reset flag so that message is shown next time basket is updated
    }
    return(false); // write cookie fails
  }
  else if(oWindow.closed == true) // or if window is closed
  {
    if(!bAlertPopupShown) // if it was not displayed recently
    {
      bAlertPopupShown = true; // prevent multiple alerts from being shown when updating multiple items in basket
      alert(sErrorMsg); // display error message
      window.setTimeout('bAlertPopupShown=false;','500'); // reset flag so that message is shown next time basket is updated
    }
    return(false); // write cookie fails
  }
  
  return(true); // success
}

function readCookiePopup(){
  window.open('/cgi-bin/vbshtmlcgi.cgi?script=$CADENAS_DATA/23d-libs/ahp/guide/script/create.vbb&method=readcookie');
}


//---------------------------------------------
// example : WriteCookie('wert4','jkl',ExpirationTime)
function WriteCookie(n,w,e){
//   if ( cookieWriteAllowed()==true ) {
    var a = new Date();
    a = new Date(a.getTime() +e);
//     document.cookie = n+'='+encodeCookie(w)+'; expires='+a.toGMTString()+';';
    document.cookie = n+'='+encodeCookie(w)+'; expires='+convertCookieDate(a)+';';
//   }else{
//     var a = new Date();
//     a = new Date(a.getTime() +e);
// 
//     writeCookiePopup(n,w,a.toGMTString(),1);
// //     writeCookiePopup(n,w,a.toGMTString());
//   }
}

//---------------------------------------------

function ReadAllPrjFromCookies()
{
  var countPrjs = 0;
  // var PrjNames = new Array();
  var obj = new Array();  
  obj['CountPrj'] = 0;
//   alert('ReadAllPrjFromCookies::document.URL: \n'+document.URL);
//   alert('ReadAllPrjFromCookies::document.cookie: \n'+document.cookie);
  var cookie = decodeCookie(document.cookie).split(";");
  //   var CookieName = cookie[i].split("=")[0];
  
  // counter for object:
  var k = 0;
   
  for(i=0;i<cookie.length;i++) //alle Cookies durchgehen
  {
    obj[k] = new Array();
    // obj[i]['HasAcc'] = false;
    var cookie = decodeCookie(document.cookie).split(";");
    var CookieName = cookie[i].split("=")[0];
    CookieName = rightTrim(leftTrim(CookieName));
    
    if(CookieName.substring(0,prefix.length) == prefix){    
      // alert("CookieName :"+ CookieName)
      obj[k]['CookieName'] = CookieName;    
 
      // get the position of the first "=":
      var pos = cookie[i].search(/=/);
      
      // value of the cookie:      
      CookieVal = cookie[i].substring(pos+1,cookie[i].length);
      obj[k]['CookieVal'] = CookieVal;
      // alert("obj["+k+"]['CookieVal'] :"+ obj[k]['CookieVal'])      
       
      obj[k]['PrjName'] = CookieName;
      // alert("obj[k]['PrjName'] :"+ obj[k]['PrjName'])

      // get Cookie-ID;
      var a = obj[k]['PrjName'].search(/\[/);
      var b = obj[k]['PrjName'].search(/\]/);
      var CookieId = obj[k]['PrjName'].slice(a+1,b);
      obj[k]['CookieID'] = CookieId;        
      // alert("obj["+k+"]['CookieID'] :>" + obj[k]['CookieID']+ "<")

      // alert("obj["+k+"]['PrjName'] :" + obj[k]['PrjName'])        
      // alert("obj["+k+"]['CookieVal'] :" + obj[k]['CookieVal'])
      // split value of cookie into value for project and accessories

      var x = obj[k]['CookieVal'].split("|||"); 
      
      // Val = x[0];
      obj[k]['PrjVal'] = x[0];
      // alert("obj[k]['PrjVal'] :" + obj[k]['PrjVal'])
      var a = x[0].split("|");
      obj[k]['PrjVal'] = a;
      // alert("obj[k]['PrjVal'][0] :" + obj[k]['PrjVal'][0])
      obj[k]['PrjVal']['LINA'] = obj[k]['PrjVal'][0];
      obj[k]['PrjVal']['ParamList'] = obj[k]['PrjVal'][1];
      obj[k]['PrjVal']['RelPath'] = obj[k]['PrjVal'][2];
      obj[k]['PrjVal']['Count'] = obj[k]['PrjVal'][3];
      countPrjs = countPrjs + 1;
      obj['CountPrj'] = countPrjs;
      // alert("obj["+k+"]['PrjVal']['Count'] : " + obj[k]['PrjVal']['Count'])                      
     
      // if accessories are available:
      if (x.length == 2)
      {
        obj[k]['HasAcc'] = true;
        // Zubehör:
        var y = x[1].split("||");
        obj[k]['CountAcc'] = y.length;
        // alert("obj[k]['CountAcc'] :" + obj[k]['CountAcc'])                        
        for(j=0;j<y.length;j++)
        {
          var z = y[j].split("|");
          obj[k][j] = z;
          obj[k][j]['AccName']  = obj[k][j][0];
          obj[k][j]['AccVal']   = obj[k][j][1];            
          // alert("obj[k][j]['AccName'] :" + obj[k][j]['AccName'])
          // alert("obj[k][j]['AccVal'] :" + obj[k][j]['AccVal'])            
        } 
      }
      else
      {
        obj[k]['HasAcc'] = false;
      }
      
      
      // This is necessary, since Safari does not actually delete cookies when
      // the assistant is being run within an iFrame. Instead the value
      // 'delete' is assigned to the cookie's value and the cookie is treated as
      // if it were not existing. All other browsers are actually deleting the
      // cookie.
      
      if(CookieVal != 'delete') // if cookie shall not be treated as if it were deleted
      {
        k++; // increase index
      }
      else // otherwise
      {
        obj[k] = null; // distroy instance of array and read next cookie into the same index k
        countPrjs--; // decrease project count since it has been increased before
        obj['CountPrj'] = countPrjs; // update result object
      }
      
      
    }
  }
  // alert("hasacc :" + obj[i]['HasAcc'])
  return obj; 
}

//---------------------------------------------
function ReadCookieByName(n)
{
  //alert('n :' + n)
 a = decodeCookie(document.cookie);
 res = '';
 while(a != '')
 {
  while(a.substr(0,1) == ' '){a = a.substr(1,a.length);}
  CookieName = a.substring(0,a.indexOf('='));
  //alert('CookieName :'+CookieName)  
   
  a.indexOf(';') != -1 ?  cookiewert = a.substring(a.indexOf('=')+1,a.indexOf(';')) : cookiewert = a.substr(a.indexOf('=')+1,a.length);
  //alert('cookiewert :'+cookiewert)  
  if(n == CookieName) {res = cookiewert;}
  i = a.indexOf(';')+1;
  if(i == 0){i = a.length;}
  a = a.substring(i,a.length);
 }
return(res)
}
//---------------------------------------------
function DeleteCookieByName(name)                                             // example: DeleteCookieByName('PSOL_Project');
{ 
    //alert('name :' + name)
    var exp = new Date();
    exp.setTime (exp.getTime() - 1000);
    if(cookieWriteAllowed()==true)
    {
      document.cookie = name + "=delete; expires=" + convertCookieDate(exp);
//       document.cookie = name + "=delete; expires=" + exp.toGMTString();
    // alert('document.cookie :\n' + document.cookie);
    }
    else
    {
      writeCookiePopup(name, 'delete', (-1000));
    }    
}
// ----------------------------------------------------------------------------
function ReadValsFromCookie(name)
{
  // Cookienames of the first version:
  temp = ReadCookieByName("basket_" + name);
  if ( temp != "" )
    return temp;  
  else
    return ReadCookieByName(prefix_basket + name);
}

// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
//   $STGU: NEW CODE  from templates
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
function WriteInCookies(name)
{
//   if (name == "comments" || name == "ordertype" )
//     input = eval("document.typedata." + name);
//   else  
//     input = eval("document.userdata." + name);
  input = eval("document.userdata." + name);
  name = prefix_basket + name;
  if (cookieWriteAllowed()==true){
    WriteCookie(name, input.value, ExpirationTime);
  }else{
    writeCookiePopup(name, input.value, ExpirationTime);
  }
  
}

function WriteInCookiesSelectBox(sName)
{
  // anpl - 15.05.2008
  var oSelectBox = eval('document.userdata.' + sName);
  if (cookieWriteAllowed()==true){
    WriteCookie((prefix_basket + sName), oSelectBox.selectedIndex.toString(), ExpirationTime);
  }else{
    writeCookiePopup((prefix_basket + sName), oSelectBox.selectedIndex.toString(), ExpirationTime);
  }
  
}

function ReadFromCookies(sName)
{
  // anpl - 15.05.2008
  var sContent = ReadCookieByName(prefix_basket + sName);
  var oInputField = eval('document.userdata.' + sName);
  oInputField.value = sContent;
}

function ReadFromCookiesSelectBox(sName)
{
  // anpl - 15.05.2008
  var iContent = parseInt(ReadCookieByName(prefix_basket + sName));
  var oSelectBox = eval('document.userdata.' + sName);
  oSelectBox.selectedIndex = iContent;
}

function WriteInAllCookies()
{

  WriteInCookies('input_0');
  WriteInCookies('input_1');
  WriteInCookies('input_2');
  WriteInCookies('input_4');
  WriteInCookies('input_5');
  WriteInCookies('input_3');
  WriteInCookies('input_6');
  WriteInCookies('input_7');
  WriteInCookies('input_8');
  WriteInCookies('input_9');
//   WriteInCookies('input_10');
  WriteInCookies('input_11');
  WriteInCookies('input_12');
  WriteInCookies('comments');
  WriteInCookiesSelectBox('ordertype');
}

function ReadFromAllCookies()
{
  // anpl - 15.05.2008
  var iInputCookieCount = 13; // adjust if necessary
  for(var i = 0; i < iInputCookieCount; i++)
  {
    if(i != 10) // input 10 does not exist
    {
      ReadFromCookies('input_' + i);
    }
  }
  ReadFromCookiesSelectBox('ordertype');
  ReadFromCookies('comments');
}

// ----------------------------------------------------------------------------
// function orderFromCadenas(part_values){
//   alert(partvalues[0]);
//   
//   var user_id = ReadCookieByName("user_id");
//   // alert("user_id :" + user_id);
//   var email = ReadValsFromCookie("email")
//   // alert("email :" + email);
//   alert("language :" + language)
//   
//    
//   // var part_value = "{$CADENAS_DATA/23d-libs/univer/cylinders/m/m_asy.prj},{SR=M},{TYP=2},{TYP1=01},{HUB=100},{HUBST=20},{OPT=M}"
// 
//   window.frames['IFrame1'].OrderFromPARTserver(part_values,language);
// }
// // ----------------------------------------------------------------------------


