// --- Structure of the javascript: -------------------------------------------
// -jquery.min.js - all jquery modules reside in jquery.min.js
// -default.js ---- in this doc the jquery widgets are initialized and if needed
// ---------------- altered togehter with other functions. They are sorted by
// ---------------- FUNCTIONS FOR SIDEWIDE CONTENT and
// ---------------- FUNCTIONS FOR SINGLE MODULES 
// ---------------- At the bottom all the functions are called in a $(document).ready(function(){});
// ---------------- This way the functions can also be excluded and called from a special
// ---------------- external print.js or screen.js in order to implement only the needed functions.




// ----------------------------------------------------------------------------
// --- FUNCTIONS FOR SIDEWIDE CONTENT -----------------------------------------
// ----------------------------------------------------------------------------

// --- dropdown lanuage chooser -----------------------------------------------
// sets width & needs to run after window is loaded
function setLanguageWidth() { 
  var openerW = $("#opener").width()+36;
  var listW = $("#languageList").width();

  if ( openerW > listW ) { $("#languageList").width(openerW); }
  if ( openerW < listW ) { $("#opener").width(listW-36); }
  // IE6 loading problem leads to wrong width. Fixed width is set as a result.
  if ( listW > 200 || openerW > 200 ) {
    $("#languageList").width(80);
    $("#opener").width(44);
  }
  
  $("#drawerOpener").click(function(){
    return false;
  });
}


// --- flashmap drawer --------------------------------------------------------
function openDrawer() {
  if ($("").length > 0){
    
  }
    
  $("#drawerOpener").click(function(){
    if ($("#Header .groupLink").length > 0){
      $("#Header .groupLink").css('visibility', 'hidden');
      $(".n_Global_Navigation_Map .n_Global_Navigation").show();
    }
    $("#drawer").animate({ top: '0px' }, 800 );return false;
  });
  $(".openDrawerLink").click(function(){
    if ($("#Header .groupLink").length > 0){
      $("#Header .groupLink").css('visibility', 'hidden');
      $(".n_Global_Navigation_Map .n_Global_Navigation").show();
    }
    $("#drawer").animate({ top: '0px' }, 800 );return false;
  });
  if ($("#GlobalHomePage").length > 0){
    $("#drawerCloseLine").click(function(){
      return false;
    });
    $("#drawerCloseText").click(function(){
      return false;
    });
  }
  else {
    $("#drawerCloseLine").click(function(){
      if ($("#Header .groupLink").length > 0){
        setTimeout(function() {
          $("#Header .groupLink").css('visibility', 'visible');
          $(".n_Global_Navigation_Map .n_Global_Navigation").hide();
        }, 800);
      }
      $("#drawer").animate({ top: '-421px' }, 800 );return false;
    });
    $("#drawerCloseText").click(function(){
      if ($("#Header .groupLink").length > 0){
        setTimeout(function() {
          $("#Header .groupLink").css('visibility', 'visible');
          $(".n_Global_Navigation_Map .n_Global_Navigation").hide();
        }, 800);
      }
      $("#drawer").animate({ top: '-421px' }, 800 );return false;
    });
  }
}

function openDrawerLink() {
  $("#drawer").animate({ top: '0px' }, 800 );
}


// --- labeled Inputs ---------------------------------------------------------
// a lable inside the input is displayed & hidden onSelect
function labeledInputs() {  
  $("#searchField, #searchFieldContent").focus(function () {
    $(this).addClass("focus");
    if (this.value == this.defaultValue){this.value = '';}
    if(this.value != this.defaultValue){this.select();}
  }).blur(function () {
    if ($.trim(this.value) == ''){
      $(this).removeClass("focus");
      $(this).removeClass("filled");
      this.value = (this.defaultValue ? this.defaultValue : '');
    } 
    else {$(this).removeClass("focus").addClass("filled");}
  });
}


// --- Content_Teaser_Group row divider ---------------------------------------------------------
function contentTeaserRows() {
  //$(".m_Content_Teaser:nth-child(odd)").addClass("oddElement");
  $(".grid_6_container.m_Content_Teaser_Group > .grid_3:odd").after("<div class='clearRow'></div>");
  $(".grid_9_container.m_Content_Teaser_Group > .grid_3:nth-child(3n)").after("<div class='clearRow'></div>");
  $(".grid_12_container.m_Content_Teaser_Group > .grid_4:nth-child(3n)").after("<div class='clearRow'></div>");
}


// --- hoverExtention for browsers with lack of :hover support ----------------
// yes, this is for IE (and opera at some point)
function hoverExtention() {
  $(".m_CTG_Images a").hoverIntent(
    function () {$(this).addClass("hover");},
    function () {$(this).removeClass("hover");}
  );
  $(".iconButton").hoverIntent(
    function () {$(this).addClass("hover");},
    function () {$(this).removeClass("hover");}
  );
  $(".acc_Opener").hoverIntent(
    function () {$(this).addClass("acc_Opener_Hover");},
    function () {$(this).removeClass("acc_Opener_Hover");}
  );
}



// ----------------------------------------------------------------------------
// --- FUNCTIONS FOR SINGLE MODULES -------------------------------------------
// ----------------------------------------------------------------------------


// --- advanced Search ---------------------------------------------------------

function advancedSearch() {

$(".m_Advanced_Search .advancedSearchLink").click(function(){
  $(".advancedSearchContainer").slideDown(300);
  $(".advancedSearchLink").hide();
  $(".hideSearchLink").show();
  return false;
});
$(".m_Advanced_Search .hideSearchLink").click(function(){
  $(".advancedSearchContainer").slideUp(300);
  $(".hideSearchLink").hide();
  $(".advancedSearchLink").show();
  resetDefaultSelects();
  return false;
});
$(".m_Advanced_Search .resetSearchLink").click(function(){
  resetDefaultSelects();
  return false;
});
}


// --- selectContactAddress functionality in module m_Form --------------------
// in the contact form the user can select a contact. This will be 
// displayed after selection is made.
function selectContactAddress() {
  $(".contactInformation div").hide();
  SelectValue = $(".contactSelect").val();
  $(".contactInformation div#" + SelectValue ).show();
  if ($("#m_googleMap").length > 0) {showLocation();}
  if ($("#m_contactMap").length > 0) { showLocation();}

  $(".contactSelect").change(function(){
    SelectValue = $(".contactSelect").val();
    setHeightContact = $(".contactInformation div#" + SelectValue ).height();
    $(".contactInformation").height(setHeightContact);
    $(".contactInformation div").hide();
    $(".contactInformation div#" + SelectValue ).show();
    
    // script for Map inside Content 
    if ($("#Content #m_googleMap").length > 0) {
      // route page
      if ($(".m_Google_Route #m_googleMap").length > 0) {
        valOrigin = $("#iOrigin").val();
        valDestination = $("#iDestination").val();
        if ($.trim(valOrigin) == '' || $.trim(valDestination) == ''){
          showLocation();
        }
        if ($.trim(valOrigin) != '' && $.trim(valDestination) != ''){
          dropdownReloadRouteSearch();
        }
      }
      // contact page
      else {
        showLocation();
      }
    }
    
    return false;
  });
}


// -- newsletter form switcher ------------------------------------------------
// when a input is selected the javascript will show the corresponding form
function newsletterFormSwitcher() {
  $("input[name='newsletter']").click( function() {
    if ($("input:checked").val() == "newNL") {
      $(".newNL").show();
      $(".changeNL").hide();
    }
    if ($("input:checked").val() == "changeNL") {
      $(".changeNL").show();
      $(".newNL").hide();
    }
  });
}


// --- contentAccordion for m_Content_Accordion & Sitemap -----------------
function contentAccordion() {
  //m_Content_Accordion
  $(".acc_Content").hide();
  $(".acc_Content:first").show();  
  $(".acc_Header").toggle(function(){$(this).addClass("active");}, function () {$(this).removeClass("active");});
  $(".acc_Header").click(function(){$(this).next(".acc_Content").slideToggle("slow");});
  //sitemap
  $(".has_Accordion ul").hide();
  
  $(".has_Accordion .acc_Opener").toggle(function(){$(this).addClass("active");}, function () {$(this).removeClass("active");});
  $(".has_Accordion .acc_Opener").click(function(){
    $(this).parent().children("ul").slideToggle("slow");
    });
};


// --- lindeStandards swaps a list with a dropdown (m_Linde_Standards) --------
function lindeStandards() {
  $(".m_Linde_Standards .firstCat").show();

  $(".m_Linde_Standards .firstCat a").click(function(){
    $(".m_Linde_Standards .firstCat").hide();
    $(".m_Linde_Standards .firstCatSelect").show();
    $(".m_Linde_Standards .secondCat").show();
    return false;
  });
  $(".m_Linde_Standards .secondCat a").click(function(){
    $(".m_Linde_Standards .secondCat").hide();
    $(".m_Linde_Standards .secondCatSelect").show();
    $(".m_Linde_Standards .thirdCat").show();
    return false;
  });
  $(".m_Linde_Standards .thirdCat a").click(function(){
    $(".m_Linde_Standards .thirdCat").hide();
    $(".m_Linde_Standards .thirdCatSelect").show();
    $(".m_Linde_Standards .fourthCat").show();
    return false;
  });
}


// --- function for product finder dropdowns ------------------------------------------------------------

function productFinder() {
  $('.m_Product_Finder .listOpener').click( function() {
    if ( $(this).parent().children('.productList').hasClass('openList') == false ) {
      $('.productList').removeClass('openList').hide();
      $('.productFinderItem').css('z-index','1');
      $(this).parent().css('z-index','310');
      $(this).parent().children('.productList').addClass('openList').show();
      $(this).parent().focus();
    }
    else {
      $('.productList').removeClass('openList').hide();
    }
    
    $("body").click(function(){
      $('.productList').removeClass('openList').hide();
    });

    // Prevent events from getting pass .productList
    $(this).closest('.productList').click(function(e){
      e.stopPropagation();
    })
    
    return false;
  });
}


// --- Splitting up ULs in the content area into multiple columns --------------
function splitColumns() {
  $('.splitList').each(function() {
    $(this).addClass('splitScriptList');
    var colsize = Math.round($(this).find("li").size() / 2);
    $(this).find("li").each(function(i) {
      if (i>=colsize) { $(this).addClass('rightCol');}
    });
    $(this).find('.rightCol').insertAfter(this).wrapAll("<ul class='splitList splitScriptList rightList'></ul>").removeClass("rightCol");
    $(this).after("<div></div>");
  });
}

function splitSitemap() {
  $('.splitSitemap').each(function() {
    $(this).find("li").addClass('splitSitemapItem');
    $(this).find(".has_Accordion li").removeClass('splitSitemapItem');
    var length_sitemap = Math.round($(this).find(".splitSitemapItem").size() /3);
    var right_Column = length_sitemap * 2;
    $(this).find(".splitSitemapItem").each(function(i) {
      if (i>=right_Column) { $(this).addClass('rightCol');}
    });
    $(this).find(".splitSitemapItem").each(function(i) {
      if (i<right_Column && i>=length_sitemap) { $(this).addClass('middleCol');}
    });
    $(this).find('.rightCol.top_Sitemap_Navigation').insertAfter(this).wrapAll("<ul class='splitSitemap grid_3'></ul>");
    $(this).find('.middleCol.top_Sitemap_Navigation').insertAfter(this).wrapAll("<ul class='splitSitemap grid_3'></ul>");
    $(this).find('.rightCol').removeClass("rightCol splitSitemapItem");
    $(this).find('.middleCol').removeClass("middleCol splitSitemapItem");
  });
}

function getParameters(){
	var	settingsObject = {},
	hash,
	hashes = location.search.substring(1).split(/&/);
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		settingsObject[hash[0]] = hash[1];
	}
	return settingsObject;
}
// --- initialize swf files ------------------------------------------------------------

// params for all
params = {};
params.quality = "high";
params.wmode = "transparent";
params.allowfullscreen = "false";
params.allowscriptaccess = "sameDomain";
// params for map
if ($(".n_Global_Navigation_Map").length > 0) {params.bgcolor = "#e5edef";}


// --- set height of Main_navigation for IE & multicolumns for dropdown navi -----------

function setMainNavigationHeight() {
  mainNavigationHeight = $(".n_Main_Navigation").height();
  $(".print_navigation_bg img").height(mainNavigationHeight);
  $(".print_navigation_bg").show();
  
  if ($(".dropdown_Navigation").length > 0) {
    $("#Header").css({'z-index' : '650'});    
    
    $('.dropdown_Navigation').each(function() {
      dropdownItems = $(this).find("li").size();
      right_Column = Math.round($(this).find("li").size()/2);
      
      if (dropdownItems >= 9) {
        $(this).addClass('split_Dropdown');
        multilineVar = 0;
        alldropdownItemsHeight = 0
        
        $(this).find("li").each(function(i) {
          if (i >= right_Column) {
            $(this).addClass('rightCol');
            
            dropdownItemHeight = $(this).height()+10;
            //$(this).addClass('h_'+dropdownItemHeight);
            alldropdownItemsHeight = alldropdownItemsHeight + dropdownItemHeight;
            //$(this).addClass('dd_'+alldropdownItemsHeight);
            // $("#Service").prepend("h_" + alldropdownItemsHeight + "<br />");
            
            $(this).css('top',((i-right_Column)*23)+15+multilineVar);
            if( dropdownItemHeight > 34 ) {multilineVar = multilineVar + 14}
            //$(this).addClass('v_'+multilineVar);
            // $("#Service").prepend("z_" + ($(this).height()+10) + " -> ");
          }
          
          if ( (i == (right_Column-1)) || (i == (dropdownItems-1)) ) {
            $(this).addClass('last-child');
          }
          
        });
        dropdownHeight = $(this).height();
        if (dropdownHeight <= (alldropdownItemsHeight)) {$(this).height(alldropdownItemsHeight-7);}
      }
      
      NaviItemPosition = $(this).parent().position().left;
      NaviItemDropdown = $(this).width()+32;
      NaviListPostion = Math.round(955 - (NaviItemPosition + NaviItemDropdown));
      if ( NaviItemPosition > (955 - NaviItemDropdown)) {
        //$("#Service").prepend( MenueItemDropdown + " <br /> " + MenueItemPosition+ " <br /> " +(955 - (MenueItemPosition + MenueItemDropdown)));
        $(this).css("left", NaviListPostion );
      }
    });
    
  }
}


// ----------------------------------------------------------------------------
// --- DOCUMENT READY ---------------------------------------------------------
// ----------------------------------------------------------------------------

$(document).ready(function(){

// JAVASCRIPT FOR SITEWIDE ELEMENTS

  // --- dropdown lanuage chooser ---------------------------------------------
  // initialising dropdown
  setLanguageWidth();
  $('ul.sf-menu').superfish({ 
    delay: 900   // delay on mouseout 
  });

  // --- flashmap drawer ------------------------------------------------------

  openDrawer();
  $('#drawer').bgiframe();


  // --- labeled Inputs -------------------------------------------------------
  labeledInputs();
  contentTeaserRows();

  // --- hoverExtention for browsers with lack of :hover support --------------
  hoverExtention();


  // --- bookmark page -------------
  $('.bookmarkButton').jFav();



// JAVASCRIPT FOR SINGLE MODULES

  // --- advanced Search ---------------------------------------------------------
  advancedSearch()

  // --- disclaimer -----------------------------------------------------------

  $("#accept").click(function(){
    if ($("#accept:checked")) {
      var date = new Date();
      date.setTime(date.getTime()+(2000));
      var expires = "; expires="+date.toGMTString();
      document.cookie = "chkChecked"+"="+"active"+expires+"; path=/";
      window.location.reload();                          
    }
  });

  // --- selectContactAddress functionality in module m_Form ------------------
  selectContactAddress();

  // -- newsletter form switcher ----------------------------------------------
  newsletterFormSwitcher();

  // --- contentAccordion for m_Content_Accordion & Sitemap -------------------
  contentAccordion();

  // --- accordion for m_Task_Accordion ---------------------------------------
  $(".accordionList").accordion({ fillSpace: true });

  // --- lindeStandards swaps a list with a dropdown (m_Linde_Standards) ------
  lindeStandards();

  // --- function for product finder dropdowns ------------------------------------------------------------
  productFinder();

  // --- Splitting up ULs in the content area into multiple columns -----------
  splitColumns();
  splitSitemap();

  // --- configure carousels --------------------------------------------------
  $('.m_Highlight_Teaser_2 ul').cycle({ 
    timeout: 4350, // ms btw transitions (0 to disable auto advance)
    speed: 850, // speed of transition
    prev: '.c_pager_right .prev', 
    next: '.c_pager_right .next',
    pager: '.c_pager_left',
    pause: 1, // true to enable "pause on hover" 
    sync: 1 // true if in/out transitions should occur simultaneously
  });

  $('.m_Highlight_Teaser_1 ul').cycle({ 
    timeout: 4350, // milliseconds btw slide transitions (0 to disable auto advance)
    speed: 850, // speed of transition
    prev: '.c_pager_right .prev', 
    next: '.c_pager_right .next',
    pager: '.c_pager_left',
    pause: 1, // true to enable "pause on hover"
    sync: 1 // true if in/out transitions should occur simultaneously
  });

  $('.m_Stage_Highlight_Teaser ul').cycle({ 
    fx: 'scrollHorz',
    timeout: 9000,  // ms btw transitions (0 to disable auto advance)
    speed: 1150,  // speed of transition
    prev: '.c_pager_right .prev', 
    next: '.c_pager_right .next',
    pager: '.c_pager_left',
    pause: 1 // true to enable "pause on hover"
  });


  // --- configure colorboxes -------------------------------------------------

 
  //initialise colorbox for "relatedButton"
  $(".relatedButton").colorbox({
    speed:0,
    scrolling:false,
    initialWidth:"660px",
    width:"660px",
    initialHeight:"436px",
    innerHeight:"436px",
    iframe:true,
    close:"x Hide Details",
    opacity: 0.5,
    onComplete:function(){ $("body").removeClass("m_Gallery_colorbox").removeClass("m_Layer_colorbox").addClass("m_Related_colorbox"); }
  });

  //initialise generic layer
  $(".m_LayerLink").colorbox({
    speed:0,
    scrolling:false,
    initialWidth:"800px",
    width:"800px",
    initialHeight:"500px",
    innerHeight:"500px",
    iframe:true,
    close:"",
    opacity: 0.5,
    onComplete:function(){ $("body").removeClass("m_Related_colorbox").removeClass("m_Gallery_colorbox").addClass("m_Layer_colorbox"); }
  });

  //initialise image library
  $(".btn_Preview, .img_Preview").colorbox({
    transition:"elastic",
    speed:0,
    close:"X Close",
    opacity: 0.5,
    onComplete:function(){ $("body").removeClass("m_Related_colorbox").removeClass("m_Layer_colorbox").addClass("m_Gallery_colorbox"); 
	$('#colorbox').removeClass('hasTitle');
	if($(this).attr('title') != '' ){
			$('#colorbox').addClass('hasTitle');
		}
	}
  });
  
    //initialise Test
	$('a[rel=example1]').colorbox($.extend({
			transition:"elastic",
			close:"",	
			speed:0,
			inline:true,
			onComplete:function(){ $("body").removeClass("m_Related_colorbox").removeClass("m_Layer_colorbox").addClass("m_Gallery_colorbox"); }
		}, getParameters())
	);
  
  //initialisiere tab navigation ----------------------------------------------
  
  if ( $('#tabNavi').length > 0 ) {
    var offsetActiveLine = $('#tabNavi .active').offset().top;
    var firstLi = $('#tabNavi ul:first li:first').offset().left;
    var elementsToMove = new Array();
    $('#tabNavi li').each(function(index) {
      if ($(this).offset().left == firstLi) {
        $(this).addClass("firstLi");
      }
      if ($(this).offset().top == offsetActiveLine) {
        elementsToMove.push($(this));
      }
    });
    $('#tabNavi').append('<ul id="tabsActive"></ul>')
    for (var i = 0; i < elementsToMove.length; i++) {
      $('#tabsActive').append(elementsToMove[i]);
    }
    $('#tabNavi ul li').css("visibility","visible");
    $('#tabNavi li:first-child').addClass("firstLi");
  }

  // tabs implemented in additions.js now -------------------------------------

});

// ----------------------------------------------------------------------------
// --- WINDOW LOADED ----------------------------------------------------------
// ----------------------------------------------------------------------------

$(window).load(function() {
  
  // makes the page jump back to top when a tab was linked directly from another page
  if ( $('.n_Product_Tabs').length > 0 ) {
    setTimeout(function() {if (location.hash) {window.scrollTo(0, 0);}}, 1);}
  // in case the IE is a bit slow
  if ( $('.ie .n_Product_Tabs').length > 0 ) {
    setTimeout(function() {if (location.hash) {window.scrollTo(0, 0);}}, 200);}

    // --- dropdown_Navigation --------------------------------------------------
    setMainNavigationHeight();
    if ($(".dropdown_Navigation").length > 0) {
      $('.n_Main_Navigation').addClass("has_dropdown");
      $('.n_Main_Navigation ul li').addClass("no_dropdown");
      $('.dropdown_Navigation').parent().removeClass("no_dropdown");
      $('.dropdown_Navigation li').removeClass("no_dropdown");
      $('.n_Main_Navigation>ul').superfish({ 
        disableHI: true,
        speed : 280,
        autoArrows: false,
        delay: 700 // delay on mouseout
      });
    }
});




