var USE_SIFR = true;

var SAFARI_STYLESHEET_REFERENCE = RESOURCES_PATH + "css/styles-safari.css";
var MACOS_STYLESHEET_REFERENCE  = RESOURCES_PATH + "css/styles-macos.css";
var SIFR_SLAB_PATH              = RESOURCES_PATH + "sifr/siemensslab.swf";

var jslog;

/********************************************************************/
/* START: browser detection                                         */
var Info = new function() 
{
	var userAgent = navigator.userAgent.toLowerCase();
	var b = {};
	b.isIE      = userAgent.indexOf("msie") != -1;
	//b.isIE7     = b.isIE && (typeof window.XMLHttpRequest != "undefined");  wrong! Frameworks define it anyway
	b.isIE7     = userAgent.indexOf("msie 7") != -1;
	b.isIE6     = userAgent.indexOf("msie 6") != -1;
	b.isIE5     = userAgent.indexOf("msie 5") != -1;
	// b.isIEpre7  = b.isIE && !b.isIE7;   wrong! What if IE8?
	b.isIEpre7  = b.isIE6 || b.isIE5;
	b.isSafari  = userAgent.indexOf("safari") != - 1;
	b.isMozilla = userAgent.indexOf("gecko") != -1 && b.isSafari === false;
	b.isFirefox = b.isMozilla === true && userAgent.indexOf("firefox") != -1;
	b.isOpera   = typeof window.opera != "undefined"; // || userAgent.indexOf("opera") != -1;
	this.browser = b;
	this.os = {
		isLinux: (navigator.platform.indexOf("Linux") === 0),
		isMac:   (navigator.platform.indexOf("Mac") === 0),
		isWin:   (navigator.platform.indexOf("Win") === 0)
	};
};


Type.registerNamespace("AjaxControlToolkit");



/* END: browser detection                                           */
/********************************************************************/
/* START: serve special styles                                      */

if (Info.browser.isSafari)
{
	document.write ("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + SAFARI_STYLESHEET_REFERENCE + "\" />");
}
if (Info.os.isMac)
{
	document.write ("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + MACOS_STYLESHEET_REFERENCE + "\" />");
}

/* END: serve special styles                                        */
/********************************************************************/
/* START: Fix Flickering Background Images                          */

if (window.createPopup && document.compatMode && document.compatMode=="CSS1Compat" && !window.XMLHttpRequest) {
	try{
		document.execCommand("BackgroundImageCache", false, true);
	} catch(e) {}
}

/* END: Fix Flickering Background Images                            */




/********************************************************************/
Sys.Browser.getWindowSize = function(w)
{
	var width, height;
	w = w ? w : window;
	width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
	return { width: width, height: height };
};

Sys.UI.Point.cumulativeOffset = function(element) 
{
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
};

/* END: Ajax extensions                                             */
/********************************************************************/

/* > > >> >>> INDIVIDUAL FUNCTIONS >>>>> >>>>>>>> */

/********************************************************************/
/* START: layout initalisation                                      */

// inits global vars as std zones and page type
//-------------------------------------------------------------------
function initGlobals() 
//-------------------------------------------------------------------
{
	var ptReg = /^page-type-(.+)$/;

	var bodyClassName = document.body.className;
    if (ptReg.test(bodyClassName)) 
        pageType = bodyClassName.replace(ptReg, "$1");
        
    if(typeof pv_sifr_hasFlash != "undefined" && !pv_sifr_hasFlash)
    {
        var html = document.getElementsByTagName("html")[0];         
        html.className = html.className.replace(/\s*(sIFR-hasFlash)\s*/g, ' '); 
    }
  
    Array.forEach(["content", "header"], function(zoneId)
    {
		try {
			var _zone = $get(zoneId + "-zone");
			if (!_zone) {
				throw ("Implementation Exception: Zone " + zoneId + " is missing.");
			}
			zone[zoneId] = _zone;
		} catch (e) {
			alert(e);
			return false;
		}
    }, this);
    	correctFooterPositionIfNecessary();
	return true;
}

// provides min-width/max-width for IE < 7
//-------------------------------------------------------------------
function initLayoutIEPre7() 
//-------------------------------------------------------------------
{
	var innerWidth = Sys.Browser.getWindowSize().width;
	
	var toolbarElm = $get("toolbar-zone");
	if (toolbarElm) 
		toolbarElm.style.width = innerWidth < 990 ? "916px" : (innerWidth-68) + "px";
    jslog.debug ("Toolbar: Calculated innerWidth="+(innerWidth-916));

	zone.content.style.width = innerWidth > 960 ? "auto" : "960px";
	
    var headervisualElm = $get("headervisual-zone");
    var fluidElm        = $get("fluid-zone");
    
	if (headervisualElm && fluidElm && pageType != "1") 
	{
		var headervisualWidth = Sys.UI.DomElement.getBounds(headervisualElm).width;
		var fluidWidth = Sys.UI.DomElement.getBounds(fluidElm).width;
		
		var realHeaderWidth = headervisualWidth + fluidWidth;
		
		if (innerWidth <= realHeaderWidth) 
		{
			var newWidth = innerWidth;
			newWidth = (newWidth - fluidWidth < 364) ? fluidWidth + 364 : newWidth;
			zone.header.style.width = newWidth + "px";
		} 
		else 
		{
			zone.header.style.width = realHeaderWidth + "px";
		}
	}
}
// inits sifr
//-------------------------------------------------------------------
function initLayoutSifr_old() 
//-------------------------------------------------------------------
{
	/*
	if (typeof sIFR != "function" || Info.browser.isOpera ) return;
	if(typeof pv_sifr_hasFlash != "undefined" && !pv_sifr_hasFlash) return;

	sIFR.replaceElement(named({sSelector:"div.link-list span.sifr", sFlashSrc: SIFR_SLAB_PATH, sColor:"#666666", sHoverColor:"#900000", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr h3", sFlashSrc: SIFR_SLAB_PATH, sColor:"#333333", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-h1 h1", sFlashSrc: SIFR_SLAB_PATH, sColor:"#333333", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-h2 h2", sFlashSrc: SIFR_SLAB_PATH, sColor:"#666666", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-header h1", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-header h2", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr-header h3", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sHoverColor:"#000000", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr h5", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sHoverColor:"#000000", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr .site-id-link", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sHoverColor:"#000000", sWmode:"transparent"}));
	sIFR.replaceElement(named({sSelector:"div.sifr .toolbar-link", sFlashSrc: SIFR_SLAB_PATH, sColor:"#ffffff", sHoverColor:"#000000", sWmode:"transparent"}));
	*/
}

/* END: layout initalisation                                        */
/********************************************************************/
/* START: functional initalisation                                  */
//---------------------------------------------------------------
function initLogo() 
//---------------------------------------------------------------
{
	var logo = $get("logo");
	if(logo != null)
	{
	    var logoLink = logo.firstChild;
	    if(logoLink != null)
	        logo.onclick = function() { window.open(this.href); return false; }
	}
}
//---------------------------------------------------------------
function initContentLayers()
//---------------------------------------------------------------
{
    var links = $get("toolbar-nav").getElementsByTagName("a");
    for(var index = 0; index < links.length; index++)
    {
        var link = links[index];
        var bhv = link.PopupButtonBehavior;
        
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7)
        {
            link.onmouseover = function()
            {
	            if(this.className.indexOf('hover') != -1) 
		            return;
	            this.className = this.className == '' ? 'hover' : this.className + ' hover';
            };
            
            link.onmouseout =  function()
            {
	            if(this.className.indexOf('hover') == -1) 
		            return;
	            this.className = this.className.replace(/\s*(hover)\s*/g, ' ');
            };
        }

        if(bhv != null)
            extendPopupBehavior(bhv);    
    }
}


//---------------------------------------------------------------
function initLanguageSwitchLayer() 
//---------------------------------------------------------------
{
	var bhv = $find("bhvLang");
	if(bhv)
	{
        var popupBehavior = bhv._popupBehavior;
        var elm           = bhv.get_element();    
        var clickHandler  = bhv._focusHandler;
        
               
        if(clickHandler)
        {
            $removeHandler(elm, 'click', clickHandler );
            $removeHandler(elm, 'focus', clickHandler );
            
            bhv._focusHandler = null;
        }
            
        var clickHandler2 = Function.createDelegate(elm, function(e) 
	            {
                    var old = AjaxControlToolkit.PopupControlBehavior.__VisiblePopup;
                    if (old && old._popupBehavior) 
                        __PopupToggle = true;
                        
                    if(clickHandler != null)
                        clickHandler(e);
                }     );

        
	    $addHandler(elm, 'click', clickHandler2); 
        $addHandler(elm, 'focus', clickHandler2); 
        
        bhv._focusHandler = clickHandler2;
        
        popupBehavior.add_showing
        (
            function(bhv)
            {
	            Sys.UI.DomElement.addCssClass($get("multi-language-switch"), "active");
            }

        );
    
        popupBehavior.add_hiding
        (
		    function(bhv)
            {
                var link = bhv._parentElement;
	            var panel = bhv._element;

	            if(!__PopupToggle)
	                HeaderAnimation.registerLayer(panel);

	            Sys.UI.DomElement.removeCssClass ($get("multi-language-switch"), "active");
		    }
        );
    
        popupBehavior.add_hidden
        (
            function()
            {
                if(!__PopupToggle)
                    HeaderAnimation.augment();
                __PopupToggle = false;
            }

        );
        
	}
}

//---------------------------------------------------------------
function initHeaderVisual()
//---------------------------------------------------------------
{	
	var bhv = $find("bhvHme");
	if(bhv)
	{
        bhv.add_populated
        (
            function()
            {
	            initLayoutSifr();
            }
        );
	}

}

var __PopupToggle = false;
//---------------------------------------------------------------
function extendPopupBehavior(bhv)
//---------------------------------------------------------------
{
    var popupBehavior = bhv._popupBehavior;
    var elm           = bhv.get_element();    
    var clickHandler  = bhv._focusHandler;
    var dynamicControl = $get(bhv._DynamicControlID);
    
    bhv.isPopulated = false;
    
    if(clickHandler)
    {
        $removeHandler(elm, 'click', clickHandler );
        $removeHandler(elm, 'focus', clickHandler );
        
        bhv._focusHandler = null;
    }
        
    var clickHandler2 = Function.createDelegate(elm, function(e) 
	{
        var old = AjaxControlToolkit.PopupControlBehavior.__VisiblePopup;
        
        if (old && old._popupBehavior) 
        {
            if(old._popupBehavior == popupBehavior)
                return;
            __PopupToggle = true;
        }
             
        if(clickHandler != null)
            clickHandler(e);
    });

	$addHandler(elm, 'click', clickHandler2); 
    $addHandler(elm, 'focus', clickHandler2); 
    
    bhv._focusHandler = clickHandler2;
    
    bhv.add_populated 
    (
        function(bhv2)
        {	        
            if(bhv2._popupBehavior)
            {
                Sys.UI.DomElement.removeCssClass(dynamicControl, "loading");
                bhv2._popupBehavior.show();
                bhv2._popupBehavior.setupPopup();
            }
            bhv.isPopulated = true;
        }
    );
	      
    popupBehavior.add_showing
    (
        function(bhv2)
        {	                    
	        var link = bhv2._parentElement;
	        var panel = bhv2._element;

	        Sys.UI.DomElement.addCssClass(panel, "active-layer");
            Sys.UI.DomElement.addCssClass(dynamicControl, "loading");
	        Sys.UI.DomElement.addCssClass(link.parentNode, "active");
	        Sys.UI.DomElement.addCssClass(link, "clicked");
        }

    );

    popupBehavior.add_shown
    (
        function(bhv2)
        {
            var panel = bhv2._element;
            HeaderAnimation.registerLayer(panel);
            HeaderAnimation.diminish();

           if( bhv.isPopulated)
           {
                Sys.UI.DomElement.removeCssClass(dynamicControl, "loading");  
           }
           if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) 
           {
                bhv2.show();
                bhv2.setupPopup();
           }
        }

    );
    
    popupBehavior.add_hiding
    (
		function(bhv2)
        {
            var link = bhv2._parentElement;
	        var panel = bhv2._element;
	        
	        if(!__PopupToggle)
	            HeaderAnimation.registerLayer(panel);

	        Sys.UI.DomElement.removeCssClass (panel, "active-layer");
	        Sys.UI.DomElement.removeCssClass(dynamicControl, "loading");
	        Sys.UI.DomElement.removeCssClass (link.parentNode, "active");
	        Sys.UI.DomElement.removeCssClass (link, "clicked");
		}
    );
    
    popupBehavior.add_hidden
    (
        function()
        {
            if(!__PopupToggle)
                HeaderAnimation.augment();
            __PopupToggle = false;
        }

    );

}

/* END: functional initalisation                                    */
/********************************************************************/
/* START: header zone animation  */
var HeaderAnimation = function(){};
HeaderAnimation.registerClass('HeaderAnimation') ;
                                  
//var HeaderAnimation = Class.create();

HeaderAnimation.initialize = function() 
{
	this.layer         = null;
	this.slide         = {}
	this.animate       = true;
	this.augmented     = true;
	var pageTypeProps = pageType.split(" ");
	this.diminishable  = (pageTypeProps[0] == "1" || pageTypeProps[0] == "2" || pageTypeProps[0] == "Home989px" || pageTypeProps[0] == "Entry");
	this.diminish      = (this.diminishable) ? this.diminish_393 : function() {};
	this.augment       = (this.diminishable) ? this.augment_393 : function() {};

	this.toolbarNode = $get("toolbar-nav");
    var toolbarNodeBounds = Sys.UI.DomElement.getBounds(this.toolbarNode.parentNode);
    this.toolbarHeight = toolbarNodeBounds.height;
    
    this._tickHandler = Function.createDelegate(this, this._onTimerTick);
    this._timer = new Sys.Timer();
    this._timer.add_tick(this._tickHandler);
    this._timer.set_interval(100);
}

HeaderAnimation.augment_393 = function() 
{
	if (!this.augmented) {
		if (this.animate) {
			this._toggleAnimated([154, 174, 204, 244, 284, 324, 354, 385, 393]);
		} else {
			this._toggle(393);
		}
		this.augmented = true;
	}
}

HeaderAnimation.diminish_393 = function() 
{
	if (this.augmented) 
	{
		if (this.animate) {
			this._toggleAnimated([363, 313, 263, 213, 183, 163, 152, 144]);
		} else {
			this._toggle(144);
		}
		this.augmented = false;
	}

}

HeaderAnimation.registerLayer = function(layer) 
{
	this.layer = layer;
	if(this.layer) 
	{
		this.layer.style.top = (this.toolbarHeight + Sys.UI.Point.cumulativeOffset(this.toolbarNode)[1]) + "px";
	}
}

HeaderAnimation.unregisterLayer = function() 
{
	this.layer = null;
}

HeaderAnimation._toggle = function(offset) 
{
	this.diminished = !this.diminished;
	this._setOffsets(offset);
}

HeaderAnimation._onTimerTick = function() 
{
    if (this.slide.index >= this.slide.length) 
    {
        this.diminished = !this.diminished;
        this._timer.set_enabled(false);
    } 
    else 
    {
        this._setOffsets(this.slide.offsets[this.slide.index]);
        this.slide.index++;
    }
}

HeaderAnimation._toggleAnimated = function(offsets) 
{
	this.slide.offsets = offsets;
	this.slide.length = offsets.length;
	this.slide.index = 1;

	this._toggle(this.slide.offsets[0]);

    if(this._timer)
        this._timer.set_enabled(true);
}

HeaderAnimation._setOffsets = function(offset) 
{
	document.body.style.backgroundPosition = "0 " + (offset - 393) + "px";
	zone.header.style.height = offset + "px";
	if(this.layer) 
		this.layer.style.top = (this.toolbarHeight + 1 + offset) + "px";
}

/* END: header zone animation                                       */
/********************************************************************/
/* START: register functions */
//---------------------------------------------------------------
var zone = {}; // global hash for standard zones
//var LINK_REL_REGEX   = /^jump-to-(.+)$/;
var pageType = null;


Sys.Application.add_load(
    function()
    {
	    if (!initGlobals()) return false;

        jslog.info ("User agent="+navigator.userAgent.toLowerCase());

	    if (Info.browser.isIEpre7) 
	    {
		    initLayoutIEPre7();
		    Sys.UI.DomEvent.addHandler(window, "resize", initLayoutIEPre7);
	    }
	    HeaderAnimation.initialize(); // animate height
	    initLayoutSifr();
	    //initLogo();
	    initContentLayers();
	    initHeaderVisual();
	    initLanguageSwitchLayer();
    }
);

/* END: register functions                                          */
/********************************************************************/



/********************************************************************/
/* START: canonicalizedUtf8FromUnicode */
// NOTE: Taken from LAYOUTS/1033/search.js
//---------------------------------------------------------------
var i7F = parseInt("0x7F");
var i7FF = parseInt("0x7FF");
var iFFFF = parseInt("0xFFFF");
var i1FFFFF = parseInt("0x1FFFFF");
var i3FFFFFF = parseInt("0x3FFFFFF");
var i7FFFFFFF = parseInt("0x7FFFFFFF");

function canonicalizedUtf8FromUnicode(strURL) 
{
    var strSpecialUrl = " <>\"#%{}|^~[]`&?+";
    var strEncode="";
    var i;
    var chUrl;
    var iCode;
    var num;
    var iCodeBin;
    var tempBin;
    var j, leadingzeros;

    strURL += "";
    for (i=0; i<strURL.length; i++) {
        chUrl = strURL.charAt(i);
        iCode = chUrl.charCodeAt(0);
        if (iCode<=i7F)
        {
            if (strSpecialUrl.indexOf(chUrl)!=-1)
            {

                strEncode+="%"+iCode.toString(16).toUpperCase();
            }
            else
            {

                strEncode+=chUrl;
            }
        }
        else
        {
            leadingzeros="";
            iCodeBin=iCode.toString(2)
            if (iCode<=i7FF)
            {

                for (j=11; j>iCodeBin.length; j--) leadingzeros+="0";
                iCodeBin=leadingzeros+iCodeBin

                tempBin="110"+iCodeBin.substr(0,5);
                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                tempBin="10"+iCodeBin.substr(5,6);
                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
            }
            else
            {
                if (iCode<=iFFFF)
                {

                    for (j=16; j>iCodeBin.length; j--) leadingzeros+="0";
                    iCodeBin=leadingzeros+iCodeBin

                    tempBin="1110"+iCodeBin.substr(0,4);
                    strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                    tempBin="10"+iCodeBin.substr(4,6);
                    strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                    tempBin="10"+iCodeBin.substr(10,6);
                    strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                }
                else
                {
                    if (iCode<=i1FFFFF)
                    {

                        for (j=21; j>iCodeBin.length; j--) leadingzeros+="0";
                        iCodeBin=leadingzeros+iCodeBin

                        tempBin="11110"+iCodeBin.substr(0,3);
                        strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                        tempBin="10"+iCodeBin.substr(3,6);
                        strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                        tempBin="10"+iCodeBin.substr(9,6);
                        strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                        tempBin="10"+iCodeBin.substr(15,6);
                        strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                    }
                    else
                    {
                        if (iCode<=i3FFFFFF)
                        {

                            for (j=26; j>iCodeBin.length; j--) leadingzeros+="0";
                            iCodeBin=leadingzeros+iCodeBin

                            tempBin="111110"+iCodeBin.substr(0,2);
                            strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                            tempBin="10"+iCodeBin.substr(2,6);
                            strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                            tempBin="10"+iCodeBin.substr(8,6);
                            strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                            tempBin="10"+iCodeBin.substr(14,6);
                            strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                            tempBin="10"+iCodeBin.substr(20,6);
                            strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                        }
                        else
                        {
                            if (iCode<=i7FFFFFFF)
                            {

                                for (j=31; j>iCodeBin.length; j--) leadingzeros+="0";
                                iCodeBin=leadingzeros+iCodeBin

                                tempBin="1111110"+iCodeBin.substr(0,1);
                                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                                tempBin="10"+iCodeBin.substr(1,6);
                                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                                tempBin="10"+iCodeBin.substr(7,6);
                                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                                tempBin="10"+iCodeBin.substr(13,6);
                                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                                tempBin="10"+iCodeBin.substr(19,6);
                                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                                tempBin="10"+iCodeBin.substr(25,6);
                                strEncode+="%"+parseInt(tempBin,2).toString(16).toUpperCase()
                            }
                        }
                    }   
                }           
            }
        }
    }
    return strEncode;
}
/* END: canonicalizedUtf8FromUnicode                                          */
/********************************************************************/

//-----------------------------------------------------------------------------------------------
// Corrects the footer-position-wrapper's padding so that the footer does not overwrite the text
//-----------------------------------------------------------------------------------------------
function correctFooterPositionIfNecessary()
{
    var root= document.compatMode=='BackCompat'? document.body : document.documentElement;
    var hasVerticalScrollbar= root.scrollHeight>root.clientHeight;

    jslog.info ("Scrollbar visible="+hasVerticalScrollbar);

    if (hasVerticalScrollbar)  // html document larger than the screen
    {
        jslog.info ("Document larger than screen, correcting footer position");
        var fpw = document.getElementById("footer-position-wrapper");
        if (fpw)
        {
            fpw.style.marginBottom = "0";
        }
    }
}