/************ Search Input Autocompleter ******************/
function toggleSearchField(searchField, value, newValue) {
	if (searchField.value == value)
	{
		searchField.value = newValue;
	}
}

function MMS_initSearch() {

	searchitems = new Object();
	
	searchitems.de   = ['Energieabsatz','Nettoumsatz','Abschreibungen','Gruppengewinn','Erneuerbaren Energien','Stromhandel','Stromproduktion','Konsolidierte Erfolgsrechnung','Konsolidierte Bilanz','Aktiven','Passiven','Sachanlagen','Immaterielle Anlagen','Langfristige Finanzverbindlichkeiten','Latente Ertragssteuern','Anlagevermögen','Terminguthaben','Flüssige Mittel','Wertschriften des Umlaufvermögens','Derivative Finanzinstrumente','Umlaufvermögen','EBITDA','EBIT','Aktienkapital','Agio','Eigene Aktien','Gewinnreserven','Latente Ertragssteuern','Langfristige Finanzverbindlichkeiten','Kurzfristige Finanzverbindlichkeiten','Derivative Finanzinstrumente','Eigenkapital','Konsolidierte Mittelflussrechnung','Cashflow','Finanzinstrumente','Abschreibungen','Finanzergebnis','Ertragssteuern','Sachanlagen','Eigenkapital','Rückzahlung','Segmentberichterstattung','Konsolidierungskreis'];
	
	searchitems.en  = ['Intangible assets','Long-term financial liabilities','Deferred income tax assets','Fixed assets','Time deposits','Cash','Securities under current assets','Derivative financial instruments','Current assets','EBITDA','EBIT','Share premium','Treasury shares','Retained earnings','Deferred income tax liabilities','Long-term financial liabilities','Other long-term liabilities','Short-term financial liabilities','Equity','Consolidated Cash Flow Statement','Cashflow','Financial instruments','Depreciation','Finance income','Income taxes','Tangible fixed assets','Equity','Segment reporting','Scope of Consolidation'];
	
	searchitems.fr   = ['Livraison d’énergie','Chiffre d’affaires net','Amortissements','Bénéfice du Groupe ','Energies renouvelables ','efficacité énergétique ','grandes centrales ','Négoce d’électricité ','Production d’électricité ','EBIT ','EBITDA','demande d’autorisation générale','gestion de portefeuille','parc éolien','centrale nucléaire','libéralisation','centrale de pompage-turbinage','tour solaire','Vente d’énergie','EBITDA','Bénéfice du Groupe','Amortissements','Total des capitaux propres','Chiffre d’affaires net','Résultat opérationnel','Résultat financier','Résultat avant impôts sur les bénéfices','Impôts sur les bénéfices','Comptes de profits','Bilan consolidé','Actif','Passif','Immobilisations corporelles','Immobilisations financières','Total de l’actif immobilisé','Trésorerie','Dépôts à terme','Instruments financiers dérivés','Autres actifs circulants','Total de l’actif circulant','Total de l’actif','Total des capitaux propres','Capital-actions','Agio','Gains et pertes non réalisés','Actions propres','Tableau de flux de trésorerie consolidé','Information sectorielle'];
	
	language = document.body.getAttribute('lang');
	
	autocompleter = false;
	MMS_getAutoCompleter();
}

function MMS_getAutoCompleter() {
	
	autocompleter 			 = true;
	
	var inputElement		 = $("search");
		
	
	var createDiv			 = document.createElement("div");
	var createDivId 		 = document.createAttribute("id");
	createDivId.nodeValue 	 = "autosearchinput";	
	var createDivClass 		 = document.createAttribute("class");
	createDivClass.nodeValue = "page_name_auto_complete";
	createDiv.setAttributeNode(createDivId);
	createDiv.setAttributeNode(createDivClass);	
	
	inputElement.appendChild(createDiv);
	
	searchitems[language].sort(function(x,y){ 
      var a = String(x).toUpperCase(); 
      var b = String(y).toUpperCase(); 
      if (a > b) 
         return 1 
      if (a < b) 
         return -1 
      return 0; 
    });

	new Autocompleter.Local('searchinput', 'autosearchinput', searchitems[language], {partialChars:1});
}

/************ Glossary pop ups ******************/
function MMS_GetGlossary(level, type, lang, target)
{
    Event.observe(document, "mouseover", updateMousePositon);

    var linkElement = $("glossary");

	if (linkElement == null)
    {
		var url = level + "segments/" + type + "/" + lang + "/" + target + ".inc.htm";

		var glossaryContainer = Builder.node("div", {id: "glossary", className:"glossary"}, [
    								Builder.node("div", {id:"glossarycontent", className:"glossarycontent"})
    							]);
        
        document.body.appendChild(glossaryContainer);

		new Ajax.Updater('glossarycontent', url);
	}
	
	return;
}

function MMS_RemoveGlossary() 
{
    var target = $("glossary");
    
	if (target != null) 
    {
        target.innerHTML = '';
		destroy = document.body.removeChild(target);
		delete linkElement;
		delete updateMousePositon;
	}
	return;
}

function updateMousePositon(e) 
{
        var linkElement	= $("glossary");		
		if (linkElement != null) 
        {
			linkElement.style.left = (Event.pointerX(e)) + "px";
			linkElement.style.top = (Event.pointerY(e)) + "px";
		}
    
        Event.stopObserving(document, "mouseover", updateMousePositon);
		
}

/************ Annotation pop ups ******************/
var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, 
{
  initialize: function(id) 
  {
    this.createOverlay();

    this.dialog_box = $(id);
    this.dialog_box.show = this.show.bind(this);
    this.dialog_box.hide = this.hide.bind(this);
    this.dialog_box.style.position = "absolute";

    this.parent_element = this.dialog_box.parentNode;

    var e_dims = Element.getDimensions(this.dialog_box);
    var b_dims = Element.getDimensions(this.overlay);
    
    this.dialog_box.style.left = ((b_dims.width/2) - (e_dims.width/2)) + 'px';
    this.dialog_box.style.top = f_scrollTop() + 66 + 'px';
    this.dialog_box.style.zIndex = this.overlay.style.zIndex + 1;
  },

  createOverlay: function() 
  {
    if($('dialog_overlay')) {
      this.overlay = $('dialog_overlay');
    } else {
      this.overlay = document.createElement('div');
      this.overlay.id = 'dialog_overlay';
      Object.extend(this.overlay.style, {
      	position: 'absolute',
      	top: 0,
      	left: 0,
      	zIndex: 90,
      	width: '100%',
      	backgroundColor: '#000',
      	display: 'none'
      });
      document.body.insertBefore(this.overlay, document.body.childNodes[0]);
    }
  },

  moveDialogBox: function(where) 
  {
    Element.remove(this.dialog_box);
    if(where == 'back')
      this.dialog_box = this.parent_element.appendChild(this.dialog_box);
    else
      this.dialog_box = this.overlay.parentNode.insertBefore(this.dialog_box, this.overlay);
  },

  show: function() 
  {
    this.overlay.style.height = $('background').getHeight() + 'px';
    this.overlay.style.width = document.body.clientWidth + 'px';
    this.moveDialogBox('out');
    this.overlay.onclick = this.hide.bind(this);
    this.selectBoxes('hide');
    new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
    this.dialog_box.style.display = '';
  },

  hide: function() 
  {
    this.selectBoxes('show');
    new Effect.Fade(this.overlay, {duration: 0.1});

    this.dialog_box.innerHTML = '';
    document.body.removeChild(this.dialog_box);

    //this.dialog_box.style.display = 'none';
    //this.moveDialogBox('back');
    //$A(this.dialog_box.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
  },

  selectBoxes: function(what) 
  {
    $A(document.getElementsByTagName('select')).each(function(select) {
      Element[what](select);
    });

    if(what == 'hide')
      $A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)})
  }
});

function MMS_OpenAnnotation(level, type, lang, section, target)
{

	var url = level + "segments/" + type + "/" + lang + "/";
	if (section != "") 
    {
		url  += section + "/";;
	}
	
    url +=  target + ".inc.htm"
	
	var closeCaption = "schliessen";
	if(lang == 'eng' || lang == 'ENG')
	{
        closeCaption = "close";
    }
	
    var annotationDiv = Builder.node("div", {id: "annotation", className:"annotation"});
    var annotationHeaderDiv = Builder.node("div", { id:"annotationheader", className:"annotationheader"});
    var annotationHeaderContent = Builder.node("p", [ Builder.node("a", {href:"javascript:MMS_CloseAnnotation();"}, closeCaption)]);
		var annotationContent = Builder.node("div", {id:"annotationcontent", className:"annotationcontent"});

    annotationHeaderDiv.appendChild(annotationHeaderContent);
    annotationDiv.appendChild(annotationHeaderDiv);
    annotationDiv.appendChild(annotationContent);
    document.body.appendChild(annotationDiv);

    new Ajax.Updater('annotationcontent', url);							

    new Dialog.Box('annotation');
    
    if(Dialog.Box != null)
    {
        $('annotation').show();
    }
    
    return;
}

function MMS_CloseAnnotation()
{
    $('annotation').hide();
    
    return;
}

/************ Position helper functions ******************/
/**** (see http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html) *****/
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

