// +------------------------------------------------------------------------+
// | GLOBALS                                                                |
// +------------------------------------------------------------------------+
try {
    GLOBALS.ie6 == GLOBALS.ie7;
}
catch (eExc)
{
    var GLOBALS = {
        ie6: false,
        ie7: false
    };
}



// +------------------------------------------------------------------------+
// | Page                                                                   |
// +------------------------------------------------------------------------+
var Page = {

    /**
     * @var integer
     */
    iScope : 0,

    /**
     * @var element
     */
    eSection : null,

    /**
     * Initialize website.
     *
     * @return void
     */
    init : function ()
    {		
        Object.extend(
            GLOBALS,
            {
                page: env.getPageSize()
            }
        );
        
        if ($('#footerSkirt') && GLOBALS.ie7)
          $('#footerSkirt').setStyle({height: $('groupsDropdownItems').getHeight() + "px"});

        Behaviour.apply();
        DealerSearch.init();
        Page.scrolling();
        Page.anchors();
		
        if (document.location.hash.match(/^#([a-z0-9_-]+)/i))
        {          
          Page.scrollTo(RegExp.$1);
        }
		
		// Fill product dropdowns
		var aHeadlines = jQuery('.productOverview h2.productAnchor');		
		jQuery('div.productOverview .dropDown.standalone .dropDownItems').append('<ul></ul>');
		for (var i = 0; i < aHeadlines.length; i++)
		{
			jQuery('.productOverview .dropDown.standalone .dropDownItems ul').append('<li><a class="anchor" href="#" name="' + 'anc_'+i + '">' + aHeadlines[i].title + '</a></li>');
			jQuery(aHeadlines[i]).addClass("anc_"+i);
		} 
		
		jQuery('span.top').click(function(event) 
		{
			window.scrollTo(0, 0);
		});
		
    },

	
    /**
     * Open external links in a new window.
     *
     * @param  object _oEvent Fired event
     * @return void
     */
    externalLinks : function (_oEvent)
    {    
        if (GLOBALS.ie6 || GLOBALS.ie7 || GLOBALS.ie8)
            window.open(Event.element(_oEvent));
        else
			window.open(this.href);
			
		
			

        if (_oEvent)
            Event.stop(_oEvent);
    },

    /**
     * Window resize event handler.
     *
     * @return void
     */
    resize : function ()
    {
        GLOBALS.page = env.getPageSize();
        Page.scrolling();
    },

    /**
     * Check page scrolling. Fix header and footer if neccessary.
     *
     * @return void
     */
    scrolling : function ()
    {        
        var eBody      = document.getElementsByTagName('body')[0];
        var eFooter    = $('footer');
        var iScope     = Element.getHeight($('container'));

        
        // Calculate minimum height for #body
        var iMinHeight = 632;
        var iHeight    = iMinHeight - Element.getHeight($('header')) - Element.getHeight($(eFooter)) + "px";
        
    
        // ~~~~~~~~~~~~~~~~~~~~
        // Set height for #body
        // ~~~~~~~~~~~~~~~~~~~~
        if ((iScope <= GLOBALS.page[3] || GLOBALS.page[2] < 1004) && iScope <= iMinHeight)
          $('body').setStyle({height: iHeight});
    
    
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // Best pal IE6 needs special treatment
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if (GLOBALS.ie6)
        {
            Page.scrollingIE6();
            return;
        }


        if (iScope <= GLOBALS.page[3] || GLOBALS.page[2] < 1004)
        {
            Element.removeClassName(eBody, 'fixItems');
            Element.setStyle(eFooter, {top: 'auto'});
        }
        else
        {
            Element.addClassName(eBody, 'fixItems');
            Element.setStyle(eFooter, {bottom:'0px'});
        }
    },

    /**
     * Check page scrolling for IE6. Fix header and footer if neccessary.
     *
     * @return void
     */
    scrollingIE6 : function ()
    {
           
        var eHtml      = document.getElementsByTagName('html')[0];
        var eBody      = document.getElementsByTagName('body')[0];
        var eContainer = $('container');
        var iScope = Element.getHeight(eContainer);
        var eFooter    = $('footer');

        // Calculate minimum height for #body
        var iMinHeight = 632;
        var iHeight    = iMinHeight - Element.getHeight($('header')) - Element.getHeight($(eFooter)) + "px";
        
        // ~~~~~~~~~~~~~~~~~~~~
        // Set height for #body
        // ~~~~~~~~~~~~~~~~~~~~
        if ((iScope <= GLOBALS.page[3] || GLOBALS.page[2] < 1004) && iScope <= iMinHeight)
          $('body').setStyle({height: iHeight});

        if (iScope > GLOBALS.page[3] && GLOBALS.page[2] >= 1004)
        {
            Element.addClassName(eHtml, 'fixItems');
            Element.addClassName(eBody, 'fixItems');

            eBody.insertBefore($('header'), eContainer);
            eBody.insertBefore($('footer'), eContainer);
        }
    },
    
    /**
     * Scroll to element
     *
     * @param string
     * @return void
     */
    scrollTo : function (_sIdentifier)
    {
        var aOffset = Position.cumulativeOffset(jQuery(_sIdentifier));
        
        document.location.hash = _sIdentifier;

        var iNewOffset = aOffset[1] - 132;
        
        if (Element.hasClassName(document.getElementsByTagName('body')[0], 'fixItems'))
        {        
          if (GLOBALS.ie6)
            jQuery('container').scrollTop = iNewOffset;
          else  
            window.scrollTo (0, iNewOffset);
        }
    },
	
	 // ~~~~~~~~~~~~~~~~~~~~~~~
	// Custom anchor behaviour
	// ~~~~~~~~~~~~~~~~~~~~~~~
	anchors : function()
	{
		if (document.location.hash.match(/^#([a-z0-9_-]+)/i))
		{
			Page.anchScrollTo(RegExp.$1);
			return
		}
	},
	
	// ~~~~~~~~~~~~~~~~~
	// Scroll to element
	// ~~~~~~~~~~~~~~~~~
	anchScrollTo : function(_sIdentifier)
	{       
		var aOffset = jQuery("a[name='" + _sIdentifier + "']").offset();
		if(!aOffset)
		{
			var aOffset = jQuery("#" + _sIdentifier).offset();
		}
		
		document.location.hash = _sIdentifier;
		
		jQuery('#container').get(0).scrollTop = aOffset.top - 120;   
	}
}

var Quickfinder = {

  switchLinks : function (_sAreaId, _sAreaName)
  {  
    eBereichLabel   = $('quickfinderBereicheDropdown').getElementsByTagName("span");
    eDropdownList   = $('quickfinderLinks').childNodes;
    var aItemLinks = $$('#quickfinderLinks .dropDownItems a');
    aLinkDropdowns  = new Array ();

    if (GLOBALS.ie7 || GLOBALS.ie6)
    {        
      aItemLinks.each(function(s, index) {
         aItemLinks[index].setStyle(
          {width: "auto"}
         );
      }); 
    }
    
    for (var i = 0; i < eDropdownList.length; i++)
    {
      if (eDropdownList[i].nodeType == 1)
      {
        aLinkDropdowns.push (eDropdownList[i]);
      }
    }

    for (var i = 0; i < aLinkDropdowns.length; i++)
    {
      if (Element.hasClassName(aLinkDropdowns[i],_sAreaId))
      {
        Element.removeClassName(aLinkDropdowns[i], 'hidden');
        var iMaxWidth = 0;
        
        if (GLOBALS.ie7 || GLOBALS.ie6)
        {
          eItems = aLinkDropdowns[i].childNodes;
          
          for (var j = 0; j < eItems.length; j++)
          {
            if (eItems[j].nodeType == 1 && $(eItems[j]).hasClassName('dropDownItems'))
            {
              iMaxWidth = $(eItems[j]).getWidth();
            }
          } 
        
          aItemLinks.each(function(s, index) {
             aItemLinks[index].setStyle(
              {width: iMaxWidth + "px"}
             );
          }); 
        }       
      }
      else
      {
        Element.addClassName (aLinkDropdowns[i], 'hidden');
      }
    }

    eBereichLabel[0].firstChild.nodeValue = _sAreaName;
  }
}


var DropDown = {

    /**
     * DropDown box stack.
     *
     * @var array
     */
    aBox : new Array(),

    /**
     * Document event observer registered or not.
     *
     * @var boolean
     */
    bDocumentEvent : false,

    /**
     * Push box to DropDown stock.
     *
     * @param  element _eLabel
     * @param  element _eItem
     * @return void
     */
    pushBox : function (_eLabel, _eItem)
    {
        Event.observe(
            _eLabel,
            'click',
            DropDown.check
        );

        DropDown.aBox.push(
            {
                label  : _eLabel,
                item   : _eItem,
                active : false
            }
        );
    },

    /**
     * Returns the stock-index of given box.
     *
     * @param  element         _eLabel
     * @return integer|boolean
     */
    getIndex : function (_eLabel)
    {
        var iLength = DropDown.aBox.length;
        var iIndex  = 0;

        while (iLength--)
        {
            if (DropDown.aBox[iIndex++].label == _eLabel)
                return iIndex;
        }

        return false;
    },

    /**
     * Open external links in a new window.
     *
     * @param  object _oEvent Fired event
     * @return void
     */
    check : function (_oEvent)
    {
        var eTarget = Event.element(_oEvent);
        var iIndex  = DropDown.getIndex(eTarget);

        if (iIndex && false == DropDown.aBox[iIndex-1].active)
        {
            DropDown.close(null);
            Event.stop(_oEvent);

            DropDown.show(iIndex-1);
        }
    },

    /**
     * Show DropDown items
     *
     * @param  integer _iIndex
     * @return void
     */
    show : function (_iIndex)
    {
        // ~~~~~~~~~~~~~~~~~
        // Show DropDown box
        // ~~~~~~~~~~~~~~~~~
        DropDown.aBox[_iIndex].active = true;

        Element.setStyle(DropDown.aBox[_iIndex].item,{display:'block'});

        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // If not already registered, register document event observer
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        if (!DropDown.bDocumentEvent)
        {
            DropDown.bDocumentEvent = true;

            Event.observe(document, 'click', DropDown.close);
        }
    },

    /**
     * Hide all DropDown items
     *
     * @param  object _oEvent
     * @return void
     */
    close : function (_oEvent)
    {
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // Unregister document event observer
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        DropDown.bDocumentEvent = false;

        Event.stopObserving(document, 'click', DropDown.close);

        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // Run all boxes to close them
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
        var iLength = DropDown.aBox.length;
        var iIndex  = 0;

        while (iLength--)
        {
            if (false == DropDown.aBox[iIndex++].active)
                continue;

            DropDown.aBox[iIndex-1].active = false;

            Element.setStyle(
                DropDown.aBox[iIndex-1].item,
                {display : 'none'}
            );
        }
    }
}

var Streumaster = {

  switchDownload : function (_sUrl, _iId, _sLanguage)
  {
    eDownloadButton = $('ciberTanksDownload' + _iId);
    eDownloadButton.href = _sUrl;

    eDropdownLabel = $('dropdownLabel' + _iId);
    eDropdownLabel.firstChild.nodeValue = _sLanguage;
  },
  
  /*  funktion prueft inhalt des Links auf # und setzt einen Fehler in der Anzeige*/
  
  showError : function (_oEvent)
  {
	eTarget = Event.element(_oEvent);	
	sURL = eTarget.getAttribute('href');
	// substring des href: im letzten byte steht bei nicht gesetzer URL eine #
	
	
	iLengthURL = sURL.length;
	iStartURL = iLengthURL - 1;
	
	if (sURL.substring(iStartURL,iLengthURL) == '#')
		{				
			sErrorID = eTarget.getAttribute('id');			
			eElement = $(sErrorID + 'error');			
			Element.setStyle(eElement,{visibility : 'visible'});
		}
  },
  
  hideError : function (_oEvent)
  {
	eTarget = Event.element(_oEvent);	
	sErrorID = eTarget.getAttribute('id');			
	eElement = $(sErrorID + 'error');			
	Element.setStyle(eElement,{visibility : 'hidden'});
	
  },  
  preventClick : function (_oEvent)
  {
	eTarget = Event.element(_oEvent);	
	sURL = eTarget.getAttribute('href');
	// substring des href: im letzten byte steht bei nicht gesetzer URL eine #
		
	iLengthURL = sURL.length;
	iStartURL = iLengthURL - 1;
	
	if (sURL.substring(iStartURL,iLengthURL) == '#')
		{				
			Event.stop(_oEvent);								
		}
	else
		{			
			if (GLOBALS.ie6 || GLOBALS.ie7 || GLOBALS.ie8)
				window.open(Event.element(_oEvent));
			else
				window.open(this.href);
			if (_oEvent)
				Event.stop(_oEvent);
		}
  }
}

// +------------------------------------------------------------------------+
// | Videoportal			                                                |
// +------------------------------------------------------------------------+
var videoportal = {

  switchDownload : function (_iId, _sUrl, _sLanguage)
  {
    eDownloadButton = $('videoLink_' + _iId);
    eDownloadButton.href = _sUrl;

    eDropdownLabel = $('dropdownLabel_' + _iId);
    eDropdownLabel.firstChild.nodeValue = _sLanguage;
  }

  
}



// +------------------------------------------------------------------------+
// | Exhibitions and events                                                 |
// +------------------------------------------------------------------------+
var Fairs = {
  
  switchYear : function (_iYear)
  {
    eDropdown = $('fairYear').getElementsByTagName('span');    
    eDropdown[0].innerHTML = _iYear;
  },
  
  switchMonth : function (_iMonth)
  {
    eDropdown = $('fairMonth').getElementsByTagName('span');    
    eDropdown[0].innerHTML = _iMonth;
  },
  
  jump : function (_sUrl)
  {
    iMonth = $('fairMonth').getElementsByTagName('span')[0].innerHTML; 
    iYear = $('fairYear').getElementsByTagName('span')[0].innerHTML;

    try
    {
        $(iMonth + iYear).nodeType == 1;

        var aOffset = Position.cumulativeOffset($(iMonth + iYear));

        document.location.hash = iMonth + iYear;
        window.scrollTo(0, aOffset[1] - 130);
    }
    catch (exc) {}
  }
  
}

var Branches = {

  switchBranch : function (_sBranch)
  {

    $('branchDropDownContact').getElementsByTagName('span')[0].innerHTML = _sBranch;
    $('inputBranch').value = _sBranch;
  }
}

var Contact = {

  switchLanguage : function (_sLanguage, _iBranchIndex, _sOverwrite)
  {    
    if (_sLanguage == '')
      sLabel = _sOverwrite;
    else
      sLabel = _sLanguage;
    
    $('langDropDown[' +_iBranchIndex+ ']').getElementsByTagName('span')[0].innerHTML = sLabel;

    $('brochureLanguage[' +_iBranchIndex+ ']').value = _sLanguage;
  }
}

/// +------------------------------------------------------------------------+
// | DealerSearch                                                           |
// +------------------------------------------------------------------------+
var DealerSearch = {

  init : function ()
  {
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Display Brazil HQ only ( matched by ID!, careful on changes)
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    try {
	  // ~~~~~~~~~~~~~~~~~~~
      // Hide all items
      // ~~~~~~~~~~~~~~~~~~~   
      var aListItems = $$('#dealerSearchContacts ul li.regionContact');
      jQuery(aListItems).each(function() {
		jQuery(this).hide();
		jQuery(this).parent().hide();
		jQuery(this).parent().prev().hide();
      });
	  // ~~~~~~~~~~~~~
      // Show selected - default: Brazil 
      // ~~~~~~~~~~~~~
	  var eBrazilHQ = $$('#dealerSearchContacts ul li.reg141');
	  jQuery(eBrazilHQ).each(function(){
		jQuery(this).show();
		jQuery(this).parent().show();
		jQuery(this).parent().prev().show();
	  });
     } catch (e){}
  },

  switchRegion : function (_iRegionId)
  {
    try {
    	  // ~~~~~~~~~~~~~~~~~~~
      // Hide all items
      // ~~~~~~~~~~~~~~~~~~~   
      var aListItems = $$('#dealerSearchContacts ul li.regionContact');
      jQuery(aListItems).each(function() {
		jQuery(this).hide();
		jQuery(this).parent().hide();
		jQuery(this).parent().prev().hide();
      });
	  // ~~~~~~~~~~~~~
      // Show selected - default: Brazil 
      // ~~~~~~~~~~~~~
	  var eBrazilHQ = $$('#dealerSearchContacts ul li.reg' + _iRegionId);
	  jQuery(eBrazilHQ).each(function(){
		jQuery(this).show();
		jQuery(this).parent().show();
		jQuery(this).parent().prev().show();
	  });
	  	  
    } catch (e) {}
  }

}


// +------------------------------------------------------------------------+
// | Search form                                                            |
// +------------------------------------------------------------------------+
var Search = {
    
    /**
     * Toggle search field value
     *
     * @param  event _oEvent
     * @return void
     */
    toggleValue : function (_oEvent)
    {
      if (this.value != "")
        this.value = "";
      else
        this.value = this.className;
    },
    
    /**
     * Toggle help window
     *
     * @param  event _oEvent
     * @return void
     */
    toggleHelp : function (_oEvent)
    {
      $('search_help').toggleClassName('hidden');
    }

}

var RuleSet = {

    /**
     * Open external links in a new window.
     *
     * @param  element _eElement Anchor element.
     * @return void
     */
    'a.ext' : function (_eElement)
    {
		if(!GLOBALS.ie8)
			Event.observe(_eElement, 'click', Page.externalLinks);
    },

    
    /**
     * Display errors at ciber tanks page
     *
     * @param  element _eElement Link element.
     * @return void
     */
  	'#ciberTanksDownload0' : function (_eElement)
  	{	
  	  Event.stopObserving(_eElement, 'click', Page.externalLinks);
  	  Event.observe(_eElement, 'mouseover', Streumaster.showError);	
  	  Event.observe(_eElement, 'click', Streumaster.preventClick);		  
  	  Event.observe(_eElement, 'mouseout', Streumaster.hideError);
  	},		
    
    'div.ciberTanksDownload a.ext' : function (_eElement)
    {
  	  Event.stopObserving(_eElement, 'click', Page.externalLinks);
  	  Event.observe(_eElement, 'mouseover', Streumaster.showError);	
  	  Event.observe(_eElement, 'click', Streumaster.preventClick);		  
  	  Event.observe(_eElement, 'mouseout', Streumaster.hideError);    
    },
	
	// error handling Videoportal links
	'div.jobreportsDL a.downloadLink' : function (_eElement)
    {
  	  Event.observe(_eElement, 'mouseover', Streumaster.showError);	  	  
  	  Event.observe(_eElement, 'mouseout', Streumaster.hideError);    
    },	
  
    /**
     * Drop down boxes
     *
     * @param  element _eElement Anchor element.
     * @return void
     */
    'span.dropDownLabel' : function (_eElement)
    {
        DropDown.pushBox(
            _eElement,
            Element.next(_eElement, 'div.dropDownItems')
        );
    },
    
    
    /**
     * Remove content when hovering search field
     *
     * @param  element _eElement Input element.
     * @return void
     */
    '#search input' : function (_eElement)
    {
      Event.observe(_eElement, 'focus', Search.toggleValue);
      Event.observe(_eElement, 'blur', Search.toggleValue);
      Event.observe(_eElement, 'mouseover', Search.toggleHelp);
      Event.observe(_eElement, 'mouseout', Search.toggleHelp);      
    }
    
}

Behaviour.register(RuleSet);

Event.observe(window , 'load', Page.init);
Event.observe(window , 'resize', Page.resize);

// +------------------------------------------------------------------------+
// | Videoportal			                                                |
// +------------------------------------------------------------------------+

jQuery(document).ready(function(){
	jQuery('#videoportal a.downloadLink').click(function(event){
		var myPlayer = jQuery(this).attr("rel");
		var myCloseButton = jQuery(this).attr("rev");
		var myFLV = jQuery(this).attr("href");
		event.preventDefault();
		//notbremse für flashbox bei nicht ausgewähltem Video (href endet dann auf #)	
		iLengthMyFLV = myFLV.length;
		iStartMyFLV = iLengthMyFLV - 1;
		
		if (myFLV.substring(iStartMyFLV,iLengthMyFLV) != '#') {

			// IE css special
			if(jQuery.browser.msie) {			
				jQuery('body').attr("style","overflow:visible !important;");					
			}
			// Masse holen und ablegen
			var iBodyWidth = jQuery('html').width();
			var iBodyHeight = jQuery(document).height();
			
			// Differenzen (erstmal static)
			var iTopOffset = (iBodyHeight - 360) / 2;
			// Offset fuer Overlay (body ist relative)
			var iLeftOffset = ((iBodyWidth - jQuery('body').width()) / 2);
			jQuery('body').append('<div id="jquery-overlay" style="left:-'+iLeftOffset+'px; background-color: rgb(0, 0, 0); width:'+iBodyWidth+'px; height:'+iBodyHeight+'px;"/><div id="jquery-lightbox"><div id="lightbox-container-image-box" style="background-color: transparent;top:'+iTopOffset+'px;"><div id="lightbox-container-image" style="background-color: white;"></div></div></div>');
			jQuery('#lightbox-container-image-box').height(380);
			jQuery('#lightbox-container-image-box').width(500);
			jQuery('#lightbox-container-image').flash({
					swf: myPlayer,
					width: '480',
					height: '360',
					wmode: 'transparent',
					quality: 'high',
					allowfullscreen: 'true',
					flashvars: {   
								width: '480',
								height: '360',
								allowfullscreen: 'true',
								autostart: 'true',
								frontcolor: '0XFFFFFF',
								backcolor: '0x8D969F',
								file: myFLV	
							}
				});			
			jQuery('#lightbox-container-image-box').append('<p id="lightbox-secNav-btnClose" style="color:white;cursor:pointer;height:10px;padding-top:5px;text-align:right;width:auto;"><strong>X '+myCloseButton+'</strong></p>');		
			jQuery('#lightbox-secNav-btnClose,#jquery-overlay').live('click', function(event) {		
				jQuery('#jquery-overlay').remove();
				jQuery('#jquery-lightbox').remove();
			// IE css special
			if(jQuery.browser.msie) {				
				jQuery('body').attr("style","");					
			}
			});
		}
	});
	
	// livequery fuer Anchors im Produktbereich (dropdowns)
	jQuery('a.anchor').livequery('click', function(event) 
	{
		event.preventDefault();
		var oOffset = jQuery('.'+ jQuery(this).attr("name")).offset();
		/*jQuery(this).parent().parent().parent().parent().find('.dropDownLabel').text(jQuery(this).text());*/
		window.scrollTo(0, oOffset.top - 130);
	});
	
});
