var lockActions = false;
var selectedEntryId = null;
var selectedOrderId = null;
var depotId = 0;
var module = '';
var selectedTabId = '';
var selectedOrderTabId = '';
var bgColor ='transparent';
var depotRequestURL = '/depot/ajax.php';

var LOADING_TEXT = "Daten werden geladen. Haben Sie bitte ein Augenblick Geduld.";
var CHKFORM_ERROR   = "Bitte die rot gekennzeichneten Felder korrigieren oder mit dem richtigen Inhalt f&uuml;llen!";
var CALCSUM_ERROR_1 = 'Sie k&ouml;nnen nicht f&uuml;r mehr Geld kaufen als Sie im Depot haben!';
var CALCSUM_ERROR_2 = 'Sie k&ouml;nnen nicht mehr Wertpapiere verkaufen als Sie im Depot haben!';
    
// Fetch URL-Paramaters
function initializeDepotFramework() {
    return true;
}
                                
function showEntryBoxTab(index,id) {
  selectedTabId = id;
  if (id == 'closeTab') {
    hideEntryBox('depot_entry_actions');
    return;
  } else if(id == 'notesTab') {
    var notes = $$('.note_text');
    notes.each(function(object) {
      var id = object.id.replace('depot_note_text','');
      new Ajax.InPlaceEditor(object.id, depotRequestURL+'?module='+module+'&listsId='+depotId+'&action=notes&do=editNote&note='+id+'&id='+selectedEntryId,{
        cancelText: 'abbrechen', 
        okText: 'ok',
        formClassName: 'inplaceeditor_form', 
        cancelButton : true,
        cancelLink : false, 
        highlightcolor: '',
        highlightendcolor: '', 
        rows : 3, 
        cols: 50});
    });
  } else if(id == 'historyTab') {
    SortableTable.create('eventHistory');
    TablePagination.create('eventHistory', {
      rowsPerPage : 10
    });
  } else if(id == 'sellTab' || id == 'buyTab') {
    if ($('action_count')) { activateObserver(); }
  }
}

function showOrderBoxTab(index,id) {
  selectedOrderTabId = id;
  if (id == 'closeTab') {
    hideEntryBox('depot_order_actions');
    return;
  } else if(id == 'notesTab') {
    var notes = $$('.note_text');
    notes.each(function(object) {
      var id = object.id.replace('depot_note_text','');
      new Ajax.InPlaceEditor(object.id, depotRequestURL+'?module='+module+'&listsId='+depotId+'&action=notes&do=editNote&note='+id+'&id='+selectedEntryId,{
        cancelText: 'abbrechen', 
        okText: 'ok',
        formClassName: 'inplaceeditor_form', 
        cancelButton : true,
        cancelLink : false, 
        highlightcolor: '',
        highlightendcolor: '', 
        rows : 3, 
        cols: 50});
    });
  } else if(id == 'sellTab' || id == 'buyTab') {
    // nothing to do
  }
}

function hideEntryBox(id) {
  var box = $(id);
  if(box) {
    if(selectedEntryId != null) {
      $('entry'+selectedEntryId).removeClassName('selected');
      selectedEntryId = null;
    }
    $(id+'_box').innerHTML = LOADING_TEXT;
    box.hide();
  }
}

function showEntryBox(entryId, id) { 
  if(id == undefined) {
    id = 'depot_entry_actions';
  }
  if(selectedEntryId != null) {
    $('entry'+selectedEntryId).removeClassName('selected');
  }
  
  selectedEntryId = entryId;
  hideActionBox(id);
  
  // Highlight the selected row
  var entryRow = $('entry'+entryId);
  entryRow.addClassName('selected');
  
  var box = $(id);
  box.show();
  tabpane = TabPane.getTabPaneById(id);
  tabpane.setOption('staticParameters','module='+module+'&listsId='+depotId+'&id='+entryId);
  tabpane.showTab(0,true);
}

function showTable(category) {
  var myAjax = new Ajax.Request(
    depotRequestURL, 
    {
      method: 'post', 
      parameters: 'module='+module+'&listsId='+depotId+'&action=TableDisplay&category='+category, 
      onComplete: function(request,object) {
          $('listcategory'+category).innerHTML = request.responseText;          
          $('listcategory'+category).innerHTML.evalScripts();
        }
    });
  return false;
}

function deleteNote(entryId,noteId) {
  var myAjax = new Ajax.Request(
      depotRequestURL, 
      {
        method: 'post', 
        parameters: 'module='+module+'&listsId='+depotId+'&action=notes&do=deleteNote&id='+entryId+'&note='+noteId, 
        onComplete: function(request,object) {
            var tabpane = false;
            if (module == 'depot' || module == 'watchlist') {
              tabpane = TabPane.getTabPaneById('depot_entry_actions');
            }
            if (!tabpane) {
              return false;
            }
            tabpane.showContent(request);
          }
      });
      
  return false;
}

function addNote(entryId) {
  var text = $('noteText').value;
  if(text == '') {
    return false;
  }
  
  var myAjax = new Ajax.Request(
      depotRequestURL, 
      {
        method: 'post', 
        parameters: 'module='+module+'&listsId='+depotId+'&action=notes&do=addNote&text='+text+'&id='+entryId, 
        onComplete: function(request,object) {
            var tabpane = false;
            if (module == 'depot' || module == 'watchlist') {
              tabpane = TabPane.getTabPaneById('depot_entry_actions');
            }
            if (!tabpane) {
              return false;
            }
            tabpane.showContent(request);
          }
      });
  return false;
}

function removeInstrument(listId, entryId) {
  var myAjax = new Ajax.Request(
      depotRequestURL, 
      {
        method: 'post', 
        parameters: 'module='+module+'&listsId='+depotId+'&action=removeTab&do=delete&id='+entryId, 
        onComplete: function(request,object) {
            tabpane = TabPane.getTabPaneById('depot_entry_actions');
            tabpane.showContent(request);
          }
      });
  window.setTimeout('location.reload()', 3500);    
  return false;
}

/** 
 * toggle the display of the filter
 */
function filterBoxToggle() {
  $('depotEventFilterContainer').toggleClassName('hidden'); 
  $$('.filterbox')[0].toggleClassName('filterbox_closed');
  return false;
}

////////////////////////////   transaction filter /////////////////////////////////
function applyEventFilter(id) {
  var tableId = 'depotEventListTable';

  var loader = TableLoader.getTableLoaderById(tableId);
  var pagination = TablePagination.getTablePaginationById(tableId);
  items = new Array('event_type','from_month','from_year','to_month','to_year', 'instruments');
  addQuery="";
  for (var i=0; i< items.length; i++) {
    var name=items[i];
    if ($F(name)) {
      if($F(items[i]) instanceof Array) {
        for (var j=0; j<$F(items[i]).length; j++) {
          addQuery = addQuery + "&" + items[i] + "[]="+$F(items[i])[j];
        }
      } else {
        addQuery = addQuery + "&" + items[i] + "="+$F(items[i]);
      }
    }
  }    
  loader.options['staticParameters'] = 'action=historyTable&listsId=' + id + addQuery;

  loader.setCurrentPage(0);
  loader.load();
  return false;
}

function toggleFilterBox() {
  var div = $('depotEventFilterContainer');
  div.toggle();
}
  
////////////////////////////   action box ////////////////////////////////////////
  
  var contentElement = undefined;
  
  function showReloadContent(request,object) {
    contentElement.innerHTML = request.responseText; 
    toggleLoadingEffect(contentElement.id);
     
    if ($('action_count') || $('action_price') || $('action_fee')) {
      activateObserver();
    }
    if ($('searchresults')) {
      activateSorting();
    }
  }
  
  function reloadContent(element,action,step,params) {
    contentElement = element;
    selectedTabId = '';
    
    var more = '';
    if (!params.match(/module/)) {
      more = '&module='+module;
    }
    if(params != '') {
      more = more + '&' + params;
    }
    
    if(step != 0) {
      var inputElements = element.getElementsBySelector('input,select,textarea');
      for(var i=0;i<inputElements.length;i++) {
        more = more + '&' + inputElements[i].name + '=' + inputElements[i].value;
      }
    }
    
    toggleLoadingEffect(element.id);
    
    var myAjax = new Ajax.Request(
      depotRequestURL, 
      {
        method: 'post', 
        parameters: 'listsId='+depotId+'&action='+action+'&step='+step+more, 
        onComplete: showReloadContent
      });
    
    return false;
  }
  
  function showActionBox(action,step,params,force) {
    if(lockActions && force != true) {
        return false;
    }
        
    hideEntryBox();
    
    $('depot_actions').show();
    return reloadContent($('depot_actions_box'),action,step,params);
  }
  
  function hideActionBox(force) {
    if(lockActions && force != true) {
        return false;
    }
    
    $('depot_actions').hide();
    $('depot_actions_box').innerHTML = LOADING_TEXT;
  }

////////////////////////////// addBox ////////////////////////////////////////////
function activateSorting() {
  SortableTable.create('searchresults');
  TablePagination.create('searchresults', {rowsPerPage: 10});
}
  
////////////////////////////  sell/buy checks ////////////////////////////////////

/**
 * initialize keypress - observers for transactions add/sell/move/buy
 */
function activateObserver() {
  if($('action_count')) {
    Event.observe($('action_count'), 'keyup', observeNumber);
    Event.observe($('action_count'), 'click', observeNumber);
  }
  if($('action_price')) {
    Event.observe($('action_price'), 'keyup', observeNumber);
    Event.observe($('action_price'), 'click', observeNumber);
  }
  if($('action_fee')) {
    Event.observe($('action_fee'), 'keyup', observeNumber);
    Event.observe($('action_fee'), 'click', observeNumber);
  }
  if($('action_date') && $('depot_content') && $$('calendar').length == 0) {
    Calendar.setup({
          inputField     :    "action_date",      // id of the input field
          ifFormat       :    "%d.%m.%Y",       // format of the input field
          showsTime      :    false,            // will display a time selector
          button         :    "action_trigger"   // trigger for the calendar (button ID)
      }); 
  }
}

/**
 *  disable / enable date part.
 */
function disableDate(field) {
  if (field == 'market') {
    $('action_price').value = $('exchange').options[$('exchange').selectedIndex].text.match(/\d+(?:\,\d*)?/);
    $('action_price').value.replace(',','.');
    $('action_price').setAttribute('readonly', 'readonly');
  } else {
    $('action_price').removeAttribute('readonly');
  }
  if (field == 'limit' || field == 'stop') {
    $('action_date').show();
    $('label_action_date').update('Enddatum');
    if ($('action_trigger')  instanceof Object) {
      $('action_trigger').show();
    }
    
  } else {
    $('action_date').hide(); 
    $('label_action_date').update('&nbsp;');
    if ($('action_trigger') instanceof Object) {
      $('action_trigger').hide();
    }
  }
}

/**
 * checks the complete input form for transactions add/sell/move/buy
 */
function checkForm() {
  var ret = true;
  if (module == 'watchlist') return true;
  if($('action_count')) {  
    if ($('action_count').value == '') {
      $('action_count').setStyle({ background: 'red' })
      ret = false;
    }
    if (isNaN($('action_count').value.replace(',','.'))) ret=false;
  }
  if ($('action_price') && isNaN($('action_price').value.replace(',','.'))) ret=false;
  if ($('action_fee') && isNaN($('action_fee').value.replace(',','.'))) ret=false;
  if ($('action_date') && checkDate('action_date') == false) ret=false;
  if (ret == false) {
    showMessageBox(CHKFORM_ERROR,'error',3500);
  }
  return ret;
}

/**
 * check for date
 */
function checkDate(elementId) {
  var obsElement = $(elementId);
  bgColor = (obsElement.getStyle('backgroundColor') != 'red' || !bgColor)?obsElement.getStyle('backgroundColor'):bgColor;
  if (!obsElement.value.match(/^\d+\.\d+\.\d+$/)) {
    obsElement.setStyle({ backgroundColor: 'red' });
    return false;
  }
  obsElement.setStyle({ backgroundColor: bgColor });
  return true;
}

/**
 * check for numbers
 */  
function observeNumber(event) {
  var obsElement = Event.element(event);
  if (obsElement.tagName.toLowerCase() != 'input') {
    showMessageBox('Die Eingabe&uuml;berwachung ist fehlerhaft!', 'error', 3500);
    return false;
  } 
  var obsValue = obsElement.value;
  var sum = "-";
  bgColor = (obsElement.getStyle('backgroundColor') != 'red' || !bgColor) ? obsElement.getStyle('backgroundColor') : bgColor ;
  if (isNaN(obsValue.replace(',','.'))) {
    Event.element(event).setStyle({ backgroundColor: 'red' });
  } else {
    Event.element(event).setStyle({ backgroundColor: bgColor });    
    calcSum();
  }
  if (obsElement.id == 'action_fee') {
    checkFee(obsValue);
  }
}

function checkFee(valueStr) {
  return;
  /*
  if (!$('feeAdd')) return;
  var valueNum = valueStr.replace(',','.')
  // percent calc
  if(!$('feetype_euro').checked ) {
      valueNum = (parseFloat($F('action_count')) * parseFloat($F('action_price')) * valueNum) / 100;
  }
  
  if (valueNum > 5.9) {
    var feeDiff = new String(Math.round((valueNum - 5.9)*100)/100);
    if (feeDiff.search(/\./) == feeDiff.length-2) {
      feeDiff += '0';
    }
    feeDiff.replace(/\./,',');
    $('feeAddDifference').update(feeDiff);
    $('feeAdd').show();
  } else {
    $('feeAdd').hide();
  }
  */
}

/**
 * calculates the sum of buy or sell 
 */
 function calcSum() {
    if (!$('action_sum')) return;
    if ($F('action_count') == '' || $F('action_price') == '') {
      $('action_sum').innerHTML = 'Summe: -';
      return;
    }
    
    var fee = (isNaN(parseFloat($F('action_fee').replace(',','.')))?0:parseFloat($F('action_fee').replace(',','.')));
    if (selectedTabId == 'sellTab') {
      fee = fee * -1;
    }
    
    if($('feetype_euro').checked) {
      var sum = (parseFloat($F('action_count').replace(',','.')) * parseFloat($F('action_price').replace(',','.')) + fee);
    } else {
      var sum = (parseFloat($F('action_count').replace(',','.')) * parseFloat($F('action_price').replace(',','.')) * ((fee+100) / 100));
    }
    
    sum = sum.toFixed(2);
    
    //if (selectedTabId == 'buyTab' || selectedTabId == 'moveTab' || !selectedTabId) {
    if (selectedTabId != 'sellTab') {
      value = $F('cash_amount');//.replace(/\./g, '').replace(',','.');
      if (isNaN(value) || isNaN(sum)|| parseFloat(value) < sum ) {
        $('action_sum').className = 'transaction_error';
        $('action_sum').addClassName = 'red';
        showMessageBox(CALCSUM_ERROR_1,'error',3500);
      } else {
        $('action_sum').className = '';
      }
    } else { 
      entry_count = parseFloat($F('entry_count').replace(',','.'));
      myCount = parseFloat($F('action_count').replace(',','.'));
      if (isNaN(myCount) || isNaN(sum) || entry_count < myCount ) {
        $('action_sum').className = 'transaction_error';
        $('action_sum').addClassName = 'red';
        showMessageBox(CALCSUM_ERROR_2,'error',3500);
      } else {
        $('action_sum').className = ''; 
      }
    }
    $('action_sum').innerHTML = 'Summe: ' + sum + ' ' + $F('action_currency');
 }
 
/**
 * set the current quote for this instrument on change with the exchanges
 */
function changeActionCount(id, id2Change) {
  if (!$(id2Change)) return;
  var index = $(id).selectedIndex;
  var obsValue2 = $(id).options[index].text.match(/\d+(?:\,\d*)?/);  
  if (obsValue2) {
    $(id2Change).value = obsValue2[0].replace(',','.');
  } else {
    $(id2Change).value = 0.001;
  }
  if (selectedTabId != 'sellTab') {
      var value = $F('cash_amount').replace(/\./g, '').replace(',','.');
      var max_count = $('max_count').readAttribute('max');
      var fee = (isNaN(parseFloat($F('action_fee').replace(',','.')))?0:parseFloat($F('action_fee').replace(',','.')));
      if (module == 'depot' && $('feetype_percent').checked ) {
        $('max_count').update( '(max: ' + parseInt((value * 100) / ($(id2Change).value*(100+fee))) +')'); 
      } else {
        $('max_count').update( '(max: ' + parseInt((value - fee)/$(id2Change).value) + ')'); 
      }
  }  
  calcSum();
}

/*
 *  load the historic data
 */
function loadHistoricQuotes(frame, action, step, params) {
    var da=$F('action_date').split('.'); 
    var ta=$F('action_time').split(':'); 
    var currdate=new Date(da[2]-0,da[1]-1,da[0]-0,ta[0]-0,ta[1]-0); 
    reloadContent($('action_date').up(frame+3),action, step, 'timestamp='+(currdate.getTime()/1000)+params);
    return false;
}

