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


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

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

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

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

    /**
     * Initialize website.
     *
     * @return void
     */
    init : function ()
    {
        Object.extend(
            GLOBALS,
            {
                page: env.getPageSize()
            }
        );

        Behaviour.apply();
        Page.scrolling();

        if (document.location.hash.match(/^#([a-z0-9_-]+)/i))
            Page.scrollTo(RegExp.$1);
    },
    
    /**
     * Open external links in a new window.
     *
     * @param  object _oEvent Fired event
     * @return void
     */
    externalLinks : function (_oEvent)
    {
        var oWindow = window.open(this.readAttribute('href'));
        oWindow.focus();

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

            Element.addClassName(eBody, 'fixItems');
            //Element.setStyle(eFooter, {top: iTop+'px'});
            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 eFooter    = $('footer');
        var iScope = Element.getHeight(eContainer);
        var iMinHeight = 632;
        
        // ~~~~~~~~~~~~~~~~~~~~
        // Set height for #body
        // ~~~~~~~~~~~~~~~~~~~~
        if ((iScope <= GLOBALS.page[3] || GLOBALS.page[2] < 1004) && iScope <= iMinHeight)
          $('body').setStyle({height: 632 - Element.getHeight($('header')) - Element.getHeight($(eFooter)) + "px"});

          
        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;

        if (Element.hasClassName(document.getElementsByTagName('body')[0], 'fixItems'))
            window.scrollTo(0, aOffset[1] - 132);
    }
}


// +------------------------------------------------------------------------+
// | Selectbox handling                                                     |
// +------------------------------------------------------------------------+

function handle_selectbox (_iId)
{
    ePulldown = document.getElementById(_iId);
    if (ePulldown.style.display == 'none' || ePulldown.style.display == '')
    {
        ePulldown.style.display = 'block';
    }
    else
    {
        ePulldown.style.display = 'none';
    }
}

// +------------------------------------------------------------------------+
// | Gallery behaviour                                                      |
// +------------------------------------------------------------------------+

var subwindow=0;

function gallery_popup (_ref,_name,_height)
{
	var attribWithoutAll="location=no,menubar=no,toolbar=no,status=no";
		attribWithoutAll+=",resizable=no,scrollbars=no,width=760,height=517";	
	ClosePopUp();
 	subwindow=window.open(_ref,_name,attribWithoutAll);
	 subwindow.moveTo(60,160);
	
}
function ClosePopUp()
{
 	if (!subwindow)
 	return;
 	if (subwindow.closed)
 	return;
 	subwindow.close();
}

// +------------------------------------------------------------------------+
// | Video behaviour                                                      |
// +------------------------------------------------------------------------+


var videosubwindow=0;

function video_popup (_ref,_name,_width,_height)
{
	var attribWithoutAll="location=no,menubar=no,toolbar=no,status=no";
		attribWithoutAll+=",resizable=no,scrollbars=no,width="+_width+",height="+_height;	
	ClosePopUp();
 	videosubwindow=window.open(_ref,_name,attribWithoutAll);
	videosubwindow.moveTo(60,160);
	
}
function ClosePopUp()
{
 	if (!videosubwindow)
 	return;
 	if (videosubwindow.closed)
 	return;
 	videosubwindow.close();
}


// +------------------------------------------------------------------------+
// | Gallery                                                                |
// +------------------------------------------------------------------------+
var Gallery = {

    /**
     * Gallery element.
     *
     * @var element
     */
    eSelf : null,

    /**
     * Gallery list.
     *
     * @var element
     */
    eList : null,

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

    /**
     * Summed up width of all years.
     *
     * @var integer
     */
    iWidth : 0,

    /**
     * Gallery element position in document.
     *
     * @var integer
     */
    iPosition : 0,

    /**
     * Gallery scrolling speed.
     *
     * @var integer
     */
    iSpeed : 0,

    /**
     * Difference between Gallery width and Gallery scope.
     *
     * @var integer
     */
    iDiff : 0,

    /**
     * Gallery scrolling indicator.
     *
     * @var object
     */
    oTimeout : null,

    /**
     * Initialize timeline.
     *
     * @return void
     */
    init : function ()
    {
        Gallery.eSelf = $('galleryThumbs');
        Gallery.eList = Gallery.eSelf.getElementsByTagName('ul')[0];

        // ~~~~~~~~~~~~~~~~~
        // Set tab positions
        // ~~~~~~~~~~~~~~~~~
        Gallery.iWidth = 39 * Gallery.eSelf.getElementsByTagName('li').length;
		
		if(GLOBALS.ie6){
			Gallery.iWidth = 40 * Gallery.eSelf.getElementsByTagName('li').length;
		};
		
        var sCrnt = $('gallery_popup').className;

        var aImage  = Gallery.eList.getElementsByTagName('img');
        var iLength = aImage.length;
        var iIndex  = 0;

        while (iLength--)
        {
            var eImage = aImage[iIndex++];

            if (sCrnt != eImage.id)
                Element.addClassName(eImage, 'alpha');
        }

        // ~~~~~~~~~~~~~~~~~
        // Set gallery width
        // ~~~~~~~~~~~~~~~~~
        Element.setStyle(
            Gallery.eSelf,
            {
                width: (Gallery.iWidth+16)+'px',
                marginLeft: (-1 * (Gallery.iWidth+16) / 2)+'px'
            }
        );
        
        Element.setStyle(
            Gallery.eList,
            {
                width: (Gallery.iWidth)+'px',
                display: 'block',
                left: '-1px'
            }
        );
/*
        Gallery.iScope    = Element.getWidth(Gallery.eSelf) - 50;
        Gallery.iPosition = Position.cumulativeOffset(Gallery.eSelf)[0];
        Gallery.iDiff     = Gallery.iWidth - Gallery.iScope;

        if (Gallery.iDiff <= 0)
            return;

        Element.setStyle(Gallery.eList, {left: (-1 * Gallery.iDiff)+'px'});

        Event.observe(Gallery.eSelf, 'mousemove', Gallery.setSpeed);
        Event.observe(Gallery.eSelf, 'mouseover', Gallery.start);
        Event.observe(Gallery.eSelf, 'mouseout',  Gallery.stop);
*/
    },

    /**
     * Set Gallery scrolling speed.
     *
     * @param  object _oEvent
     * @return void
     */
    setSpeed : function (_oEvent)
    {
        var iPosition = Event.pointerX(_oEvent) - Gallery.iPosition;

        Gallery.iSpeed = Math.round(
            iPosition / (Gallery.iScope / 2) * 100
        ) - 100;

        Gallery.iSpeed *= -1;

        dom.get_element('#header input')[0].value = Gallery.iSpeed;

        if (Gallery.iSpeed >= -20 && Gallery.iSpeed < 20)
            Gallery.iSpeed = 0;
    },

    /**
     * Start Gallery scrolling.
     *
     * @param  object _oEvent
     * @return void
     */
    start : function (_oEvent)
    {
        Gallery.oTimeout = window.setTimeout('Gallery.scroll()', 25);
    },

    /**
     * Stop Gallery scrolling
     *
     * @param  object _oEvent
     * @return void
     */
    stop : function (_oEvent)
    {
        window.clearTimeout(Gallery.oTimeout);

        Gallery.oTimeout = null;

        Element.stopObserving(document, 'mouseup', Gallery.stop);
    },

    /**
     * Execute Gallery scrolling.
     *
     * @return void
     */
    scroll : function ()
    {
        var iLeft = parseInt(
            Element.getStyle(Gallery.eList, 'left').replace(/[a-z]+/,"")
        ) + Math.round(Gallery.iSpeed / 2);

        if (iLeft < Gallery.iDiff * -1)
            iLeft = (Gallery.iDiff * -1) + 1;
        else if (iLeft > 0)
            iLeft = 0;

        Element.setStyle(Gallery.eList, {left : iLeft+ 'px'});

        Gallery.oTimeout = window.setTimeout('Gallery.scroll()', 25);
    }
}



// +------------------------------------------------------------------------+
// | Common ruleset                                                         |
// +------------------------------------------------------------------------+

var RuleSet = {

    /**
     * Drop down boxes
     *
     * @param  element _eElement Anchor element.
     * @return void
     */
    'span.dropDownLabel' : function (_eElement)
    {
        DropDown.pushBox(
            _eElement,
            Element.next(_eElement, 'div.dropDownItems')
        );
    },


    /**
     * Gallery Thumbs
     *
     * @param  element _eElement Product detail view tab.
     * @return void
     */
    '#galleryThumbs' : function (_eElement)
    {
        Gallery.init();
    }
}

Behaviour.register(RuleSet);

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


// +------------------------------------------------------------------------+
// | Quickfinder                                                            |
// +------------------------------------------------------------------------+

var Quickfinder = {

  switchLinks : function (_sAreaName)
  {
    eBereichLabel   = $('quickfinderBereicheDropdown').getElementsByTagName("span");
    eDropdownList   = $('quickfinderLinks').childNodes;
    aLinkDropdowns  = new Array ();

    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],_sAreaName))
      {
        Element.removeClassName(aLinkDropdowns[i], 'hidden');
      }
      else
      {
        Element.addClassName (aLinkDropdowns[i], 'hidden');
      }
    }

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

}

// +------------------------------------------------------------------------+
// | Messen & Veranstaltungen												|
// +------------------------------------------------------------------------+

var Fairs = {
  
  switchYear : function (_iYear)
  {
    eDropdown = $('fairYear').getElementsByTagName('span');    
    eDropdown[0].innerHTML = _iYear;
	eMonthDropdownList = $('monthselect').childNodes;
	aMonthDropdowns = new Array ();
		
	//alle monats dropdowns einsammeln
	for (var i = 0; i < eMonthDropdownList.length; i++)
	{
      if (eMonthDropdownList[i].nodeType == 1)
      {
        aMonthDropdowns.push (eMonthDropdownList[i]);
      }		
	}
	
	for (var i = 0; i < aMonthDropdowns.length; i++)
	{
	  if (aMonthDropdowns[i].id == 'fairMonths' + _iYear)
      {
        Element.removeClassName(aMonthDropdowns[i], 'hidden');
      }
      else
      {
        Element.addClassName(aMonthDropdowns[i], 'hidden');
      }
	}	
  },
  
  switchMonth : function (_iMonth,_sTargetID)
  {
    eDropdown = $(_sTargetID).getElementsByTagName('span');    
    eDropdown[0].innerHTML = _iMonth;
  },
  
  jump : function (_sUrl)
  {
	iYear = $('fairYear').getElementsByTagName('span')[0].innerHTML;
    iMonth = $('fairMonths' + iYear).getElementsByTagName('span')[0].innerHTML; 
    
	try
    {
        $(iMonth + iYear).nodeType == 1;

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

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

$j(document).ready(function(){

	$j('table.lengthTable tr').removeClass('even');
	$j('table.lengthTable tr:odd').addClass('even');
	$j('table.weightTable tr').removeClass('even');
	$j('table.weightTable tr:odd').addClass('even');
	// Tablesorter plugin fuer Gebrauchtmaschinenuebersicht
	$j("table.used_equip").tablesorter();

	//Thumbnail click event fuer Gebrauchtmaschinen
	$j('div#uEGal > div.thumb > img.thumb').click(function(event) 
	{
		$j('img#big').attr("src",$j(this).attr("rel"));
		$j('img#big').removeClass();
		$j('img#big').addClass($j(this).attr("id"));
		$j('div#uEGal > div.thumb').removeClass("active");
		var eThis = $j(this).get(0).parentNode;
		$j(eThis).addClass("active");
	});	
	
	$j('.press_sidebar a.lightbox').lightBox();	

	// weiterempfehlen ajax	
	$j('#recomnd').openDOMWindow({ 
		height:550, 
		width:600, 
		positionType:'fixed', 
		positionTop:30, 
		positionLeft:199, 
		eventType:'click', 
		loader:0, 
		windowSource:'ajax', 
		windowHTTPType:'post',
		windowBGColor:'#EDEDED'
	}); 

	// condition ajax	
	$j('#condition').openDOMWindow({ 
		height:210,
		width:615, 
		positionType:'fixed', 
		positionTop:340, 
		positionLeft:170, 
		eventType:'click', 
		loader:0, 
		windowSource:'ajax', 
		windowHTTPType:'post',
		windowBGColor:'#EDEDED',
		overlayColor:'#FFF',
		overlayOpacity:'0'
	}); 		
	
});

// show / hide content in Used Equipment table
function filterUETypes(_sType, _sText)
{
	// text im dropdown anpassen
	$j('div.UEdropdown span.dropDownLabel').html(_sText);  
	if (_sType == '') 
	{	    
		$j('table.used_equip tbody tr').show();
	}
	else
	{
		$j('table.used_equip tbody tr').hide();
		$j('table.used_equip tbody tr.'+_sType).show();
	}
    
}

