// --- 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() {
  $("#drawerOpener").click(function(){
    $("#drawer").animate({ top: '0px' }, 800 );return false;
  });
  $(".openDrawerLink").click(function(){
    $("#drawer").animate({ top: '0px' }, 800 );return false;
  });
  $("#drawerCloseLine").click(function(){
    $("#drawer").animate({ top: '-421px' }, 800 );return false;
  });
  $("#drawerCloseText").click(function(){
    $("#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() {
  $("input[type='text']").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");}
  });
  $(".m_Content_Teaser:nth-child(odd)").addClass("oddElement");

}


// --- 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");}
  );
}


// --- openprintView gets the page URL and opens its printverison -------------
function openprintView() {
  $("#printView").click(function(){
    loc_var=window.location.href;
    loc_var2=loc_var.split('.html');
    printURL = loc_var2[0] + "_p.html"
    printWindow = window.open( printURL,'printView','width=800,height=680,scrollbars=1,toolbar=0,status=0,resizable=1,menubar=1,location=0,directories=0' );
    if (window.focus) {printWindow.focus()}
    return false;
  });
}




// ----------------------------------------------------------------------------
// --- FUNCTIONS FOR SINGLE MODULES -------------------------------------------
// ----------------------------------------------------------------------------




// --- 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();

  $(".contactSelect").change(function(){
    SelectValue = $(".contactSelect").val();
    setHeightContact = $(".contactInformation div#" + SelectValue ).height();
    $(".contactInformation").height(setHeightContact);
    $(".contactInformation div").hide();
    $(".contactInformation div#" + SelectValue ).show();
    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 a").toggle(function(){$(this).addClass("active");}, function () {$(this).removeClass("active");});
  $(".has_Accordion a").click(function(){$(this).next("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;
  });
}


// --- 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");
  });
}


// --- initialize swf files -----------------------------------------------------------

// params for all
var params = {};
params.quality = "high";
params.wmode = "transparent";
params.allowfullscreen = "false";
params.allowscriptaccess = "sameDomain";
// params for map
if ($(".n_Global_Navigation_Map")) {params.bgcolor = "#e5edef";}


// -----------------------------------------------------------------------------
// --- EVENT CALENDAR with the Datepicker (UI) & XML file processing -----------
// -----------------------------------------------------------------------------

function addZeros(value, len) {
var i;
value = "" + value;
if (value.length < len) {for (i=0; i<(len-value.length); i++)value = "0" + value;}
return value;
}

// get the XML data
function readXML() {
  if(typeof xmlPath != "undefined"){
  
    // perdefine empty variables to prevent the javascript from aborting if one is undefined.
    var eventURL = {};  // link to the event detail
    var startDate = 0;  // date div
    var endDate = 0;  // date Div
    var eventHeader = {}; // Headline
    var eventSubheader = {}; // short descr. in the flyover
    var eventSummary = {}; // detailed descr. in fullsize
    var eventLocation = {}; // 'Where:' in fullsize
  
  $.get(xmlPath,{},function(xml){
    $('item',xml).each(function(i) {
      var eventURL = $(this).attr("url");  // link to the event detail
      var startDate = $(this).find("startDate").text();  // date div
      var endDate = $(this).find("endDate").text();  // date Div
      var eventHeader = $(this).find("heading").text(); // Headline
      var eventSubheader = $(this).find("subHeading").text(); // short descr. in the flyover
      var eventSummary = $(this).find("summary").text(); // detailed descr. in fullsize
      var eventLocation = $(this).find("location").text(); // 'Where:' in fullsize
      //var eventType = $(this).find("eventType").text();  --- not needed right now!
      //var eventRegion = $(this).find("eventRegion").text();  --- not needed right now!
      //var eventTime = $(this).find("queryDate").text();  --- not needed right now!

      // format date and get the dates
      var xmlMonth = $.datepicker.formatDate('mm', new Date(startDate));
      var xmlDay = $.datepicker.formatDate('dd', new Date(startDate));
      var xmlYear = $.datepicker.formatDate('yy', new Date(startDate));
      var xmlStartDate = $.datepicker.formatDate('mm.dd.yy', new Date(startDate));
      var xmlEndDay = $.datepicker.formatDate('dd', new Date(endDate));
      var xmlEndDate = $.datepicker.formatDate('mm.dd.yy', new Date(endDate));
      var eventDate = $.datepicker.formatDate('mm_dd_yy', new Date(startDate));

      // compare the end and start date and put them in one variable
      if (startDate == endDate) { var dateTitle = xmlStartDate; }
      else if (endDate == 0) { var dateTitle = xmlStartDate; }
      else { var dateTitle = xmlStartDate + " - " + xmlEndDate; }

      // generating the flyover content
      var output = '<span class="date">'+ dateTitle + '</span>';
      output += '<h4><a href="' + eventURL + '">' + eventHeader + '</a></h4>';
      output += '<p class="eventSubheader">' + eventSubheader + '</p>';
      output += '<p class="forFullsize">' + eventSummary + '</p>';
      output += '<p class="forFullsize"><span>Where:</span> ' + eventLocation + '</p>';
      output += '<a href="" class="closeEvent"></a><img class="event_arrow" src="img/bg/event_hover.gif" alt="" />';
      //output += '<a href="' + eventURL + '" class="m_moreLink"><span class="buttonStart"></span>Visit this page</a>';

      // generating the flyovers for each day
      if ( $(".events div").is(".event_" + eventDate)) {
        $(".event_" + eventDate).append("<span class='hr'></span>");
        $(".event_" + eventDate).append(output);
      }
      else {$(".events").append("<div class='event_" + eventDate + "'>" + output + "</div>");}
      
      if (startDate != endDate) {
        multiDay = xmlEndDay - xmlDay;
        for (var j=1; j<=multiDay; j++) {
          eventDate = xmlMonth + "_" + addZeros((parseInt(xmlDay) + j), 2) + "_" + xmlYear
          if ( $(".events div").is(".event_" + eventDate)) {
            $(".event_" + eventDate).append("<span class='hr'></span>");
            $(".event_" + eventDate).append(output);
          }
          else {$(".events").append("<div class='event_" + eventDate + "'>" + output + "</div>");}
        }
      }
    });

    markEventDays();
  });
  }
};


function markCells(date) {
  CalendarDate = ($.datepicker.formatDate('mm_dd_yy', new Date(date)));
  // CalendarMonth = date.getMonth();
  CalendarYear = date.getFullYear();
  return [true, CalendarDate];
}


function markEventDays() {
  $('.events div').each(function(i) {
    EventDay = $(this).attr("class").substring(6, 16);
    EventDiv = $(this).clone();
    $('#datepicker .ui-datepicker-calendar .' + EventDay).addClass("event_day").children("a").append(EventDiv);
  });

  $('.event_day a').click(function() {
    fullsizeContent = $(this).children("div").html();
    $(".fullsize").append(fullsizeContent).show();
  });

  $('.closeEvent').click(function() {
    $(".fullsize").empty().hide();
    $("#datepicker").datepicker('setDate', 'currDay');
    return false;
  });
}


// Because the the event `onChangeMonthYear` get's called before updating the 
// items, we'll add our code after the elements get rebuilt. We will hook to the 
// `_updateDatepicker` method in the `Datepicker`. Saves the original function.
var _updateDatepicker_o = $.datepicker._updateDatepicker;
// Replaces the function.
$.datepicker._updateDatepicker = function(inst){ 
   // First we call the original function from the appropiate context
   _updateDatepicker_o.apply(this, [inst]); 
   // No we mark the days with events
   markEventDays();
};




// ----------------------------------------------------------------------------
// --- 5th and 6th Level Tab-Navigation ---------------------------------------
// ----------------------------------------------------------------------------

/*
function m_Tabbed_Row() {
  if ($('.n_Tab_Navigation').length) { // implies *not* zero
    widthContainer = $(".n_Tab_Navigation").width();
    var widthTab = 0;
    var rowCounter = 1;
    
    // split the rows
    $('.n_Tab_Navigation').each(function() {
      $(this).find("li").each(function(i) {
        widthTab = widthTab + $(this).width();
        if (widthTab > widthContainer) {
          rowCounter = rowCounter + 1;
          widthTab = $(this).width();
        }
        $(this).addClass("rowLi_" + rowCounter); // named
      });
      for (var i = 2; i <= rowCounter; i++) { // grouped in own rows
        $(this).find(".rowLi_"+i).appendTo(".m_Tabbed_Content").wrapAll("<div class='m_Tabbed_Row topRows row_"+i+"'><ul class='n_Tab_Navigation'></ul></div>").removeClass("rowLi_"+i);
      }
    });

    // format the rows positions
    var rowH = $(".m_Tabbed_Row").height();
    $(".m_Tabbed_Content").css("padding-top", rowH*(rowCounter-1)); // top position for relative positioned rows
    $(".topRows").each(function(i) { 
      $(this).css("top", rowH*i); // top position for absolute positioned rows
      $(".topRows li:first-child").addClass("firstLi");
    });

    // initalise tabs
    $(".m_Tabbed_Row").tabs({
      selected: -1,
      load: function(event, ui) {contentAccordion();},
      ajaxOptions: {error: function(xhr, status, index, anchor) {$(anchor.hash).html("Sorry, we couldn't load this tab. If this error keeps appearing please let us know.");}}
    });
    $(".m_Tabbed_Row.bottomRow").tabs( "option", "selected", 0 );

    // when a tap is clicked --> re-initalise tabs and row position
    $(".m_Tabbed_Row").bind('tabsselect', function(event, ui) {

      // reset rows
      $(".m_Tabbed_Row ul li").removeClass("firstLi");
      $(".m_Tabbed_Row").removeClass("bottomRow topRows");
      $(this).css("top", "0");

      // re-format rows and re-initalise tabs
      $(ui.panel).parent().addClass("bottomRow");
      $(".m_Tabbed_Row:not('.bottomRow')").each(function(i) {
        $(this).css("top", rowH*i).addClass("topRows").tabs( "destroy" )
      });
      $(".topRows").tabs({
        selected: -1,
        load: function(event, ui) {contentAccordion();},
        ajaxOptions: {error: function(xhr, status, index, anchor) {$(anchor.hash).html("Sorry, we couldn't load this tab. If this error keeps appearing please let us know.");}}
      });
      $(".topRows ul li:first-child").addClass("firstLi");
    });

  }
}
*/


// ----------------------------------------------------------------------------
// --- 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();
  
  // --- hoverExtention for browsers with lack of :hover support --------------
  hoverExtention();

  // --- openprintView gets the page URL and opens its printverison -------------
  //openprintView();
  
  // --- bookmark page -------------
  $('.bookmarkButton').jFav();



// JAVASCRIPT FOR SINGLE MODULES

  // --- disclaimer -----------------------------------------------------------

  $("#accept").click(function(){
    //dbPath= "http://www.linde.com/international/web/linde/like35lindecom.nsf"
    //var forwardUrl = dbPath + "/docbyalias/page_nav_bonds"; 
    if ($("#accept:checked")) {
      $(location).attr('href',forwardUrl);
    }
  });

  // --- initialize UI Datepicker ---------------------------------------------
  //readXML();
  $("#datepicker").datepicker({
    showStatus:true,
    firstDay: 1,
    inline: true,
    dateFormat: 'mm_dd_yy',
    beforeShowDay: markCells
  });
  
  // --- 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();

  // --- Splitting up ULs in the content area into multiple columns -----------
  splitColumns();
  splitSitemap();

  // --- tab functionality in C2 ----------------------------------------------
  /* $(".n_Product_Tabs").tabs();
  m_Tabbed_Row(); */

  // --- 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").colorbox({
    transition:"elastic",
    speed:0,
    close:"",
    opacity: 0.5,
    onComplete:function(){ $("body").removeClass("m_Related_colorbox").removeClass("m_Layer_colorbox").addClass("m_Gallery_colorbox"); }
  });

//initialisiere tab navigation
if ( $('#tabNavi').length ) {
  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 .active').css("margin-top","4px");
  $('#tabNavi li:first-child').addClass("firstLi");
  //$("#Content").prepend(firstElement + "px offset-left" );
}



});





