/************ Search Input Autocompleter ******************/
function MMS_initSearch() {

	searchitems = new Object();
	
	searchitems.de   = ['Energieabsatz','Nettoumsatz','Abschreibungen','Gruppengewinn','Erneuerbare Energien','Energieeffizienz','Grosskraftwerke','Stromhandel','Stromproduktion','Konsolidierte Erfolgsrechnung','Konsolidierte Bilanz','Aktiven','Passiven','Sachanlagen','Immaterielle Anlagen','Beteiligungen an assoziierten Unternehmen','Langfristige Finanzanlagen','Latente Ertragssteuern','AnlagevermÃ¶gen','VorrÃ¤te','Forderungen','Terminguthaben','FlÃ¼ssige Mittel','Wertschriften des UmlaufvermÃ¶gens','Derivative Finanzinstrumente','Zur VerÃ¤usserung gehaltene VermÃ¶genswerte','Rechnungsabgrenzungsposten','UmlaufvermÃ¶gen','EBITDA','EBIT','Aktienkapital','Agio','Eigene Aktien','Gewinnreserven','RÃ¼ckstellungen','Latente Ertragssteuern','Langfristige Finanzverbindlichkeiten','Ãœbrige langfristige Verbindlichkeiten','Langfristiges Fremdkapital','Verbindlichkeiten aus laufenden Ertragssteuern','Kurzfristige Finanzverbindlichkeiten','Ãœbrige kurzfristige Verbindlichkeiten','Derivative Finanzinstrumente','Rechnungsabgrenzungsposten','Kurzfristiges Fremdkapital','Fremdkapital','Eigenkapital','Konsolidierte Mittelflussrechnung','Cashflow','KonsolidierungsgrundsÃ¤tze','Finanzielles Risikomanagement','Finanzinstrumente','Kreditrisikomanagement','LiquiditÃ¤tsrisiko','Marktrisiko','Energie- und Warenaufwand','Personalaufwand','Abschreibungen','Wertminderungen','Finanzergebnis','Ertragssteuern','Sachanlagen','Eigenkapital','RÃ¼ckstellungen','Segmentberichterstattung','Konsolidierungskreis','Rahmenbewilligungsgesuch','Portfoliomanagement','Windpark','Kernkraftwerk','Liberalisierung','Strommarktliberalisierung','Marktliberalisierung','Alpiq','Pumpspeicherkraftwerk','Kleinwasserkraft','Solarturmkraftwerk'];
	
	searchitems.en  = ['Energy sales','Net revenue','Depreciation','Group profit','Renewable energies','energy efficiency','large power stations','Electricity trading','Power generation','Consolidated Income Statement','Consolidated Balance Sheet','Assets','Equity and Liabilities','Tangible fixed assets','Intangible assets','Investments in associates','Long-term financial assets','Deferred income tax assets','Fixed assets','Inventory','Trade and other receivables','Time deposits','Cash','Securities under current assets','Derivative financial instruments','Assets of disposal group classified as held for sale','Accrued assets','Current assets','EBITDA','EBIT','Issued capital','Share premium','Treasury shares','Retained earnings','Provisions','Deferred income tax liabilities','Long-term financial liabilities','Other long-term liabilities','Non-current liabilities','Current income tax liabilities','Short-term financial liabilities','Other short-term liabilities','Derivative financial instruments','Accrued liabilities','Current liabilities','Total liabilities','Equity','Consolidated Cash Flow Statement','Cashflow','Basis of consolidation','Financial risk management','Financial instruments','Credit risk management','Liquidity risk','Market risk','Energy and goods purchased','Personnel expenses','Depreciation','Amortisation and impairment','Finance income','Income taxes','Tangible fixed assets','Equity','Provisions','Segment reporting','Scope of Consolidation','general licence application','portfolio management','wind farm','nuclear power station','liberalisation','liberalisation of the electricity market','market liberalisation','Alpiq','pumped storage power station','small hydroelectric power station','solar tower power station'];
	
	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','libÃ©ralisation du marchÃ©','libÃ©ralisation du marchÃ© de lâ€™Ã©lectricitÃ©','Alpiq','centrale de pompage-turbinage','petite centrale hydroÃ©lectrique','tour solaire'];
	
	searchitems.it   = ['Energia venduta','Fatturato netto','Accantonamenti','Utile del Gruppo','Energie rinnovabili','efficienza energetica','grandi centrali','Commercio di energia elettrica','Produzione di energia elettrica','EBIT','EBITDA','domanda di autorizzazione di massima','gestione del portafoglio','parco eolico','centrale nucleare','liberalizzazione','liberalizzazione del mercato dellâ€™energia','liberalizzazione del mercato','Alpiq','centrale di pompaggio','piccola centrala idroelettrica','centrale a torre solare'];
	
	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() 
  {
    // check for object elements and hide flash objects
    f = document.getElementsByTagName('h1');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "sIFR-replaced") {
         f[i].style.cssText = 'display:none';
         f[i].style.visibility = 'hidden';
       }
    }
    f = document.getElementsByTagName('h2');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "sIFR-replaced") {
         f[i].style.cssText = 'display:none';
         f[i].style.visibility = 'hidden';
       }
    }
    f = document.getElementsByTagName('h3');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "sIFR-replaced") {
         f[i].style.cssText = 'display:none';
         f[i].style.visibility = 'hidden';
       }
    }
    f = document.getElementsByTagName('p');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "title sIFR-replaced") {
         f[i].style.cssText = 'display:none';
         f[i].style.visibility = 'hidden';
       }
    }
          
    this.overlay.style.height = $('container').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);
        
      // check for object elements and show flash objects
    f = document.getElementsByTagName('h1');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "sIFR-replaced") {
         f[i].style.cssText = '';
         f[i].style.visibility = 'visible';
       }
    }
    f = document.getElementsByTagName('h2');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "sIFR-replaced") {
         f[i].style.cssText = '';
         f[i].style.visibility = 'visible';
       }
    }
    f = document.getElementsByTagName('h3');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "sIFR-replaced") {
         f[i].style.cssText = '';
         f[i].style.visibility = 'visible';
       }
    }
    f = document.getElementsByTagName('p');
    for(var i=0; i<f.length; i++){
       if (f[i].className == "title sIFR-replaced") {
         f[i].style.cssText = '';
         f[i].style.visibility = 'visible';
       }
    }

    //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", {id:"closeAnnocation", className:"close", 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, {method:'get', onComplete:onCompleteFunc});			

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

function onCompleteFunc(e) 
{
  var titleAnchor = document.getElementById("annotationcontent");    
    //alert(titleAnchor.nodeName);
    var len = titleAnchor.childNodes.length;
    for(var i = 0; i < len; i++)
    {
      if (titleAnchor.childNodes[i].nodeName == "H2" || titleAnchor.childNodes[i].nodeName == "H3") {
        var replacedTitle = document.createElement("span")
        var attr = document.createAttribute("class");
        attr.nodeValue = titleAnchor.childNodes[i].nodeName;
        replacedTitle.setAttributeNode(attr);
        replacedTitle.innerHTML = titleAnchor.childNodes[i].innerHTML;
        titleAnchor.replaceChild(replacedTitle, titleAnchor.childNodes[i]);
      }
    }					
}

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;
}

