// +------------------------------------------------------------------------+
// | 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();
        
        if (document.location.hash.match(/^#([a-z0-9_-]+)/i))
        {          
          console.log("@info Hash matched (" + document.location.hash + ")");
          Page.scrollTo(RegExp.$1);
        }
    },
    
    /**
     * 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 ()
    {
        console.log("@info Resized!");
        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 ()
    {
        console.log("@info Scrolling for IE6 initialized");
            
        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($(_sIdentifier));
        
        document.location.hash = _sIdentifier;

        var iNewOffset = aOffset[1] - 132;
        
        if (Element.hasClassName(document.getElementsByTagName('body')[0], 'fixItems'))
        {        
          if (GLOBALS.ie6)
            $('container').scrollTop = iNewOffset;
          else  
            window.scrollTo (0, iNewOffset);
        }
    }
}

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)
				window.open(Event.element(_oEvent));
			else
				window.open(this.href);
			if (_oEvent)
				Event.stop(_oEvent);
		}
  }
}


// +------------------------------------------------------------------------+
// | 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 {
      var aListItems = $$('#dealerSearchContacts ul li.regionContact');
      aListItems.each(Element.hide);
	  var eBrazilHQ = $$('#dealerSearchContacts ul li.reg141');
	  $(eBrazilHQ.first()).show();
	  var aListHeader = aListItems.first();
	  $(aListHeader.parentNode).hide();
	  $(aListHeader.parentNode.previous()).hide();     
    } catch (e){}
  },

  switchRegion : function (_iRegionId)
  {
    try {
      // ~~~~~~~~~~~~~~~~~~~
      // Hide all list items
      // ~~~~~~~~~~~~~~~~~~~    
      var aListItems = $$('#dealerSearchContacts ul li.regionContact');
      aListItems.each(Element.hide);
	  var aListHeader = aListItems.first();
	  $(aListHeader.parentNode).hide();
	  $(aListHeader.parentNode.previous()).hide();     
      
	  aListHeader = aListItems.last();
	  $(aListHeader.parentNode).hide();
	  $(aListHeader.parentNode.previous()).hide();     
	  
      // ~~~~~~~~~~~~~
      // Show selected
      // ~~~~~~~~~~~~~
      var eListItem = $$('#dealerSearchContacts ul li.reg' + _iRegionId);
      $(eListItem.first()).show();    
	  var aListHeaderShow = eListItem.first();
	  $(aListHeaderShow.parentNode).show();
	  $(aListHeaderShow.parentNode.previous()).show();     
	  aListHeaderShow.each(Element.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)
    {
        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);    
    },
	
  
    /**
     * 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);