/////////////////////////////////////////////////////////
//  FILENAME    : global.js
//  COPYRIGHT   :
//  AUTHOR      : Gunther Berner
//  DESCRIPTION : Globle JavaScriptFunktionen




/////////////////////////////////////////////////////////
//  Funktionsname    : getSelection
//  Kurzbeschreibung : ermittelt aus einem Checkbox - Feld
//                     alle angehakten Values und schreibt diese
//                     Kommasepariert in eine HiddenInputbox
//  >  : String Formular_Name
//  >  : String CheckBoxFeld_Name
//  >  : String HiddenInputBox_Name
/////////////////////////////////////////////////////////
window.onload = OnLoad;
bFormEditMode = true;

//try{
//  if(!debug){
//    window.document.onselectstart = selstarthandler;
//  }
//}catch(exeption){
//
//}




//function selstarthandler(){
//  if(!window.event.srcElement.name){  // nur elemente die einen einen namen haben dürfen selectiert werden
//    return false;
//  }
//  return true;
//}

function OnLoad(){
  DoReload = getParam("ReloadAll");
  if(DoReload){
    top.location.reload();
  }
  py = getParam("Y");
  if(py != ""){
    window.scrollTo(0,py);
  }
  inittwdragging();
  //stopp();
}
function disableMainForm(){
  aElements = mainform.elements;
  var f;
  for(f=0;f<aElements.length;f++){
    if(!aElements[f].letItBe){aElements[f].disabled=true};
  }
  aLinks = document.links;
  for(f=0;f<aLinks.length;f++){
    if(aLinks[f].formelement){
      aLinks[f].firstChild.style.visibility = "hidden";
      aLinks[f].style.cursor = "default";
      aLinks[f].href="javascript://";
    }
  }
  bFormEditMode = false;
}


function convertK2P(element){
  element.value = element.value.replace(/,/g,".");
  if(isNaN(element.value) && element.value != ""){
    alert("Dieses Feld muß einen numerischen Wert enthalten!")
    element.focus();
    element.select();

    return false;
  }
}

function ensure(s){
  return escape(s).replace(/\+/g,"%2b");
}

function LinkScrl( sLocation ){
  nY = parseInt(document.all ? document.body.scrollTop : window.pageYOffset);
  location.href = sLocation + "&Y=" + nY;
}

function ScrlParam(){
  nY = parseInt(document.all ? document.body.scrollTop : window.pageYOffset);
  return nY;
}

function sortList( sListID, sFieldName ){
  nY = parseInt(document.all ? document.body.scrollTop : window.pageYOffset);
  sLink = location.href;
  // giebt es einen SortierParameter
  sSortField = getParam( sListID + "SortField" );
  bSortDesc = getParam( sListID + "SortDesc" )
  // nachschauen, ob ein QS da ist
  pos =  sLink.search(/\?/);
  if( pos == -1 ){
    sLink = sLink + "?";
  }

  if( sFieldName == sSortField && bSortDesc != '1' ){
    // Sort Desc
    sLink = sLink + "&" + sListID + "SortDesc=1";
  }else{
    // normale Sortierung
    RE = eval( "/" + sListID + "SortField/"  );
    pos = sLink.search( RE );
    if( pos != -1 ){
      // alte Parameter aus QS entfernen
      RE = eval( "/(&)(" + sListID + "SortField=)([^&]*)/g" );
      sLink = sLink.replace( RE, "" );
      RE = eval( "/(&)(" + sListID + "SortDesc=1)/g" );
      sLink = sLink.replace( RE, "" );
    }
    sLink = sLink + "&" + sListID + "SortField=" + sFieldName;
  }
  location.href = sLink.replace(/&Y=[^&]*/g, "") + "&Y=" + nY;;
}


/////////////////////////////////////////////////////////
//  Funktionsname    : getKeys
//  Kurzbeschreibung : ermittelt aus einem Checkbox - Feld
//                     alle angehakten Values und gibt diese
//                     [strSplitItem] separiert zurück
//  >  : String CheckBoxFeld-Object
//  >  : String Separator
/////////////////////////////////////////////////////////
function getKeys( objCheckBoxField , strSplitItem ){
  buf = "";
  le = objCheckBoxField.length;
  if(!le){
    // es ist nur ein Element (Liste mit einem Datensatz)
    if( objCheckBoxField.checked ){
      return objCheckBoxField.value;
    }else{
      return '';
    }
  }
  for (f=0;f<le;f++){
    if (objCheckBoxField[f].checked == true){
      buf += objCheckBoxField[f].value + strSplitItem;
    }
  }
  if (buf.length > 1){
    buf = buf.slice( 0, buf.length - strSplitItem.length );
  }
  return buf;
}


// Test ob das auch geht
function ChangeRowColor(objRow,objChk){
  if(objChk.checked == true){
    //objRow.bgColor="#99ccff";
    objRow.className = "FormText";
  }else{
    objRow.className = "ListText";
    //objRow.bgColor="#aaaabc";
  }
  return;
}

function InvertSelection(objChkField){
  if(!objChkField){return;} // Fehler abfangen (Liste ist leer)
  if(objChkField.length){
    for(f=0;f<objChkField.length;f++){
      if(objChkField[f].checked == true){
        objChkField[f].checked = false;
      }else{
        objChkField[f].checked = true;
      }
    }
  }else{
    // es gibt nur ein Element in der Liste
    if(objChkField.checked == true){
      objChkField.checked = false;
    }else{
      objChkField.checked = true;
    }
  }

}

/////////////////////////////////////////////////////////
//  Funktionsname    : limitSize
//  Kurzbeschreibung : begrenzt Zeichen
//
//
/////////////////////////////////////////////////////////

function limitSize(objTextarea){
  Size = objTextarea.value.length;
  if(Size > 250){
    alert("Sie haben die Maximalanzahl an Zeichen überschritten!");
    Text = objTextarea.value;
    objTextarea.value = Text.slice(0,250);
  }
}



///////////////////////////////////////////////////////////////////
//  Funktionsname    : Screenshot-Funktion
//  Kurzbeschreibung : Schreibt HTML-Quelltext der
//                     angezeigten Seite in Inputfelder -> Adminframe
//                     Entfernt Links,JavaScripte und Submitbutton
//                     Öffnet Fenster mit Message-Formular               /(<script[^>]*>)((([^<][^\/][^s][^c][^r][^i][^p][^t][^>])*)|([^<]*[^\/]*[^s]*[^c]*[^r]*[^i]*[^p]*[^t]*[^>]))(<\/script>)/ig
//
///////////////////////////////////////////////////////////////////

function getSrcCode(){
  SrcCode = "<HTML>" + top.action.document.all.tags("html")[0].innerHTML + "</HTML>";
  admFrameCode = "<HTML>" + top.tree.document.all.tags("html")[0].innerHTML + "</HTML>";
  SrcCode = SrcCode.replace(/<script[^>]*>[^>]*t>/ig,"");
  SrcCode = SrcCode.replace(/(<a[^>]*>)([^<]*[^\/]*[^a]*[^>])(<\/a>)/ig,"$2");
  SrcCode = SrcCode.replace(/<script/ig,"<!-- script");
  SrcCode = SrcCode.replace(/<\/script>/ig,"</script-->");
  SrcCode = SrcCode.replace(/onclick/ig,"nix");
  SrcCode = SrcCode.replace(/onchange/ig,"nix");
  SrcCode = SrcCode.replace(/onsubmit/ig,"nix");
  SrcCode = SrcCode.replace(/onload/ig,"nix");
  SrcCode = SrcCode.replace(/submit/ig,"button");
  SrcCode = SrcCode.replace(/javascript:/ig,"javascript://");

  admFrameCode = admFrameCode.replace(/(<script>)[^<]*[^\/]*[^s]*[^c]*[^r]*[^i]*[^p]*[^t]*[^>](<\/script>)/ig,"");
  admFrameCode = admFrameCode.replace(/<script[^>]*><\/script>/ig,"");
  admFrameCode = admFrameCode.replace(/(<a[^>]*>)([^<]*[^\/]*[^a]*[^>])(<\/a>)/ig,"$2");
  admFrameCode = admFrameCode.replace(/javascript:/ig,"javascript://");
  top.tree.document.form.admFrameCode.value = admFrameCode;
  top.tree.document.forms[0].elements[0].value = SrcCode;
  Support = window.open("/system/usr_support_screenshot.html","Support","width=620,height=400,screenX=320,screenY=0,resizable=yes");
}


///////////////////////////////////////////////////////////////////
//  Funktionsname    : getParam
//  Kurzbeschreibung : gibt den Wert eines QueryStringParameters
//                     ( SParamName ) zurück
///////////////////////////////////////////////////////////////////
function getParam( sParamName ){
  sLocation = location.href;
  aLCQS = sLocation.split("?");
  if (aLCQS.length > 1){ // Es gibt ein QS
    aParams = aLCQS[1].split("&");
    for( f=0; f<aParams.length; f++ ){
      aParam = aParams[f].split("=");
      if( aParam[0] == sParamName ){
        return aParam[1]; // Den Wert zurück!!
      }
    }
  }
}

///////////////////////////////////////////////////////////////////
//  Funktionsname    : removeParam
//  Kurzbeschreibung : entfernt sParam aus QueryString
//
///////////////////////////////////////////////////////////////////
function removeParam( sParamName, sQS ){
  // RegExp zusammenbasteln
  RE = eval( "/([?&])(" + sParamName + "=[^&]*)/g" );
  // Param entfernen
  sQS = sQS.replace( RE, "$1" );
  // leere Param-Positionen entfernen
  sQS = sQS.replace( /&&/g, "&" );
  return sQS;
}


// Hängt nStellen "0" mit Komma drann, wenn nötig
function formatString( sFloat, nStellen ){
  sAdd = "";
  nPos = sFloat.indexOf(",");
  if( nPos == -1 ){
    for( f=0; f<nStellen; f++ ){
      sAdd += "0";
    }
    return sFloat+","+sAdd;
  }
  aTmp = sFloat.split(",");
  n = aTmp[1].length;
  for( f=n; f<nStellen; f++ ){
    sAdd += "0";
  }
  return sFloat+sAdd;
}

////////////////////////////////////////////////////////////////////////////////////////
// initJSRS
// baut clientseitige 2-D Arrays zusammen ( wie RS ) die mit getJSArray übergeben wurden
//
function initJSRS( name, guid ){
  aKeys = eval("K"+guid);
  len = aKeys.length;
  aData = eval("D"+guid);
  z = 0; az = 0; aOut = Array();
  for(f=0;f<aData.length;f++){
    index = (f % len);
    if(index == 0){
      aOut[z] = Array();
      az = z; z++;
    }
    aOut[az][aKeys[index]] = utf8_decode((utf8_decode(unescape(aData[f]).replace(/\+/g," "))));
  }
  
  eval(name+"=aOut");
}


// Für Netscape um die Breite der SelectBoxen zu setzen
function RemoveDummies(){
  for (f=0;f<document.forms.length;f++){
    foel = document.forms[f].elements;
    for (x=0;x<foel.length;x++){
      if(foel[x].type.indexOf("select") != -1){
        if(foel[x].options.length > 0){
          foel[x].options[0] = null;
        }
      }
    }
  }
}

function getSelValue(oSel){
  if(!oSel){return -1} // fehlerhandling
  if(oSel.selectedIndex != -1){
    return oSel.options[oSel.selectedIndex].value;
  }else{
    return -1;
  }

}

function getSelText(oSel){
  if(oSel.selectedIndex != -1){
    return oSel.options[oSel.selectedIndex].text;
  }else{
    return -1;
  }
}
function preselSel(oSel, sValue){
  oSel.options[0].selected=true;
  for(z=0;z<oSel.options.length;z++){
    if(oSel.options[z].value == sValue){
      oSel.options[z].selected=true;
    }
  }
}



function removeSelItem(objSel){
  objOpt = objSel.options;
  Index = objSel.selectedIndex;
  if (objOpt.length == 0 || Index == -1){ return false; } // handle Error
  objOpt[Index] = null;
}

function cutLength(sIn,nLen){
  if(sIn.length>nLen){
    return sIn.slice(0,nLen)+"...";
  }else{
    return sIn;
  }
}

var activBox="";
function changeStyle(obj,d){
  obj.type=="text"?classname="input":classname="textarea";
  if(d){
    obj.className = classname + "Visited";
    activBox=obj.name;
  }else{
    obj.className = classname;
    //activBox=0;
  }
}

function getWindowHeight(){
  if (document.all){
    return document.body.offsetHeight;
  }else{
    return window.innerHeight;
  }
}

function getWindowWidth(){
  if (document.all){
    return document.body.offsetWidth;
  }else{
    return window.innerWidth;
  }
}


function twshow(objDiv){
  hideBody();
  //div im fenster zentrieren
  //ww = window.document.body.offsetWidth;
  //hh = window.document.body.offsetHeight;
  ww = getWindowWidth();
  hh = getWindowHeight();
  tww = objDiv.offsetWidth;
  twh = objDiv.offsetHeight;
  st = document.body.scrollTop;

  objDiv.style.left = (ww / 2) - ( tww / 2 );
  twtop = (hh / 2) - ( twh / 2 ) - (((hh / 2) - ( twh / 2 )) / 4) + st;
  if( twtop - st < 50 ){
    twtop = 50 + st;
  }
  objDiv.style.top = twtop;
  objDiv.style.visibility = "visible";
}

function twhide(objDiv){
  objDiv.style.visibility = "hidden";
//  objDiv.innerHTML = "";
  showBody();
}

bBlockhideBodyFunction = false;
STAMMDATEN=false;
function hideBody(){
  if(bBlockhideBodyFunction){return;}
  //maintab.style.filter = "Alpha(Opacity=40)";
  //maintab.style.visibility = "hidden";

  if(STAMMDATEN){
    handelVisibilityForSelFromForm( "StForm", "hidden");
    handelVisibilityForSelFromForm( "ReForm", "hidden");
    handelVisibilityForSelFromForm( "AspForm", "hidden");
    return;
  }
//  try{
//    for(f=0;f<frames.length;f++){
//      frames[f].document.body.style.visibility = "hidden";
//    }
//  }catch(exeption){
//
//  }
  try{
    aE = mainform.elements;
    for(f=0;f<aE.length;f++){
      if(aE[f].name.indexOf("pmx")>0){
        break;
      }
      if( aE[f].type == "select-one" ){ //  || aE[f].type == "text" || aE[f].type == "button"
        aE[f].style.visibility = "hidden"
      }
    }
  }catch(exeption){
    return;
  }

}
function showBody(){
  if(bBlockhideBodyFunction){return;}

  //maintab.style.filter = "Alpha(Opacity=100)";
  //maintab.style.visibility = "visible";

  if(STAMMDATEN){
    handelVisibilityForSelFromForm( "StForm", "visible");
    handelVisibilityForSelFromForm( "ReForm", "visible");
    handelVisibilityForSelFromForm( "AspForm", "visible");
    return;
  }
//  try{
//    for(f=0;f<frames.length;f++){
//      frames[f].document.body.style.visibility = "visible";
//    }
//  }catch(exeption){
//
//  }
  try{
    aE = mainform.elements;
    for(f=0;f<aE.length;f++){
      if(aE[f].name.indexOf("pmx")>0){
        break;
      }
      if( aE[f].type == "select-one" ){ // || aE[f].type == "text" || aE[f].type == "button"
        aE[f].style.visibility = "visible"
      }
    }
  }catch(exeption){
    return;
  }

}

function handelVisibilityForSelFromForm( objForm, sState ){
  try{
    aE = eval(objForm+".elements");
    for(f=0;f<aE.length;f++){
      if( aE[f].type == "select-one" ){ //  || aE[f].type == "text" || aE[f].type == "button"
        aE[f].style.visibility = sState
      }
    }
  }catch(exeption){
    return;
  }
}

// formatiert eine zahl mit x kommastellen und rundet kaufmännisch
function number_format( sNumber, iDigits ){
  var pos;
  var Digits;
  sNumber = Math.round(sNumber * Math.pow(10,iDigits) ) / Math.pow(10,iDigits);
  sNumber = new String( sNumber );
  pos = sNumber.indexOf(".");
  Digits = pos!=-1 ? iDigits - (sNumber.length - pos) + 1 : iDigits;
  sNumber += ( pos == -1 && iDigits != 0 ) ? "." : "" ;
  for(f=0;f<Digits;f++){
    sNumber += "0";
  }
  return sNumber;
}

// neusortierung von zweidimensionalen js arrays
////////////////////////////////////////////////////////
var aOrderCols;
function oArrayElm( iiidx, aaaRow ){
  this.idx = iiidx;
  sss = "";
  for(nnn=0;nnn<aOrderCols.length;nnn++){
    if(isNaN(aaaRow[aOrderCols[nnn]])){
      sss += aaaRow[aOrderCols[nnn]];
    }else{
      // sortierung f�r numerische felder
      sss += fillZero(aaaRow[aOrderCols[nnn]]);
    }

  }
  this.sss = sss.toUpperCase();
  this.toString = orderHandler;
}

function fillZero( sNumber ){
  sNumber = number_format( sNumber, 5 );
  var f;
  while(sNumber.length<12){
    sNumber = "0" + sNumber;
  }
  return sNumber;
}
function orderHandler(){
  return this.sss;
}
function reorderArray(aSrc,sOrderCols, bDesc){
  sOrderCols = sOrderCols.replace(/[ ]+/g,"");
  aOrderCols = sOrderCols.split(",");
  // sortierindex erstellen
  aaaTmp = new Array();
  for(fff=0;fff<aSrc.length;fff++){
    aaaTmp[fff] = new oArrayElm(fff,aSrc[fff]);
  }
  // sortieren
  aaaTmp.sort();
  // sourcearray angleichen
  aaaRet = new Array();
  for(fff=0;fff<aaaTmp.length;fff++){
    aaaRet[fff] = aSrc[aaaTmp[fff].idx];
  }
  if( bDesc ) aaaRet.reverse();
  aaaTmp = null;
  return aaaRet;
}
////////////////////////////////////////////////////////

function showInfo(s){
  alert(s);
}

///////////////////////////////////////////////////////
// globales projektweies KeyHandling( TastaturKeys )
var kSTRG = false;
var kSHIFT = false;
function handleGlobalKeys( kDIR ){

  kc = window.event.keyCode;
  //status = "global:"+kc;
  switch(kc){

    case 16:
      if(kDIR=="down"){
        kSHIFT = true;
      }
      if(kDIR=="up"){
        kSHIFT = false;
      }

    break;

    case 17:
      if(kDIR=="down"){
        kSTRG = true;
      }
      if(kDIR=="up"){
        kSTRG = false;
      }
    break;

    default:
      // nop
    break;
  }
  status = "kSHIFT="+kSHIFT+"; kSTRG="+kSTRG+";";
  handleActionKeys( kc );
}

////////////////////////////////////////////////////////
function getRealDate( sSQLDate ){
  aTmp = sSQLDate.split("-");
  return aTmp[2]+"."+aTmp[1]+"."+aTmp[0];
}

////////////////////////////////////////////////////////
function getRealTime( sSQLDate ){
  aTmp = sSQLDate.split("-");
  return aTmp[3]+":"+aTmp[4];
}

function stopp(){
  for(x=0;x<10000;x++){
    a=(x*20/3.12345+4)/x*12345;
  }
  setTimeout("stopp();",50)
}
// Toolwindows dragging
drag = 0;
move = 0;
function inittwdragging() {
  window.document.onmousemove = mouseMove
  window.document.onmousedown = mouseDown
  window.document.onmouseup = mouseUp
  window.document.ondragstart = mouseStop
}
function mouseDown() {
  if (drag) {
    clickleft = window.event.x - parseInt(dragObj.style.left)
    clicktop = window.event.y - parseInt(dragObj.style.top)
    if( (clicktop+document.body.scrollTop) < 25 ){
      //dragObj.style.zIndex += 1
      move = 1;
    }
  }
}
function mouseStop() {
  window.event.returnValue = false
}
function mouseMove() {
  if (move) {
    dragObj.style.left = window.event.x - clickleft
    dragObj.style.top = window.event.y - clicktop
  }
}
function mouseUp() {
  move = 0;
}

//onFocus='handleButtonStyle(this, 1)' onBlur='handleButtonStyle(this, 0)'
function handleButtonStyle( objButton, bOn ){
  if(bOn){
    objButton.className = "buttonVisited";
  }else{
    objButton.className = "button";
  }



}

function getCharFromCode( iKeyCode ){
  switch(String(iKeyCode)){
    case "222":
      return "&Auml;";
    break;
    case "192":
      return "&Ouml;";
    break;
    case "186":
      return "&Uuml;";
    break;
    default:
      return String.fromCharCode(iKeyCode);
    break;

  }
}
function JSmsg(sMSG){
  //TODO einbauen

  sCss = "msgInfo";
  // Meldung ausgeben
  if(sMSG!=""){
    sMsgTyp = sMSG.substr(0,2);
    switch( sMsgTyp ){
      case "@E":
        sCss = "msgError";
      break;
      case "@F":
        sCss = "msgError";
      break;
      case "@W":
        sCss = "msgWarning";
      break;
      case "@I":
        sCss = "msgInfo";
      break;
    }
  }
  sMSG = sMSG.substr(2);
  alert(sCss);
  MSG.innerHTML = "<font class="+sCss+">"+sMSG+"</font>";
}
function utf8_encode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    str_data = str_data.replace(/\r\n/g,"\n");
    var utftext = "";
 
    for (var n = 0; n < str_data.length; n++) {
        var c = str_data.charCodeAt(n);
        if (c < 128) {
            utftext += String.fromCharCode(c);
        } else if((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        } else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }
    }
 
    return utftext;
}

function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    var string = "", i = 0, c = c1 = c2 = 0;
 
    while ( i < str_data.length ) {
        c = str_data.charCodeAt(i);
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if((c > 191) && (c < 224)) {
            c2 = str_data.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return string;
}

  function getColtoJSArray(aRS,sCol,sName){
    aOut = Array();
    for(z=0; z < aRS.length;z++){
      aOut[z] = eval("aRS["+z+"]."+sCol);
    }
    eval(sName+"=aOut");
  }
  
  function getMultiSelValue(oSel){
    if(!oSel){return -1} // fehlerhandling
    selvalue = ""
    for(z=0;z<oSel.options.length;z++){
      if(oSel.options[z].selected==true){
        if(selvalue==""){
          selvalue+=oSel.options[z].value;
        }else{
          selvalue+=","+oSel.options[z].value;
        }
      }
    }
    return selvalue;
  }
  
  
function preselMultiSel(oSel, aValue){
  for(z=0;z<oSel.options.length;z++){
    for(y=0;y<aValue.length;y++){
      if(oSel.options[z].value == aValue[y]){
        oSel.options[z].selected=true;
      }
    }
  }
}  
