var fPopup = null;
var markFilter = null;
var popupVisible = null;
var inContext = null;
var lineColor1 = "";
var lineColor2 = "";
var secondRow = false;
var changed = false;
var autoTimer = null;
var autoRefresh = false;
var settingsWindow = null;


function duplicateBackslashes(single) 
	{
  var list = single.split("\\");
  return list.join("\\\\");
	}

function autoChecker()
  {
  if (autoRefresh)
    {
    autoRefresh = false;
    window.clearInterval(autoTimer);
    searchRates(false);
    }
  }

function on_save()
  {
  if (changed && !confirm ("Sie haben die Eckdaten der Finanzierung verändert, aber nicht gespeichert.\n\nWenn Sie mit dem Seitenwechsel fortfahren, gehen die Änderungen verloren."))
    return false;
  if (settingsWindow && !settingsWindow.closed)
    settingsWindow.close();
  return true;
  }


function openHintPopup (ev, nr)
  {
  openPopup (ev, "hint", document.getElementById("popupDiv"), document.getElementById("popupText"), document.getElementById("hint_" + nr).innerHTML, 650, 20);
  }

function openMspOverviewPopup (ev, nr)
  {
  openPopup (ev, "hint", document.getElementById("popupMspOverviewDiv"), document.getElementById("popupMspOverviewText"), document.getElementById("mspOverview_" + nr).innerHTML, 400, 20);
  }

function openCommissionPopup (ev, nr)
  {
  openPopup (ev, "hint", document.getElementById("popupCommissionDiv"), document.getElementById("popupCommissionText"), document.getElementById("commission_" + nr).innerHTML, 300, 20);
  }

function openPaymentPopup (ev, nr)
  {
  openPopup (ev, "hint", document.getElementById("popupPaymentDiv"), document.getElementById("popupPaymentText"), document.getElementById("payment_" + nr).innerHTML, 300, 20);
  }

function openIhypRatingPopup (ev, nr)
  {
  openPopup (ev, "hint", document.getElementById("popupIhypRatingDiv"), document.getElementById("popupIhypRatingText"), document.getElementById("ihypRating_" + nr).innerHTML, 300, 20);
  }

function openProviderPopup (ev, providerName)
  {
  openPopup (ev, "hint", document.getElementById("popupProviderDiv"), document.getElementById("popupProviderText"), providerName, 300, 20);
  }

function openFilterPopup (ev, name)
  {
  openPopup (ev, "filter", document.getElementById("popupFilterDiv"), document.getElementById("popupFilterText"), document.getElementById(name + "FilterList").innerHTML, 120, 20);
  }

function openHelpPopup (ev, help)
  {
  openPopup (ev, "help", document.getElementById("popupHelpDiv"), document.getElementById("popupHelpText"), help, 250, 50);
  }

function openPqPopup (ev, txt)
  {
  openPopup (ev, "hint", document.getElementById("popupPqDiv"), document.getElementById("popupPqText"), txt, 300, 20);
  }

var noHelpPopup = false;
function openPopup (ev, type, divEl, textEl, text, width, height)
  {
  if ( !fPopup.ie && type == "help" && noHelpPopup )
    return;    
  if (popupVisible != null && popupVisible != type)
    return;
  textEl.innerHTML = text;
  if (!ev)
  	ev = window.event;
  var lefter = ev.clientY+20;
  var topper = ev.clientX+10;
  fPopup.setContent (divEl.innerHTML);
  fPopup.show(topper, lefter, width, height);
  var realWidth = fPopup.getScrollWidth();
  var realHeight = fPopup.getScrollHeight();
  realHeight += type == "hint" ? 1 : 0;
  if (topper > document.body.clientWidth - realWidth)
    topper = document.body.clientWidth - realWidth;
  if (lefter+realHeight > document.body.clientHeight)
    {
    lefter = document.body.clientHeight - realHeight;
    if (lefter < 0)
      lefter = 0;
    }
  fPopup.hide(false);
  fPopup.show(topper, lefter, realWidth, realHeight);
  popupVisible = type;
  if (fPopup.ie)
  	document.body.onmouseup = closepop;
  }

function closePopup(type)
  {
  if (type == popupVisible)
    closepop();
  }
  
function closepop()
  {
  hideToolTip ();
  popupVisible = null;
  if (fPopup)
    fPopup.hide (true);
  var tr = inContext;
  inContext = null;
  if (tr != null)
    markLine (tr, false);
  }

function overLine (el)
  {
  while (el.tagName != "TR" && el.parentNode != el && el.parentNode != null)
    el = el.parentNode;
  return el;
  }

function rowOver (el)
  {
  if (inContext != null)
    return;
  var tr = overLine (el);
  markLine (tr, true);
  }

function rowOut (el)
  {
  if (inContext != null)
    return;
  var tr = overLine (el);
  markLine (tr, false);
  }

function markLine (tr, on)
  {
  var second = (tr.getAttribute ("second") == "1");
  var marked = (tr.getAttribute ("marked") == "1");
  var cells = tr.cells;
  var even = false;
  for (var i = 0; i < cells.length; i ++)
    {
    even = !even;
    var cell = cells[i];
    cell.style.backgroundColor = (on || marked && i >= 0) ? "orange" : (second ? lineColor2 : lineColor1);
    cell.className = (on || marked && i >= 0) ? cell.className+' markLineCol' : cell.className.replace(" markLineCol","");
    if(on)
      {
      if (cell.className.indexOf("markLineCol")<0)
    	  cell.className = cell.className+' markLineCol';
      }
    else
    	cell.className = cell.className.replace(" markLineCol","");
    }
  }
	
function searchRates()
  {
  handleDisabledLoanFields();
  el = firstInput("applicationForm:fun.id.crypt");
  if (el != null)
    el.disabled = false;
	document.applicationForm.submit();
  }	

function sort(criteria)
  {
	document.applicationForm.sort.value = criteria;
	document.applicationForm.submit();
  }	

function scorefilter(how)
  {
	document.applicationForm.scorefilter.value = how;
	document.applicationForm.submit();
  }	

function categoryfilter(how)
  {
	document.applicationForm.categoryfilter.value = how;
	document.applicationForm.submit();
  }	

function commissionfilter(how)
  {
	document.applicationForm.commissionfilter.value = how;
	document.applicationForm.submit();
  }	

function getCurrentDate()
  {
  var heute = new Date();
  var Tag = heute.getDate();
  var Monat = heute.getMonth() + 1;
  var Jahr = heute.getFullYear();
  var Stunde = heute.getHours();
  if (Stunde < 10)
    Stunde = "0" + Stunde;
  var Minute = heute.getMinutes();
  if (Minute < 10)
    Minute = "0" + Minute;
  var current = '' + Tag + '.' + Monat + '.' + Jahr + ' ' + Stunde + ":" + Minute;
  return current;
  }
	
function hasExtras ()
  {
  if ( document.applicationForm.elements["fun.acceptanceDays"].value != "" )
  	return true;
  if ( document.applicationForm.elements["fun.minimalValidity"].value != "" )
  	return true;
  if ( document.applicationForm.elements["fun.providerWritesContract"].value != "" &&
       document.applicationForm.elements["fun.providerWritesContract"].value != "0" )
  	return true;
  if ( document.applicationForm.elements["fun.disableRateOptimisation"].value != "" &&
       document.applicationForm.elements["fun.disableRateOptimisation"].value != "0")
  	return true;
  	
  return false;
  }

function calcDisagio (f, form, aname, rname)
  {
	var amount = f.parseInt(form.elements[aname].value);
	var rate = f.parseInt(form.elements[rname].value);
	if (rate == 0)
		rate = 100;
	return (amount * (100 - rate)) / 100;
  }
    
function rowClick (ev, el)
  {
  var tr = overLine (el);
  var on = tr.getAttribute("marked");
  if (on == null || on == "" || on == "0")
    on = "1";
  else
    on = "0";
  rowMark (ev, tr, on);
  }

function rowClickOn (ev, el)
  {
  var tr = overLine (el);
  rowMark (ev, tr, "1");
  }

function rowMark (ev, tr, on)
  {
  if (!ev)
  	ev = window.event;
  if ((!ev || ev == undefined || !ev.ctrlKey) && tr != null && tr != undefined)
    resetRowMarks (tr.parentNode.getElementsByTagName("TR"));
  setRowMark (tr, on);
  }

function resetRowMarks (rows)
  {
  for (var i = 0; i < rows.length; i ++)
    {
    var row = rows[i];
    var on = row.getAttribute("marked");
    if (on == "1")
      setRowMark (row, "0");
    }
  }

function setAllRowMarks (rows)
  {
  for (var i = 0; i < rows.length; i ++)
    {
    var row = rows[i];
    var on = row.getAttribute("marked");
    if (on == "1")
      markLine (row, false);
    }
  }

function setRowMark (tr, on)
  {
  tr.setAttribute ("marked", on);
  var card = tr.getAttribute("card");
  if (on == "1")
    markFilter.addItem (card);
  else
    markFilter.remItem (card);

  markLine (tr, false);
  return;
  var second = (tr.getAttribute ("second") == "1");
  var mixcell = tr.cells[1];
  mixcell.style.backgroundColor = (on == "1") ? "orange" : (second ? lineColor2 : lineColor1);
  return;

  var sp = mixcell.getElementsByTagName ("span")[0];
  if (on == "1")
    sp.innerHTML = "<img src=\"../backoffice/images/linemark.gif\"/>";
  else
    sp.innerHTML = "";
  }
  
function getMenuEntry (contextMenu, key)
  {
  for (var i=0; i<contextMenu.length; i++)
    {
    var thisEntry = contextMenu[i];
    if (thisEntry.key == key)
      return thisEntry;
    }
  return null;
  }

function getContextMenu (el)
  {
  return eval (getMenuName (overLine (el)));
  }

function isZero (tr)
  {
  return (tr.getAttribute ("isZero") == "1");
  }

function isMsp (tr)
  {
  return (tr.getAttribute ("isMsp") == "1");
  }

function getMenuName (tr)
  {
  if (isZero (tr))
    return "zeroMenu";
  else if (isMsp (tr))
    return "mspMenu";
  else
    return "mainMenu";
  }
  
function goContext (ev, el)
  {
  var forTr;
  if (!ev)
  	ev = window.event;
  if (window != parent)
  	parent.openLine = openLine;
  var tr = inContext;
  inContext = null;
  if (tr != null)
    {
    markLine (tr, false);
    forTr = tr;
    }
  else
    forTr = overLine (el);

  var menu = getMenuName (forTr);

  var lefter = ev.clientY+10;
  var topper = ev.clientX+10;
  if ( !fPopup.ie && topper + 190 > screen.availWidth )
    topper = screen.availWidth - 200;
  fPopup.setContent (buildContextMenu (forTr, menu));
	if (!g_bIsCategory || g_bIsBroker)
  	fPopup.show(topper, lefter, 177, 20);
 	else
  	fPopup.show(topper, lefter, 167, 20);

  var realHeight = fPopup.getScrollHeight();
  fPopup.hide(false);
  tr = overLine (el);
  if (tr != null)
    {
    markLine (tr, true);
    inContext = tr;
    }
  var realWidth = fPopup.getScrollWidth();
  
  var posX = 0;
  var posY = 0;
  if (typeof getPopupPosXY == "undefined")
    {  
    if (lefter+realHeight > document.body.clientHeight)
      {
      lefter = document.body.clientHeight - realHeight;
      if (lefter < 0)
        lefter = 0;
      }    
    if ( topper + realWidth > screen.availWidth )
      topper = screen.availWidth - realWidth;
    
    posX = topper;
    posY = lefter;
    }
  else
    {
    var posXY = getPopupPosXY(ev, realWidth, realHeight);
    posX = posXY.x;
    posY = posXY.y;
    }
  
	if (g_bIsCategory && g_bIsBroker)
  	fPopup.show(posX, posY, 177, realHeight);
 	else
	  fPopup.show(posX, posY, 167, realHeight);
  if (fPopup.ie)
  	document.body.onmouseup = closepop;
	if (ev.stopPropagation) ev.stopPropagation();
  }
  
function ItemFilter (column)
  {
  this.itemlist = new Array();
  this.column = column;

  function addItem (item)
    {
    for (var i = 0; i < this.itemlist.length; i ++)
      if (this.itemlist[i] == item)
        return;
    this.itemlist.push (item);
    }
  this.addItem = addItem;

  function remItem (item)
    {
    var newlist = new Array();
    while (this.itemlist.length > 0)
      {
      var top = this.itemlist[0];
      if (top != item)
        newlist.push (top);
      this.itemlist.shift();
      }
    this.itemlist = newlist;
    }
  this.remItem = remItem;

  function hasItem (item)
    {
    for (var i = 0; i < this.itemlist.length; i ++)
      if (this.itemlist[i] == item)
        {
        //alert ("search for " + item + " in list of len " + this.itemlist.length + " = true");
        return true;
        }
    //alert ("search for " + item + " in list of len " + this.itemlist.length + " = false");
    return false;
    }
  this.hasItem = hasItem;

  function getList ()
    {
    var sb = new StringBuilder();
    sb.reset();

    for (var i = 0; i < this.itemlist.length; i ++)
      if (i == 0)
        sb.append(this.itemlist[i]);
      else
        sb.append("|");
        sb.append(this.itemlist[i]);
    return sb.toString();
    }
  this.getList = getList;

  function initList (list)
    {
    if (list == null || list == "") return;
    var li = list.split("|");
    for (var i = 0; i < li.length; i ++)
      this.addItem (li[i]);
    }
  this.initList = initList;
  }  
  
function openDirect (ev, el, mode)
  {
  var tr = overLine (el);
  openSub( mode, tr );
  }
    
function openLine (ev, mode)
  {
	if (!ev) ev = window.event;
  var tr = inContext;
  inContext = null;
  closepop();
  openSub (mode, tr );
	if (ev.stopPropagation) ev.stopPropagation();
	}  

function optimizeField (path, newval)
  {
  setFieldValue (path, newval);
  var index = 0;
  var pos = path.indexOf("[");
  if (pos != -1)
    {
    index = eval(path.substr(pos+1,1));
    if (index > 0)
      {
      if (path.indexOf("fun.loans[") == 0)
        setAmountChanged (index);
      else if (path.indexOf("fun.auxLoans[") == 0)
        setAuxAmountChanged (index);
      if (path.indexOf("fun.kfwLoans[") == 0)
        setKfwAmountChanged (index);
      }
    }
  }

function submitOptimization ()
  {
  setChanged();
  recalcForm();
  searchRates();
  }

function MenuEntry (_key, _name, _expExists, _expEnabled, _expPossible, _expAlert)
  {
  this.key = _key;
  this.name = _name;
  this.expExists = _expExists;
  this.expEnabled = _expEnabled;
  this.expPossible = _expPossible;
  this.expAlert = _expAlert;
  
  function me_buildHtml (mlistName, entry, tr)
    {
    if (this.key == "<hr>")
      return "<hr>";
    if (!this.doesExist (tr))
      return "";
    var enabled = this.isEnabled(tr);
    var cs = "height:16px; cursor:default; font-family:Arial; font-size:12px; padding:3px; border-bottom:1px solid #eeeeff;";
    var goHigh = "this.style.background='#000066';";
    var goLow = "this.style.background='#eeeeee';";
    if (enabled)
      {
      cs += "color: black";
      goHigh += "this.style.color='white';";
      goLow += "this.style.color='black';";
      }
    else
      {
      cs += "color: gray";
      }
    
    var result = "<div style=\"" + cs + "\" onmouseover=\"" + goHigh + "\" onmouseout=\"" + goLow + "\"";
    if (enabled)
      if (fPopup.ie)
        result += " onclick=\"parent.window." + mlistName + "[" + entry + "].invoke(event)\"";
      else
        result += " onclick=\"" + mlistName + "[" + entry + "].invoke(event)\"";
        
    result += ">" + this.getName (tr) + "</div>";
    return result;
    }
  this.buildHtml = me_buildHtml;
      
  function me_invoke (ev, el)
    {
    var tr = null;
    if (el)
      tr = overLine (el);
    else
      {
    	if (!ev) ev = window.event;
      tr = inContext;
      inContext = null;
      closepop();
      }
    if (this.isActive (tr))
      this.perform (tr);
    if (!el && ev.stopPropagation) 
      ev.stopPropagation();
    }
  this.invoke = me_invoke;
  
  function me_doesExist (tr)
    {
    if (this.expExists && !eval(this.expExists))
      return false;
    if (this.getScoreFlag (tr, "hide") == "1")
      return false;
    return true;
    }
  this.doesExist = me_doesExist;
      
  function me_isEnabled (tr)
    {
    if (this.expEnabled && !eval(this.expEnabled))
      return false;
    if (this.getScoreFlag (tr, "gray") == "1")
      return false;
    if (this.getScoreFlag (tr, "none") == "1")
      return false;
    return true;
    }
  this.isEnabled = me_isEnabled;
    
  function me_isActive (tr)
    {
    return this.doesExist(tr) && this.isEnabled(tr);
    }
  this.isActive = me_isActive;
  
  function me_perform (tr)
    {
    if (this.expPossible && !eval(this.expPossible) || this.getScoreText (tr, "msg"))
      {
      alert (this.getMessage (tr));
      return;
      }
    return openSub (this.key, tr);
    }
  this.perform = me_perform;
  
  function me_getMessage (tr)
    {
    if (this.expMessage)
      return eval (this.expMessage);
    var msg = this.getScoreText (tr, "msg");
    if (!msg)
      msg = "Dieses Kommando kann an dieser Stelle nicht durchgeführt werden";
    return msg;
    }
  this.getMessage = me_getMessage;
  
  function me_getName (tr)
    {
    var txt = this.getScoreFlag (tr, "name");
    if (!txt)
      txt = this.name;
    return txt;
    }
  this.getName = me_getName;
  
  function me_getScoreFlag (tr, what)
    {
    var attName = "cm_" + this.key + "_" + what;
    var flag = tr.getAttribute (attName);
    if (!flag || flag == "")
      return null;
    return flag;
    }
  this.getScoreFlag = me_getScoreFlag;
  
  function me_getScoreText (tr, what)
    {
    var divName = "cm_" + this.key + "_" + what + "_" + tr.getAttribute ("cardNo");
    var el = document.getElementById (divName);
    if (!el || !el.innerHTML || el.innerHTML == "")
      return null;
    return el.innerHTML;
    }
  this.getScoreText = me_getScoreText;
  }
  
function buildContextMenu (tr, mlistName)
  {
  var result = "<div style='position:relative; top:0; left:0; border:2px solid black;  border-top:2px solid #cccccc; border-left:2px solid #cccccc; background: #eeeeee; width:167px;'>\n";
  var mlist = eval (mlistName);
  var inBlock = 0;
  for (var i = 0; i < mlist.length; i++)
    {
    var section = mlist[i].buildHtml (mlistName, i, tr);
    if (section == "<hr>")
      {
      if (inBlock == 0)
        section = "";
      inBlock = 0;
      }
    else if (section != "")
      inBlock ++;    
    result += section;
    }
  result += "</div>";
  return result;
  }

function cmFlag (tr, key, what)
  {
  var attName = "cm_" + key + "_" + what;
  var flag = tr.getAttribute (attName);
  if (!flag || flag == "")
    return null;
  return flag;
  }
  
function cmMsg (tr, key, what)
  {
  var divName = "cm_" + key + "_" + what + "_" + tr.getAttribute ("card");
  var el = document.getElementById (divName);
  if (!el || !el.innerHTML || el.innerHTML == "")
    return null;
  return el.innerHTML;
  }
  
function cmActive (tr, key)
  {
  if (cmFlag (tr, key, "hide") == "1" || cmFlag (tr, key, "gray") == "1" || cmFlag (tr, key, "none") == "1")
    return false;
  }

function decodedCard (card)
  {
  if (card.substring (0, 3) == "###")
    card = "___" + card.substring (3);
  return card;
  }

