﻿// framework/utils.js
// litle helpers-collection
// Copyright (c) by IM-Systems 2007
// ---------------------------------------- 
// 15.08.2007 MPI created
// 04.09.2008 CKE openDLG(),requestTextLine()

var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
var rootfolder = getWebRoot();
//var arrowimg = createArrowImg();
var comphome = "bosch.de";
var comphome1 = "com.";
var transtags = "|SPAN|TD|LABEL|LI|BUTTON|A|P|H1|H2|H3|H4|H5|H6|OPTION|";
var translng = "";

/**
  * close / open the campus-flash-object
  */
function toggleCampus(obj) 
{
  var campusdiv = document.getElementById("teaserDIV");
  var ximg = document.getElementById("ximg");
  if (campusdiv) {
    campusdiv.style.display = (obj.src.indexOf("/img_shared/plus.png") > 0 ? "block" : "none");
  }
  obj.src = (obj.src.indexOf("img_shared/minus.png") > 0 ? obj.src.replace("minus.png", "plus.png") : obj.src.replace("plus.png", "minus.png"));
} // toggleCampus

/**
  * Get the current webroot folder.
  * @returns virtual root
  * @example "/imsite";
  */
function getWebRoot() 
{
  var allscripts = document.getElementsByTagName("script");//.scripts;
  var s = "";
  var vpath = "/portal";
  for (var n = 0; n < allscripts.length; n++) {
    s = allscripts[n].src;
    if ((s != null) && (s.length >= 19) && (s.substr(s.length - 19).toLowerCase() == "/framework/utils.js")) {
      vpath = s.substr(0,s.length - 19);
    }
  } // for

  return (vpath);
} // getWebRoot


/**
  * Get the url to the localpath and entrypage.
  * @param localpath
  * @param entrypage
  * @returns url with protocol
  * @example "http://www.google.de";
  */
function shareOrWeb(localpath, entrypage)
{
   var linkpath = "share/" + localpath + "/" + entrypage;

  if (!localpath) {
    localpath = entrypage;
    entrypage = "";
  }
  entrypage = (entrypage.length > 0 ? "/" + entrypage : "");
  localpath = localpath + entrypage;
  if (localpath.indexOf("http") == 0) {
    linkpath = localpath;
  } else if (localpath.indexOf("www.") == 0) {
    linkpath = "http://" + localpath;
  }
  return (linkpath);
} // shareOrWeb


/** Retrieving a state-value of a web page. This value can be recalled only
  * when the user navigates back or forward to this page.
  * <input type="hidden" name='imsstate'>
  * @param aName string the name of the value to store.
  * @return string the value to store or null, if no state is supported.
function getState (aName)
{
  var stateItem = window.document.getElementsByName("imsstate");
  var n, vals, val;
  var result = null;

  if (stateItem.length > 0) {
    result = "";
    vals = (stateItem[0].value).split('&');
    for (n = 0; n < vals.length; n++) {
      val = vals[n].split('=');
      if (val[0] == aName) {
        result = unescape(val[1]);
        break;
      } // if
    } // for
  } // if
  return (result);
} // getState
*/


/**
  * set the masterpage for the current role.
  * @mpage masterpagefile: tutor, user or admin
  */
function setCookie(mpage)
{
  createCookie('MASTER', mpage, 2);
  window.location.href = window.location.href;
  //window.location.reload();
} // setCookie


/**
  * create a new service track for the current page.
  * @param url 
  * @return module: "CNT" Content,
  *                 "LMS" LMS,
  *                 "PTL" Portal,
  *                 "RMS" Ressourcen-Manager,
  *                 "SVC" Service,
  *                 "TRL" Übersetzung,
  *                 "UMS" User-Manager
  */
function getModule(pageurl)
{
  var module = "PTL";
  var url = pageurl ? pageurl : window.location.href;
  
  url = url.toLowerCase();
  if (url.indexOf("/_lng_") > 0) {
    module = "TRL";
  } else if (url.indexOf("/lms") > 0) {
    module = "LMS";
  } else if (url.indexOf("/rm") > 0 || url.indexOf("/at/") > 0) {
    module = "RMS";
  } else if (url.indexOf("/serve") > 0) {
    module = "SVC";
  } else if (url.indexOf("/user") > 0 || url.indexOf("/um/") > 0) {
    module = "UMS";
  } else if (url.indexOf("/content") > 0) {
    module = "CNT";
  }
  
  return (module);
} // getModule


/**
  * get the url for a new service track for the current page.
  *
  */
function getServeUrl(webroot, pagetitle)
{
  var serveurl = window.location.href;
  var modul = getModule(serveurl);
  var servename = pagetitle;
  
  serveurl = encodeURIComponent(serveurl);
  servename = servename.replace("Power Tools Learning Campus: ", "");
  serveurl = webroot + "serve/serve.aspx?SERVEURL=" + serveurl + "&TYPE=W&STATE=1&PRIO=L&MODUL=" + getModule() + "&SERVENAME=" + servename;

  return (serveurl);
} // createServe



/** 
  * Entfernt führende und schließende Leerzeichen bei einem String.
  * @param txt String mit optionalen Leerzeichen am Anfang und Ende.
  * @return String ohne führende und schließende Leerzeichen.
  */
function trimStr(txt)
{
  if (txt != null) {
    txt = String(txt);
    txt = txt.replace(/^[\s\xA0]+/, "");
    txt = txt.replace(/[\s\xA0]+$/, "");
  }
  return(txt);
} // trimStr


/**
  * get the rounded size of a file
  * param size in bytes
  * @returns rounded size in bytes, KB or MB
  */
function formatFileSize(size)
{
  var kilobyte = 1024;
  var megabyte = 1024 * 1024;
  var ret = "";
  
  if (size) {
    ret = parseInt(size);
    if (size < kilobyte) {
      ret = size + " Bytes";
    } else if (size < megabyte) {
      ret = Math.ceil(size / kilobyte) + " kB";
    } else {
      ret = Math.ceil(size / megabyte) + " MB";
    }
  }
  
  return (ret);
} // formatFileSize


/**
  * create the arrow image used in the blue boxes once.
  * a clone of it will be used in the blue boxes.
  * @returns image object
  */
function createArrowImg() 
{
  if (!arrowimg) {
    arrowimg = window.document.createElement("img");
    arrowimg.style.className = "blueArrow";
    arrowimg.src = rootfolder + "/images/img_shared/arrow_8x7_blue.png";
    
  }
  
  return (arrowimg);
} // createArrowImg


/**
  * get the mime specific download type
  * @param mime: mime type
  */
function getDownloadMime(mime)
{
  var archivemime = "";
  
  switch (mime) 
  {
    case "html":
      archivemime = "zip";
      break;
    case "aspx":
      archivemime = "zip";
      break;
    case "asp":
      archivemime = "zip";
      break;
    case "ppt":
      archivemime = "zip";
      break;
//    case "swf":
//      archivemime = "swf";
//      break;
//    case "wmv":
//      archivemime = "wmv";
//      break;
//    default:
//      archivemime = "xxx";
//      break;
    default:
      archivemime = mime;
      break;
  }
  
  return (archivemime);
} // getDownloadMime


/**
  * translate untranslated stuff on runtime.
  * ALT + doubleclick on the sentence to translate. 
  */
function transIt()  
{
  var e = window.event.srcElement;

  if (window.event.altKey) {
    transPopup(e.innerText);
    window.event.returnValue = false; 
  }
} // transIt


/**
  * translate untranslated stuff on runtime.
  * ALT + doubleclick on the sentence to translate. 
  */
function transPopup(transtext)  
{
  translng = document.cookie.substring(document.cookie.indexOf("LNG=")+4).split(';')[0];
  //var win = window.open("http://www.mirror.im-systems.de/bosch/default.aspx?lng=de", "_trans", "width=940px,height=620px,toolbar=yes,location=yes,directories=yes,scrollbars=yes,status=yes,menubar=yes,resizable=yes");
  
  var transurl = getWebRoot() + "/transloc/lngobj.aspx?_trans=";
  var filename = window.location.href.split("?")[0].split("#")[0];
  var win = window.open(transurl + transtext + "&_LNG=" + translng + "&_FILENAME=" + filename, "_trans", "width=750px,height=420px,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes");
  win.focus();
} // transPopup


// cross browser compatible helper to register for events
function AttachEvent(obj, eventname, handler) 
{
  if (isIE) {
    obj.attachEvent(eventname, handler);
  } else { 
    obj.addEventListener(eventname.substr(2), handler, false);
  } // if
} // AttachEvent


if (typeof this.AttachEvent == "function") {
  this.AttachEvent(document, "oncontextmenu", this.transIt);
}


/**
  * set the most visited pages into the blue box
  * @param marginalobj: blue box object
  */
function tryContentPage(id, src, title, has_pop, pop_width, pop_height)
{
  if (this.loadContentPage) {
    loadContentPage(id, src, title, has_pop, pop_width, pop_height);
  } else {
    src = rootfolder + "/content.aspx#0.0.0.0." + id;
    //window.location.href = src;
    
    window.open(src, "_top", "status=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,resizable=yes");

  }
} // tryContentPage


/**
  * set a new line into the blue box
  * @param id: id of the page
  * @param src: relative path of the content
  * @param title: title of the content
  * @param marginalobj: blue box object
  * @param has_pop: content opens in own window
  * @param pop_height: content height from resource
  * @param pop_width: content width from resource
  */
function Dump(id, src, title, marginalobj, replace, has_pop, pop_width, pop_height)
{
  if (src && title) {
    var l = marginalobj.attributes["len"].value;
    var p = window.document.createElement("div");
    p.className = "itemMarginal";
//    var dumpimg = arrowimg.cloneNode(true);
//    img = p.appendChild(dumpimg);
    var a = window.document.createElement("a");
    a = p.appendChild(a);
    a.innerHTML = title;

    src = "share/" + src.replace(/\\/g, "/"); // wg.Umzug

    a.href = "javascript:tryContentPage(" + id + ", '" + src + "', '" + title + "', " + has_pop + ", '" + pop_width + "', '" + pop_height + "')";
    if (id == "") {
      p.style.display = "none";
    }
    marginalobj.appendChild(p);
    
    var alldivs = marginalobj.getElementsByTagName("div");
    if (replace && alldivs.length-1 > l) {
      marginalobj.removeChild(alldivs[1]);
    }
  }
  var ret = "";
//  if (alldivs && alldivs.length > 0) {
//    for (var z = 1; z < alldivs.length; z++) {
//    alert(alldivs[z].outerHTML);
//      ret += alldivs[z].outerHTML;
//    } // for
//  }
  
  return (ret);
} // Dump

/**
  * set a new line into the blue box
  * @param id: id of the page
  * @param src: relative path of the content
  * @param title: title of the content
  * @param marginalobj: blue box object
  */
function DumpNews(id, title, marginalobj)
{
  var l = marginalobj.attributes["len"].value;
  var p = window.document.createElement("div");
  p.className = "itemMarginal";
//  var newsimg = arrowimg.cloneNode(true);
//  img = p.appendChild(newsimg);

  //img.outerHTML = "<img width='8' height='7' border='0' alt='' src='images/img_shared/arrow_8x7_blue.png'/>";
  var a = window.document.createElement("a");
  a = p.appendChild(a);
  a.innerHTML = title;
  a.href = rootfolder + "/news.aspx?id=" + id;
  marginalobj.appendChild(p);
  // alert(p.parentElement.innerHTML);
  
  var alldivs = marginalobj.getElementsByTagName("div");
  if (alldivs.length-1 > l) {
    marginalobj.removeChild(alldivs[0]);
  }
  
  var ret = "";
  for (var z = 0; z < alldivs.length; z++) {
    ret += alldivs[z].outerHTML;
  }
  
  return (ret);
} // Dump


/**
  * set the most visited pages into the blue box
  * @param dumpobj: blue box object
  */
function DumpTopPages(dumpobj)
{
  if(dumpobj) {
    var l = dumpobj.attributes["len"].value;
    var toppageinfos = document.getElementById("topcontent").innerHTML.split("|");

    for (var i = 0; (i < l && i < toppageinfos.length); i++) {
      var pageinfo = toppageinfos[i].split(";");
      Dump (pageinfo[0], pageinfo[1], pageinfo[2], dumpobj, false, pageinfo[4], pageinfo[5], pageinfo[6]);
    } // for
  }
} // DumpTopPages


/**
  * set the last visited pages into the blue box
  * @param dumpobj: blue box object
  */
function DumpLastTitles(dumpobj)
{
  if(dumpobj) {
    var pageinfo;
    var l = dumpobj.attributes["len"].value;
    var lpi = proxies.DBUse.getLastPageInfos();
    if (lpi) {
      document.getElementById("lastpages").innerHTML = lpi;
      var lastpageinfos = lpi.split("|");
      for (var i = 0; i < l; i++) { 
        if (lastpageinfos[i]) {
          pageinfo = lastpageinfos[i].split(";");
          Dump (pageinfo[0], pageinfo[1], pageinfo[2], dumpobj, true, pageinfo[4], pageinfo[5], pageinfo[6]);
        } else {
          Dump ("", "", "", dumpobj, true);
        }
      } // for
    }
  }
  
  return (dumpobj.innerHTML);
} // DumpLastTitles


/**
  * set the most visited pages into the blue box
  * @param dumpobj: blue box object
  */
function DumpTopNews(dumpobj)
{
  if(dumpobj) {
    var l = dumpobj.attributes["len"].value;
    var lastnewsinfos = document.getElementById("lastnews").innerHTML.split("|");
    
    for (var i = 0; i < l; i++) {
      if (lastnewsinfos[i]) {
        var newsinfo = lastnewsinfos[i].split(";");
        DumpNews (newsinfo[0], newsinfo[1], dumpobj);
      }
    } // for
  }
} // DumpTopPages


function getLastChild(obj) 
{
  var ret = obj.lastChild;
  while (ret.nodeType != 1) {
    ret = ret.previousSibling;
  }
  return ret;
}


/**
  * set a cookie for the current webclient.
  * @param name: name of the cookie
  * @param val: value of the cookie
  * @param days: expire days
  */
function createCookie(name, val, days) 
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
  } else {
    expires = "";
  }
  document.cookie = name + "=" + val + expires + "; path=/";
} // createCookie


//function readCookie(name) 
//{
//  var nameEQ = name + "=";
//  var ca = document.cookie.split(';');
//  for(var i=0;i < ca.length;i++) {
//    var c = ca[i];
//    while (c.charAt(0)==' ') c = c.substring(1,c.length);
//    if (c.indexOf(nameEQ) == 0) 
//      return c.substring(nameEQ.length, c.length);
//  }
//  return null;
//}


/**
  * change the current portal language
  * @param lng: culture info like "en-US", "de-DE", ...
  */
function changeLng(lngcty) {
  var lc, lng, cty;
  var char = lngcty.indexOf('-');
  lc = (lngcty.length > 2 && char > 0) ? lngcty : _utils_const_.lngcty;
  lngcty = lc;

  lng = lngcty.split('-')[0];
  cty = lc.substr(char + 1).toUpperCase();
  proxies.DBUse.SetSessionLngCty(lngcty);
  createCookie("LNG", lng, 2);
  createCookie("CTY", cty, 2);
  window.location.reload();
}  // changeLng


/**
  * sets the checked attribute.
  * @param obj: checkbox object of the table head.
  * @param tabid id of the parent object.
  */
function changeall(obj, tabid)
{
  var tabobj = (tabid ? document.getElementById(tabid) : document) ;
  var cbx = tabobj.getElementsByTagName("INPUT");
  
  for (var i = 0; i < cbx.length; i++) {
    cbx[i].checked = obj.checked;
  }
} // changeall


/**
  * sets the checked attribute betwenn two checkboxes.
  * @param tabid id of the parent object.
  */
function changebetween(tabid)
{
  var tabobj = (tabid ? document.getElementById(tabid) : document) ;
  var cbx = tabobj.getElementsByTagName("INPUT");
  var first = -1;
  var last = -1;
  
  for (var i = 0; i < cbx.length; i++) {
    if(cbx[i].checked && first == -1) {
      first = i;
    } else if(cbx[i].checked && first > -1 && last == -1) {
      last = i;
      break;
    }
  } // for
  
  for (var j = first; j < last; j++) {
    cbx[j].checked = true;
  } // for
  
} // changebetween


/**
  * Retrieve the ids of the selected rows of a *list-page.
  * @return checked id values.
  */
function getIdList()
{
  var idlist = "";
  var cbx = document.getElementsByTagName("INPUT");
  
  for (var i = 0; i < cbx.length; i++) {
    if (cbx[i].type == "checkbox") {
      if (cbx[i].checked) {
        idlist += cbx[i].id + ","
      } // for
    }
  } // for
  if (idlist.length > 0) {
    idlist = idlist.substring(1, idlist.length-1);
  }
  
  return(idlist);
} // getIdList


/**
  * Retrieve the ids of the selected rows of a *list-page.
  * @param tabid id of the parent object.
  * @param selVal = "id" or "name".
  * @return checked id values or names as list.
  */
function getTabIdList(tabid, selVal)
{
  var idlist = "";
  var tabobj = (tabid ? document.getElementById(tabid) : document) ;
  var cbx = tabobj.getElementsByTagName("INPUT");

  for (var i = 0; i < cbx.length; i++) {
    if (cbx[i].type == "checkbox") {
      if (cbx[i].checked) {
        if(selVal == "id") {
          idlist += cbx[i].id + ",";
        } else if (selVal == "pname") { // name.attribute FF
          idlist += (cbx[i].attributes["pname"] ? cbx[i].attributes["pname"].value + "," : "");
        } else { // name.attribute
          idlist += cbx[i].attributes["name"].value + ",";
        }
      } // if
    } // if
  } // for
  
  if (idlist.length > 0) {
    if(idlist.charAt(0) == ",") {
      idlist = idlist.substring(1, idlist.length-1);
    } else {
      idlist = idlist.substring(0, idlist.length-1);
    }
  } // if
  return(idlist);
} // getTabIdList


/**
  * delivers iconname by given type or url.
  * @param type resourcetype
  * @param url url of given file
  * @return iconname
  */
function resourceTypeIcon(type, url)
{
  var ret = "";

  switch (type) {
    case 0:
      ret = "default.png";
      break;
    case 1:
      ret = "wbt.png";
      break;
    case 2:
      ret = "link.png";
      break;
    case 3:
      ret = "wbt.png";
      break;
    case 4:
      ret = "forum.png";
      break;
    case 5:
      ret = "date.png";
      break;
    case 6:
      if (url.toLowerCase().indexOf(".doc") > -1) {
        ret = "doc";
      } else if (url.toLowerCase().indexOf(".xsl") > -1) {
        ret = "xls";
      } else if (url.toLowerCase().indexOf(".txt") > -1) {
        ret = "ascii";
      } else if (url.toLowerCase().indexOf(".zip") > -1) {
        ret = "images";
      } else if (url.toLowerCase().indexOf(".jpg") > -1) {
        ret = "images";
      } else if (url.toLowerCase().indexOf(".bmp") > -1) {
        ret = "images";
      } else if (url.toLowerCase().indexOf(".png") > -1) {
        ret = "images";
      } else if (url.toLowerCase().indexOf(".gif") > -1) {
        ret = "images";
      } else if (url.toLowerCase().indexOf(".php") > -1) {
        ret = "ascii";
      } else if (url.toLowerCase().indexOf(".pdf") > -1) {
        ret = "pdf";
      } else {
        ret = "download";
      }
      ret += ".png";
      break;
    case 7:
      ret = "local_website.png";
      break;
    case 8:
      ret = "query.png";
      break;
    case 9:
      ret = "project.png";
      break;
    default:
      ret = "default.png";
      break;
  } // switch

  return (ret);
} // resourceTypeIcon()


/**
  * delivers name by given type or url.
  * @param type resourcetype
  * @param url url of given file
  * @return iconname
  */
function resourceTypeName(type, url)
{
  var ret = "";

  switch (type) {
    case 0:
      ret = "Unbekannt";
      break;
    case 1:
      ret = "Scorm WBT";
      break;
    case 2:
      ret = "Link";
      break;
    case 3:
      ret = "Scorm WBT";
      break;
    case 4:
      ret = "Forum";
      break;
    case 5:
      ret = "Datum";
      break;
    case 6:
      if (url.toLowerCase().indexOf(".doc") > -1) {
        ret = "Worddokument";
      } else if (url.toLowerCase().indexOf(".xsl") > -1) {
        ret = "Exceldokument";
      } else if (url.toLowerCase().indexOf(".txt") > -1) {
        ret = "Text";
      } else if (url.toLowerCase().indexOf(".zip") > -1) {
        ret = "Image";
      } else if (url.toLowerCase().indexOf(".jpg") > -1) {
        ret = "Image";
      } else if (url.toLowerCase().indexOf(".bmp") > -1) {
        ret = "Image";
      } else if (url.toLowerCase().indexOf(".png") > -1) {
        ret = "Image";
      } else if (url.toLowerCase().indexOf(".gif") > -1) {
        ret = "Image";
      } else if (url.toLowerCase().indexOf(".php") > -1) {
        ret = "Programmtext";
      } else if (url.toLowerCase().indexOf(".pdf") > -1) {
        ret = "Pdf-Datei";
      } else {
        ret = "Download";
      }
      break;
    case 7:
      ret = "Lokale Website";
      break;
    case 8:
      ret = "Test";
      break;
    case 9:
      ret = "Projekt";
      break;
    default:
      ret = "Unbekannt";
      break;
  } // switch

  return (ret);
} // resourceTypeName()


/** translate a pseudo url like ~/folder/page.aspx or /./folder/page.aspx to a
  * absolute url notation.
  */
function absoluteUrl(aUrl)
{
  if ((aUrl != null) && (aUrl.length > 2)) {
    if (aUrl.substr(0, 3) == "/./")
      aUrl = location.href.split("/").slice(0,4).join("/") + aUrl.substr(2);
    else if (aUrl.substr(0, 2) == "~/")
      aUrl = location.href.split("/").slice(0,4).join("/") + aUrl.substr(1);
    else if (aUrl.substr(0, 18) == "http://server/web/")
      aUrl = location.href.split("/").slice(0,4).join("/") + aUrl.substr(17);
    else if (aUrl.charAt(0) == "/")
      aUrl = location.href.split("/").slice(0,3).join("/") + aUrl;
  }
  return(aUrl);
} // absoluteUrl


/** Opens a dialog.
  * @param url for the opening page
  * @param params for the dialog
  * @param winopts optional window-Parameters
  * @return DLG-result.
  */
function openDLG(url, params, winopts)
{
  var opts = "resizable:0;status:0;";
  var ret = "";

  if (document.body.macroMode == "true") {
    opts += "center:0;dialogLeft:1;";
  } // if

  if (winopts != null) {
    opts += winopts;
  }

  ret = window.showModalDialog(absoluteUrl(url), params, opts);
  
  if(ret != null && typeof(ret) == "string") {
    ret = ret.replace(/ *$/, "");
  }
  return(ret); 
} // openDLG


/** Opens a dialog for returning a usertext.
  * @param title windowtitle
  * @param defaults default text
  * @return text or null
  */
function requestTextLine(title, defaults) 
{
  var ret;
  var p = new Object();

  p.title = title;
  p.txt = defaults;

  ret = openDLG("../framework/requestTextLine.htm", p, "resizable:0;dialogWidth:100px;dialogHeight:60px;");
  return(ret); 
} // requestTextLine


/**
  * Set the background color for the left navigation part 
  * by using the runtime height.
  */
function colorMasterNav() 
{
  var accordionNav = document.getElementById("leftrootnav");
  if (accordionNav) {
    accordionNav.style.height = document.getElementById("root").offsetHeight;
  }
} // colorMasterNav


/**
  * dynamic change of class properties.
  * @param dotclassname: classname of the HTMLtag like .FFRAME
  * @param attr: attribute to set or change
  * @param val: attribute value
  * http://www.shawnolson.net/a/503/altering-css-class-attributes-with-javascript.html
  */
function changeCSS(dotclassname, attr, val) 
{
  var cssRules;
  var added = false;

  for (var i = 0; i < document.styleSheets.length; i++) {
    if (document.styleSheets[i]['rules']) {
      cssRules = 'rules';
    } else if (document.styleSheets[i]['cssRules']) {
      cssRules = 'cssRules';
    } else {
      //no rules found... browser unknown
    }

    for (var k = 0; k < document.styleSheets[i][cssRules].length; k++) {
      if (document.styleSheets[i][cssRules][k].selectorText == dotclassname) {
        if(document.styleSheets[i][cssRules][k].style[attr]) {
          document.styleSheets[i][cssRules][k].style[attr] = val;
          added = true;
          break;
        }
      }
    } // for
    
    if(!added) {
      if(document.styleSheets[i].insertRule) {
        document.styleSheets[i].insertRule(dotclassname + ' { ' + attr + ': '+ val + '; }', document.styleSheets[i][cssRules].length);
      } else if (document.styleSheets[i].addRule) {
        document.styleSheets[i].addRule(dotclassname, attr + ': ' + val + ';');
      }
    } else {
      break;
    }
  } // for
} // changeCSS


/**
  * is called from setIframeSrc()
  * set the src value for the current active folder.
  * @param tabname: name of the depending table
  */
function setFolderISrc(tabname, isFrame)
{
  var idName = isFrame ? "folder" : "ctl00_ContentPlaceHolder1_folder";
  //Fallback if FrameSetMasterPage used
  if (!$('#' + idName).lenght) {
    idName = 'ctl00_ContentPlaceHolder1_folder';
  }

  var activenr = document.getElementById(idName).activenr;
  var _folders = document.getElementById(idName)._folders;
  var i;
  var iframeobj = null;
  tabname = tabname.toUpperCase();
  var datasetid = document.getElementById("_" + tabname + "ID").value;

  if (datasetid) {
    for(i = 0; i < _folders.length; i++) {
      if (i == activenr) {
        var ilist = _folders[i].getElementsByTagName("iframe");
        if (ilist.length > 0) {
          try { // FF
            // no refresh for the same src
            var fsrc = (ilist[0].framesrc ? ilist[0].framesrc : ilist[0].attributes["framesrc"].value);
            if (fsrc && ilist[0].src.indexOf(fsrc + tabname + "ID=" + datasetid) < 0) {
              ilist[0].src = fsrc + tabname + "ID=" + datasetid;
              iframeobj = ilist[0];
            }
          } catch (e) {}
        }
      }
    } // for
  }
  
  return (iframeobj);
} // setFolderISrc


/**
  * is called from setIframeSrcDirect()
  * set some src values for the current active folder.
  * @param someVals: any values or empty string ( be careful! )
  */
function setFolderISrcDirect(someVals)
{
  var idName = (false ? "folder" : "ctl00_ContentPlaceHolder1_folder");
  var activenr = document.getElementById(idName).activenr;
  var _folders = document.getElementById(idName)._folders;
  var i;
  var iframeobj = null;

  if (_folders) {
    for (i = 0; i < _folders.length; i++) {
      if (i == activenr) {
        var ilist = _folders[i].getElementsByTagName("iframe");
        if (ilist.length > 0) {
          try { // FF
            // no refresh for the same src
            var fsrc = (ilist[0].framesrc ? ilist[0].framesrc : ilist[0].attributes["framesrc"].value);
            if (fsrc && ilist[0].src.indexOf(fsrc + someVals) < 0) {
              ilist[0].src = fsrc + someVals;
              iframeobj = ilist[0];
            }
          } catch (e) {}
        }
      }
    } // for
  }
  
  return (iframeobj);
} // setFolderISrcDirect


/**
  * can be called from any Recordpage with DateInputfields.
  * set the single date to sqlform before insert or update database.
  * caution: ../framework/formatdate.js must be included in the Recordpage!
  * @param dateNameList: name of the dateinputfields (name1,name2,...)
  * @param compcty: selected country
  * @param bBirthday: Birthday true, false
  */
function prepDatesToSql(dateNameList, compcty, bBirthday)
{
  var aDate, fName;
  var arrList, tmpArr;
  var i, y, m, d;

  if (dateNameList != null && dateNameList.length > 0) {
    arrList = dateNameList.split(",");
    
    for(i = 0; i < arrList.length; i++) { 
      fName = arrList[i]; 
      aDate = document.getElementById(fName).value;

      if (aDate != null && aDate != "") {
        if (aDate.indexOf("*") > -1) {
          aDate = new Date();
          aDate = formatDate(aDate, "yyyyMMdd");
        
        } else if(aDate.indexOf(".") > -1) { // Annahme: de,eu
          aDate = aDate.replace(/\-/g, ".").replace(/\//g, ".");
          tmpArr = aDate.split("."); 
          y = parseInt(tmpArr[2], 10);
          if(y < 100 && !bBirthday) {
           y += 2000;
          }
          m = parseInt(tmpArr[1], 10) - 1;
          d = tmpArr[0];
          aDate = new Date(y, m, d);
          aDate = formatDate(aDate, "yyyyMMdd"); 
        
        } else if(aDate.indexOf("/") > -1) { // Annahme: us oder en
          aDate = aDate.replace(/\./g, "/").replace(/\-/g, "/");
          tmpArr = aDate.split("/"); 

          // en oder us?
          if(compcty.toLowerCase().indexOf("us") > -1) { 
            y = parseInt(tmpArr[2], 10);
            if(y < 100 && !bBirthday) {
             y += 2000;
            }
            m = parseInt(tmpArr[0], 10) - 1;
            d = tmpArr[1];
          } else { // en
            y = parseInt(tmpArr[2], 10);
            if(y < 100 && !bBirthday) {
             y += 2000;
            }
            m = parseInt(tmpArr[1], 10) - 1;
            d = tmpArr[0];
          } // if
          aDate = new Date(y, m, d);
          aDate = formatDate(aDate, "yyyyMMdd"); 
        
        } else if(aDate.indexOf("-") > -1) { // Annahme: ?
          aDate = aDate.replace(/\./g, "-").replace(/\//g, "-");
          tmpArr = aDate.split("-"); 
          y = parseInt(tmpArr[2], 10); // year = index 2 ?
          if(y < 100 && !bBirthday) {
           y += 2000;
          }
          m = parseInt(tmpArr[1], 10) - 1;
          d = tmpArr[0];
          aDate = new Date(y, m, d);
          aDate = formatDate(aDate, "yyyyMMdd"); 
        
        } else if(aDate.length == 6) {
          y = parseInt(aDate.substr(4, 2), 10);
          if(y < 100 && !bBirthday) {
           y += 2000;
          }
          aDate = new Date(y, parseInt(aDate.substr(2, 2), 10)-1, parseInt(aDate.substr(0, 2), 10));
          aDate = formatDate(aDate, "yyyyMMdd"); 
        
        } else if(aDate.length == 8) {
          aDate = new Date(parseInt(aDate.substr(4, 4), 10), parseInt(aDate.substr(2, 2), 10)-1, parseInt(aDate.substr(0, 2), 10), 0, 0, 0);
          aDate = formatDate(aDate, "yyyyMMdd"); 
        }  
        
        if(aDate != null && aDate.indexOf("NaN") < 0) {
          document.getElementById(fName).value = aDate;
        } else {
          document.getElementById(fName).value = "";
        }
        
      } else {
        document.getElementById(fName).value = "";
      }
    } // for
  } // if
} // prepDatesToSql
  

// from formatdate.js...
var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) {
		  return false;
    }
	}
	return true;
} // _isInteger


function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) {
		  return null;
		}
		if (_isInteger(token)) {
		  return token;
		}
  }
	return null;
} // _getInt

function LZ(x) {
  return (x < 0 || x > 9 ? "" : "0") + x;
}

// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";

	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
		}
		
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") {
			  x=4;
			  y=4;
			}
			if (token=="yy") {
			  x=2;
			  y=2;
			}
			if (token=="y") { 
			  x=2;
			  y=4;
			}
			year = _getInt(val,i_val,x,y);
			if (year==null) {
			  return 0;
			}
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) {
				  year=1900+(year-0);
				}	else {
				  year=2000+(year-0);
				}
		  }
		}	else if (token=="MMM"||token=="NNN") {
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val, i_val + month_name.length).toLowerCase() == month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) {
						  month -= 12;
						}
						i_val += month_name.length;
						break;
					}
				}
			}
			if ((month < 1) || (month > 12)) {
			  return 0;
	  	}
		} else if (token=="EE" || token=="E") {
			for (var i=0; i < DAY_NAMES.length; i++) {
				var day_name = DAY_NAMES[i];
				if (val.substring(i_val, i_val+day_name.length).toLowerCase() == day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
				}
			} // for
		} else if (token=="MM" || token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null || (month<1) || (month>12)) {
			  return 0;
			}
			i_val+=month.length;
		} else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null || (date<1) || (date>31)) {
			  return 0;
			}
			i_val+=date.length;
		}	else if (token=="hh" || token=="h") {
			hh = _getInt(val, i_val, token.length, 2);
			if(hh==null || (hh < 1) ||(hh > 12)) {
			  return 0;
			}
			i_val+=hh.length;
		}	else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null || (hh < 0) || (hh > 23)) {
			  return 0;
			}
			i_val+=hh.length;
		}	else if (token=="KK" || token=="K") {
			hh= _getInt(val, i_val, token.length, 2);
			if(hh==null || (hh < 0) || (hh > 11)) {
			  return 0;
			}
			i_val+=hh.length;
		}	else if (token=="kk" || token=="k") {
			hh= _getInt(val, i_val, token.length, 2);
			if(hh==null || (hh < 1) || (hh > 24)) {
			  return 0;
			}
			i_val+=hh.length;hh--;
		}	else if (token=="mm" || token=="m") {
			mm= _getInt(val, i_val, token.length, 2);
			if(mm==null || (mm < 0) ||(mm > 59)) {
			  return 0;
			}
			i_val+=mm.length;
		}	else if (token=="ss" || token=="s") {
			ss= _getInt (val, i_val, token.length, 2);
			if(ss==null || (ss < 0) || (ss > 59)) {
			  return 0;
			}
			i_val+=ss.length;
	  }	else if (token=="a") {
			if (val.substring(i_val, i_val+2).toLowerCase()=="am") {
			  ampm="AM";
			}	else if (val.substring(i_val, i_val+2).toLowerCase()=="pm") {
			  ampm="PM";
			}	else {
			  return 0;
			}
			i_val+=2;
	  }	else {
			if (val.substring(i_val, i_val+token.length)!=token) {
			  return 0;
			}	else {
			  i_val+=token.length;
			}
		}
	} // while
	
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) {
	  return 0;
	}
	
	// Is date valid for month?
	if (month == 2) {
		// Check for leap year
		if (((year % 4 == 0) && (year % 100 != 0) ) || (year % 400==0) ) { // leap year
			if (date > 29) {
			  return 0;
			}
		}	else {
		  if (date > 28) {
		    return 0;
		  }
  	}
	}
	
	if ((month==4) || (month==6) || (month==9) || (month==11)) {
		if (date > 30) {
		  return 0;
		}
	}
	
	// Correct hours value
	if (hh < 12 && ampm=="PM") {
	  hh = hh - 0 + 12; 
	}	else if (hh > 11 && ampm == "AM") {
	  hh -= 12;
	}
	
	var newdate = new Date(year, month-1, date, hh, mm, ss);
	//return newdate.getTime();
	return newdate;
} // getDateFromFormat


// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date, format) {
	format=format+"";
	
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	
	if (y.length < 4) {
	  y= "" + (y-0+1900);
	}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1]; 
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H == 0) {
	  value["h"]=12;
	}	else if (H > 12){
	  value["h"]=H-12;
	}	else {
	  value["h"]=H;
	}
	value["hh"]=LZ(value["h"]);
	if (H > 11) {
	  value["K"]=H-12;
	} else {
	  value["K"]=H;
	}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) {
	  value["a"]="PM";
	}	else {
	  value["a"]="AM";
	}
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
	  }
		if (value[token] != null) { 
		  result=result + value[token];
		} else { 
		  result=result + token;
	  }
	}
	return result;
} // formatDate

  




////////////////// EXTERNAL HEADER FUNCTIONS ///////////////////////////////

var ex = null;

/**
  * open the language specific web assistant.
  */
function openWebassistant()
{
  var popurl = "";
  try {
      switch (compcty) {
        case "jp":
        popurl = "http://servicefunctions.bosch.com/user/webassistant/search.asp?country=jp&lang=ja";
        break;
      default:
        popurl = "http://servicefunctions.bosch.com/user/webassistant/search.asp?country=" + compcty + "&lang=" + complng;
        break;
    }
    
    window.open(popurl, "wa", "width=564,height=528,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=no");
  } catch(ex) {
    /* TODO */
  }
} // openWebassistant


/**
  * diffrent urls for some countries.
  */
function openContact()
{
  var popurl = "";
  
  try {
    switch (compcty) {
        case "jp":
        popurl = "https://ssl.bosch.com/jp/contact/";
        break;
      case "cn":
        popurl = "http://header.bosch.com.cn/web/site/dealer_locator.jsp?lan=" + complng + "-" + compcty.toUpperCase();
        break;
      case "xx":
        popurl = "https://ssl.bosch.com/xx/contact/xx.php";
        break;
      case "br":
        popurl = "http://www.bosch.com.br/br/contato/index.html?lang=" + complng;
        break;
      default:
        popurl = "http://servicefunctions.bosch.com/user/contactdealer/index.asp?country=" + compcty + "&lang=" + complng + "&app=contact";
        break;
    }
    
    window.open(popurl, "contact", "width=564,height=528,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes");
  } catch(ex) {
    /* TODO */
  }
} // openContact


/**
  * open the language specific dealer.
  */
function openSource()
{
  var popurl = "";
  
  try {
      switch (compcty) {
      case "jp":
        popurl  = "http://www.bosch.co.jp/jp/header/dealer_locator/";
        break;
      case "cn":
        popurl = "http://header.bosch.com.cn/web/site/dealer_locator.jsp?lan=zh_CN"; 
        break;
      default:
        popurl = "http://servicefunctions.bosch.com/user/contactdealer/index.asp?country=" + compcty + "&lang=" + complng + "&app=dealer";
        break;
    }
    window.open(popurl, "dealer", "width=564,height=528,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes");
  } catch(ex) {
    /* TODO */
  }
} // openSource


/**
  * open the language specific newsletter abo.
  */
function openNewsletter()
{
  var popurl = "";
  
  try {
    switch (compcty) {
      default:
        popurl = "http://www.newsletter-bosch.com/index.cfm?fuseaction=subnew&l=3&cl=" + complng + "-" + compcty.toUpperCase();
        break;
    }        
    window.open(popurl, "newsletter", "width=787,height=700,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes");
  } catch(ex) {
    /* TODO */
  }
} // openNewsletter


/**
  * open the language specific about popup.
  */
function openAbout()
{
  var popurl = "";
  
  try {
    switch (complng) {
      case "de":
        popurl = "http://www.bosch.com/content/language1/html/1062.htm";
        break;
      default:
        popurl = "http://www.bosch.com/content/language2/html/1062.htm";
        break;
    }        
    window.open(popurl, "newsletter", "width=420,height=600,toolbar=no,location=no,directories=no,scrollbars=yes,status=no,menubar=no,resizable=yes");
  } catch(ex) {
    /* TODO */
  }
} // openAbout


function countChars(str, c)
{
  var pos = 0;
  var counter = 0;

  while (pos >= 0) {
    pos = str.indexOf(c, pos);
    if (pos != -1) {
      counter += 1;
      pos += 1;
    }
  } // while
  return(counter);
} // countChars


/**
 * prepare the current Date as
 *
 * @param asSqlDate true/false
 * @return Date as "dd.mm.yyyy" or
 * @return Date as "yyyy-mm-dd"
 */
function getDate(asSqlDate)
{
  var s = "", t = "";
  var d = new Date(); 

  if(! asSqlDate) {
    t = d.getDate();
    s += (t < 10 ? "0" + t : t) + "."; 
    t = (d.getMonth() + 1);
    s += (t < 10 ? "0" + t : t) + "." + d.getYear(); 
  } else {
    s += d.getYear();
    t = (d.getMonth() + 1);
    s += "-" + (t < 10 ? "0" + t : t); 
    t = d.getDate();
    s += "-" + (t < 10 ? "0" + t : t); 
  }
  return(s);
} // getDate

/**
* utils constantes
**/
var _utils_const_ = {
  dateformat: 'dd.mm.yyyy', // default
  jquilocale: null,
  lngcty: 'de-DE' // default
};

/**
* init the date format
* @param dtformat: date format i.e. dd.mm.yyyy or yy-mm-dd or ...
*/
function setDateFormat(dtformat) {
  _utils_const_.dateformat = dtformat;
}
