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";
		}
	}
}

// deprecated: inits sifr
//-------------------------------------------------------------------
function initLayoutSifr_old() 
//-------------------------------------------------------------------
{
	
}

/* END: layout initalisation                                        */
/********************************************************************/
/* START: functional initalization                                  */
//---------------------------------------------------------------
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()
//---------------------------------------------------------------
{
    // init behaviours of all buttons in the toolbar-nav zone
    var toolbarNav = $get("toolbar-nav");
    if(toolbarNav != null)
    {
        var links = toolbarNav.getElementsByTagName("a");
        for(var index = 0; index < links.length; index++)
        {
            var link = links[index];
            var bhvLink = link.PopupButtonBehavior;
            if(bhvLink != null)
                extendPopupBehavior(bhvLink, true);    
        }
    }
    
    
    var siteIdZone = $get("site-id-zone");
    if (siteIdZone != null)
    {
        var siteIdLinks = siteIdZone.getElementsByTagName("a");
        for(var index = 0; index < siteIdLinks.length; index++)
        {
            var bhvLink = siteIdLinks[index].PopupButtonBehavior;
            if(bhvLink != null)
                extendPopupBehavior(bhvLink, true);  
        }
    }
    
    var bhvSiteExplorer = $find("bhvSiteExplorer");
	if(bhvSiteExplorer)
	    extendPopupBehavior(bhvSiteExplorer, true); 
}
//---------------------------------------------------------------
function initLanguageSwitchLayer() 
//---------------------------------------------------------------
{
	var bhv = $find("bhvLang");
	
	if(bhv)
	{
        extendPopupBehavior(bhv, false);
        
        var popupBehavior = bhv._popupBehavior;
        
        popupBehavior.add_showing
        (
            function(sender, eventArgs)
            {
	            Sys.UI.DomElement.addCssClass($get("multi-language-switch"), "active");
            }

        );
    
        popupBehavior.add_hiding
        (
		    function(sender, eventArgs)
            {
	            Sys.UI.DomElement.removeCssClass ($get("multi-language-switch"), "active");
		    }
        ); 
	}
}
//---------------------------------------------------------------
function initHeaderVisual()
//---------------------------------------------------------------
{
	var bhv = $find("bhvHme");
	if(bhv)
	{
        bhv.add_populated
        (
            function()
            {
                if (typeof initLayoutSifr == "function")
                {
	                initLayoutSifr();
	            }
            }
        );
	}

}
//---------------------------------------------------------------
function extendPopupBehavior(bhv, animateHeader)
//---------------------------------------------------------------
{    
    var popupBehavior = bhv._popupBehavior;
    popupBehavior.animateHeader = animateHeader;

    popupBehavior.add_shown
    (
        function(sender, eventArgs)
        {
            var panel = sender._element;
            if(sender.animateHeader) 
            {
                HeaderAnimation.registerLayer(panel);
                HeaderAnimation.diminish();
            } 
        }
    );
    
    popupBehavior.add_hiding
    (
		function(sender, eventArgs)
        {
	        var lastClicked = AjaxControlToolkit.PopupControlBehavior.__LastClickedPopup;        
            if (lastClicked && lastClicked._popupBehavior &&
                lastClicked._popupBehavior != sender )
            {
                return;
	        }
	        
            var panel = sender._element;
            HeaderAnimation.registerLayer(panel);
		}
    );
        
    popupBehavior.add_hidden
    (
        function(sender, eventArgs)
        {
            var lastClicked = AjaxControlToolkit.PopupControlBehavior.__LastClickedPopup;
            if (lastClicked && lastClicked._popupBehavior &&
                lastClicked._popupBehavior != sender )
            {
                return;
	        }
	        
	        HeaderAnimation.augment();
        }

    );

}
/* 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
	    if (typeof initLayoutSifr == "function")
	    {
	        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                                          */
/********************************************************************/

//-----------------------------------------------------------------------------------------------
// Shows the region selector (works around Microsoft AJAX ignoring sIFR content)
//
// Parameter sifrdObject: Object that caused the click event
//-----------------------------------------------------------------------------------------------
function showRegionSelector(sifrdObject)
//-----------------------------------------------------------------------------------------------
{
    // The onFocus event is the default reaction to a click on an object using the popup button extender
    var h5 = sifrdObject.getAncestor(); 
    var siteIdZone = h5.parentNode.parentNode;
    if (typeof siteIdZone.PopupButtonBehavior != "undefined" && siteIdZone.PopupButtonBehavior != null)
    {
        siteIdZone.PopupButtonBehavior._onFocus();
    }
    else
    {
        jslog.error("Unable to open popup from Site Identifier, structure unexpected.");
    }
}


//-----------------------------------------------------------------------------------------------
// 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";
        }
    }
}


