/**
* IPPEN CODE
* - This javascript is included by client_ext.js, where libraries like prototype are included too!
* - Component initialization is done within the "initPageScripts"-Function at the end of the page
 */

// BEGIN header navigation
// important: always change in basic.js AND basic_ext.js!
var idHeaderNavi = idHeaderNavi ? idHeaderNavi : {
  options: {show_delay:0.5, show_duration:1, hide_delay:2, hide_duration:1},
  subnavis: null,

  init: function(oMainElement) {
    idHeaderNavi.subnavis = new Array();
    if (arguments[1]) {
      if (arguments[1].show_delay) {
        idHeaderNavi.options.show_delay = arguments[1].show_delay;
      }
      if (arguments[1].show_delay) {
        idHeaderNavi.options.hide_delay = arguments[1].hide_delay;
        }
    }

    oMainElement.select('.idMainNavi li.idNavi').each(function(oNavi){
      if (!oNavi.hasClassName('idCurrent')) {
        var oSubNavi = oNavi.select("ul").first();
        idHeaderNavi.subnavis.push(oSubNavi);
        oSubNavi.style.display = "none";
        oSubNavi.isVisible = false;
        oSubNavi.timer_hide = null;
        oSubNavi.timer_show = null;

        oNavi.observe('mouseover', function(e) {
          idHeaderNavi.show(oNavi, oSubNavi);
      });

        oNavi.observe('mouseout', function(e) {
          idHeaderNavi.hide(oNavi, oSubNavi);
      });
      }
    });
  },

  hide: function(navi, subnavi) {
    if (subnavi.timer_show != null) {
      subnavi.timer_show.stop();
      subnavi.timer_show = null;
  }

    navi.removeClassName('idCurrent_hovered');
    subnavi.timer_hide = new PeriodicalExecuter(function(pe) {
      pe.stop();
      subnavi.timer_hide = null;
      subnavi.style.display = "none";
      subnavi.isVisible = false;
    }, idHeaderNavi.options.hide_delay);
  },

  show: function(navi, subnavi) {
    if (subnavi.timer_hide != null) {
      subnavi.timer_hide.stop();
      subnavi.timer_hide = null;
}

    navi.addClassName('idCurrent_hovered');
    subnavi.timer_show = new PeriodicalExecuter(function(pe) {
      pe.stop();
      subnavi.timer_show = null;

      idHeaderNavi.subnavis.each(function(oSubNavi_temp){
        if (oSubNavi_temp.isVisible) {
          oSubNavi_temp.style.display = 'none';
          oSubNavi_temp.isVisible = false;
        }
      });

      subnavi.style.display = 'block';
      subnavi.isVisible = true;
    }, idHeaderNavi.options.show_delay);
  }
}
// END header navigation

/** BEGIN Accordian
 * @param sId
 */
function collapseTimer(sId) {
  acc.collapseTimer(sId);
}
function expandTimer(sId) {
  acc.expandTimer(sId);
}
var acc = acc ? acc : function() {
  var priv = {
    CLASS_OPEN: 'idOpen',
    CLASS_OPEN_GROUP: 'idOpenGroup',
    CLASS_HEADER_GROUP: 'idAccGroup',
    CLASS_HEADER: '.idAcc',
    SUFFIX_HEADER: '-header',
    SUFFIX_CONTENT: '-content',
    DELIM_ID: '-',
    hasAjaxContent: false,
    /**
    * Variable 'iSpeed' defines the speed of the accordian
    * Variable 'iRefresh' defines the refresh rate of the accordian
    */
    iSpeed: 7,
    iRefresh: 10,
    // set or get the current display style of the div
    getsetDivDisplay: function(oElement, iValue) {
	  if(iValue == undefined) {
		return oElement.style.display;
	  } else {
		oElement.style.display = iValue;
	  }
    },
    // set or get the height of a div.
    getsetDivHeight: function(oElement, iValue) {
	  // if you are getting the height then display must be block to return the absolute height
	  if(iValue == undefined) {
		if(priv.getsetDivDisplay(oElement) != 'none' && priv.getsetDivDisplay(oElement) != ''){
			return oElement.offsetHeight;
		}
		var sVisibility = oElement.style.visibility;
		oElement.style.visibility = 'hidden';
		var sDisplay = priv.getsetDivDisplay(oElement);
		priv.getsetDivDisplay(oElement, 'block');
		var iHeight = parseInt(oElement.offsetHeight);
		priv.getsetDivDisplay(oElement, sDisplay);
		oElement.style.visibility = sVisibility;
		return iHeight;
	  } else {
		oElement.style.height = iValue;
	  }
    },
    // Collapse Initializer
    collapseInitializer: function (oContent){
	    if(priv.getsetDivDisplay(oContent) == 'block') {
		clearInterval(oContent.refreshTimer);
        oContent.isCollapsing = true;
		oContent.refreshTimer = setInterval('collapseTimer("' + oContent.id + '")', priv.iRefresh);
  	  }
    },
    //Expand Initializer
    expandInitializer: function(oContent){
      if(priv.getsetDivDisplay(oContent) == 'none' || oContent.isCollapsing) {
        if (priv.hasAjaxContent) {
        // recalculate height, it can be different due to ajax-content-change!
        oContent.heightMax = priv.getsetDivHeight(oContent);
        }
		priv.getsetDivDisplay(oContent, 'block');
		oContent.style.height = '0px';
        oContent.isCollapsing = false;
		clearInterval(oContent.refreshTimer);
		oContent.refreshTimer = setInterval('expandTimer("' + oContent.id + '")', priv.iRefresh);
	  }
        }
  };

  var publ = {
    init: function(oAccordion, hasAjaxContent) {
      try {
        if (hasAjaxContent != undefined) {
          priv.hasAjaxContent = hasAjaxContent;
        }
      //aAccordions.each(function(oAccordion){
        var sActiveId = null;
        var aIds = [];
        var aHeaders = oAccordion.select(priv.CLASS_HEADER);
        aHeaders.each(function(oHeader){
          var sId_temp = oHeader.readAttribute('id');
          aIds.push(sId_temp.substr(0, sId_temp.indexOf(priv.DELIM_ID)));
        });

        aHeaders.each(function(oHeader) {
          var sId = oHeader.readAttribute('id');
          sId = sId.slice(0, sId.indexOf(priv.DELIM_ID));
          var oContent = oAccordion.select('#' + sId + priv.SUFFIX_CONTENT)[0];
          oContent.style.display = 'none';
          oContent.style.overflow = 'hidden';
          oContent.heightMax = priv.getsetDivHeight(oContent);
          oContent.refreshSpeed = (priv.iSpeed == undefined)? 7 : priv.iSpeed;
          oHeader.accordionIds = aIds;
          oHeader.observe("click", function(event) {
            publ.handleClick(sId);
          });
          if(oHeader.hasClassName(priv.CLASS_OPEN)) {
            sActiveId = sId;
          }
        });
        if(sActiveId != null) {
          publ.handleClick(sActiveId);
        }
      //});
      } catch (e) {
        //alert("An exception occurred in the accordion script. Error name: " + e.name + ". Error message: " + e.message);
      }
    },
    // click event handler
    handleClick: function(sId_selection) {
      var oOpenGroupHeader;
      $(sId_selection + priv.SUFFIX_HEADER).accordionIds.each(function(sId){
        var oHeader = $(sId + priv.SUFFIX_HEADER);
        var oHeaderParent = $(oHeader.parentNode);
        var oContent = $(sId + priv.SUFFIX_CONTENT);
        if(sId == sId_selection) {
          priv.expandInitializer(oContent);
          oHeader.addClassName(priv.CLASS_OPEN);
          if (oHeaderParent.hasClassName(priv.CLASS_HEADER_GROUP)) {
            oOpenGroupHeader = oHeaderParent; // dont set it to "open" here, because it could be overwritten in next step..
          }
        } else {
          priv.collapseInitializer(oContent);
          oHeader.removeClassName(priv.CLASS_OPEN);
          if (oHeaderParent.hasClassName(priv.CLASS_HEADER_GROUP)) {
            oHeaderParent.removeClassName(priv.CLASS_OPEN_GROUP);
          }
        }
      });
      if (oOpenGroupHeader) {
        oOpenGroupHeader.addClassName(priv.CLASS_OPEN_GROUP);
      }
    },
    //Collapse Timer is triggered as a setInterval to reduce the height of the div exponentially.
    collapseTimer: function(sElement){
	  var oElement = $(sElement);
	  if(priv.getsetDivHeight(oElement) > 0) {
		var heightTemp = Math.round(priv.getsetDivHeight(oElement) / oElement.refreshSpeed);
		heightTemp = (heightTemp < 1) ? 1 :heightTemp ;
		heightTemp = (priv.getsetDivHeight(oElement) - heightTemp);
		priv.getsetDivHeight(oElement, heightTemp + 'px');
		oElement.style.opacity = (heightTemp/oElement.heightMax);
		oElement.style.filter = 'alpha(opacity=' + (heightTemp * 100 / oElement.heightMax) + ');';
	  } else {
        if (priv.hasAjaxContent) {
        // set height to auto in order to have right height when changing content by ajax!
        priv.getsetDivHeight(oElement, "auto");
        } else {
          priv.getsetDivHeight(oElement, 0);
        }
        priv.getsetDivDisplay(oElement, 'none');
		clearInterval(oElement.refreshTimer);
	  }
    },
    //Expand Timer is triggered as a setInterval to increase the height of the div exponentially.
    expandTimer: function(sElement){
	  var oElement = $(sElement);
	  if(priv.getsetDivHeight(oElement) < oElement.heightMax) {
		var heightTemp = Math.round((oElement.heightMax - priv.getsetDivHeight(oElement)) / oElement.refreshSpeed);
		heightTemp = (heightTemp<1) ? 1 :heightTemp ;
		heightTemp = (priv.getsetDivHeight(oElement) + heightTemp);
		priv.getsetDivHeight(oElement, heightTemp + 'px');
		oElement.style.opacity = (heightTemp / oElement.heightMax);
		oElement.style.filter = 'alpha(opacity=' + (heightTemp * 100 / oElement.heightMax) + ');';
	  } else {
        if (priv.hasAjaxContent) {
        // set height to auto in order to have right height when changing content by ajax!
        priv.getsetDivHeight(oElement, "auto");
        } else {
          priv.getsetDivHeight(oElement, oElement.heightMax);
        }
		clearInterval(oElement.refreshTimer);
	  }
    }
  }
  return publ;
}();
// END accordion

// BEGIN BT (behaviour targeting) Tags
function idWriteBTTags() {
/*
    var aAGOFIds = [51, 82, 92, 390, 401, 106, 117, 121, 124, 127, 128, 134, 136, 137, 138, 147, 150, 152, 155, 156, 159, 163, 166, 167, 169, 178, 184, 192, 194, 201, 208, 216, 218, 225, 226, 241, 242, 243, 257, 258, 260, 264, 266, 284, 286, 288, 294, 295, 349, 385];
    if (aAGOFIds.indexOf("REPLACE ME!") == -1) {
        return;
    }
*/
    if(typeof(adlink_randomnumber) == "undefined"){
        var adlink_randomnumber = Math.floor(Math.random() * 10000000000);
    }

    // WLRCMD Auslesung, muss nach dem BODY eingesetzt werden
    var script_WLRCMD = document.createElement("script");
    script_WLRCMD.language = "Javascript";
    script_WLRCMD.type = "text/javascript";
    document.getElementById('idWLRCMD').appendChild(script_WLRCMD);
//    script_WLRCMD.src = 'http://rc.de.adlink.net/Get/adlink/JS/GetRcmd.js?d=' + adlink_randomnumber;

    // 1x1 Zaehlpixel Tag wird vor dem END BODY Tag gesetzt

    wsite = "oms.merkur-online.de";
    ccat = "387";
    var script_BT = document.createElement("script");
    script_BT.language = "Javascript";
    script_BT.type = "text/javascript";
    document.getElementById('idBTarget').appendChild(script_BT);
//    script_BT.writeAttribute('src', 'http://tr.adlink.net/adlink/JS/track_de.js?d=' + adlink_randomnumber);
}
// END BT (behaviour targeting) Tags

// BEGIN Yahoo Analytics(IndexTools) / IVW Actions Observer Funktionalität
var clickTracking = clickTracking ? clickTracking : {
  _actionMap: [
    // Header:
    {"css_selector":".idMainNavi li.idNavi a.idTab", "action_num":6}, // haupt Navigation
    {"css_selector":".idMainNavi ul li a", "action_num":7}, // sub Navigation
    {"css_selector":".idSubNavi li a", "action_num":7}, // sub Navigation
    {"css_selector":".idSearchBar .idButton", "action_num":10}, // Suche Button
    {"css_selector":".idVideoBar a", "action_num":11}, // Video Button
    {"css_selector":".idFotoBar a", "action_num":12}, // Fotostrecken Button
    {"css_selector":".idMeteo a", "action_num":9}, // Wetter Link
    {"css_selector":"#idAccountButtons .idButton a", "action_num":8, "ajax_submit": true}, // Registrierung / Login
    // Boxen:
    {"css_selector":".idHeimatAusgabe, .idRegionList .idList a", "action_num":13}, // Heimatausgabe Box Links
    {"css_selector":".idSmallMap area", "action_num":14}, // Regionenbox - Map
    // Allgemein
    {"css_selector":"#idBreadcrumbWrap a, .idBreadcrumbWrap a", "action_num":15}, // Breadcrumb
    {"css_selector":".idArticle a.idLinkAsPopup", "action_num":16, "ajax_submit": true}, // Bild Links bei Artikeln
    {"css_selector":".idArticle a.idLinkAsArticle", "action_num":16}, // Bild Links bei Artikeln
    // Start / Ressortseiten
    {"css_selector":".idMetaLay strong a", "action_num":17}, // Ressort Links
    {"css_selector":".idMetaLay .idCommentBar a", "action_num":18}, // Kommentar Links
    {"css_selector":".idMetaLay .idDots a", "action_num":19, "ajax_submit": true}, // Dot Links
    {"css_selector":".idTeaserLay h4 a", "action_num":20}, // Artikel Titel Link
    {"css_selector":".idTeaserLay a.idMore", "action_num":21}, // "Mehr" Link bei Artikel
    {"css_selector":".idTeaserLay .idLeadGal a", "action_num":22, "ajax_submit": true}, // Fotostrecken Link bei Artikel
    {"css_selector":".idTeaserLay h3 a", "action_num":23}, // Überschriften Links
    {"css_selector":"#idFooterWrap a", "action_num":24}, // Footer-Links
    // Artikeldetailseiten
    {"css_selector":".idArticle .idDotArticle a", "action_num":25, "ajax_submit": true}, // Dots
    {"css_selector":".idArticle .idMetaLay strong a", "action_num":26}, // Ressort Link
    {"css_selector":".idArticle .idMetaLay .idCommentBar a", "action_num":27, "ajax_submit": true}, // Kommentarlink
    {"css_selector":".idArticle .idMetaLay .idFacebook a", "action_num":28, "ajax_submit": true}, // Facebook Link
    {"css_selector":".idArticle .idMetaLay .idPrint a", "action_num":29, "ajax_submit": true}, // Artikel drucken
    {"css_selector":".idArticle .idMetaLay .idDialog_idRecContent a", "action_num":30, "ajax_submit": true}, // Artikel empfehlen
    {"css_selector":".idArticle .idMetaLay a.idStyle", "action_num":31, "ajax_submit": true}, // Schrift vergrößern / verkleinern
    {"css_selector":".idArticle a.id_link[target], .idArticle a.idActionLink[target]", "action_num":33, "ajax_submit": true}, // externe Links in Artikeln
    {"css_selector":".idArticle a.id_link", "action_num":32}, // interne Links in Artikeln
    {"css_selector":".idArticle p.idMoreEnd a", "action_num":34}, // zurück zur Übersicht Links
    {"css_selector":".idArticleKeywords a", "action_num":35}, // Schlagwortlinks
    {"css_selector":".idSocialBM a", "action_num":36, "ajax_submit": true}, // Social Bookmarks
    // Fotostrecken
    {"css_selector":".idImageGallery .idDotArticle a", "action_num":25, "ajax_submit": true}, // Dots
    {"css_selector":".idImageGallery .idMetaLay strong a", "action_num":26}, // Ressort Link
    {"css_selector":".idImageGallery .idMetaLay .idCommentBar a", "action_num":27, "ajax_submit": true}, // Kommentarlink
    {"css_selector":".idImageGallery .idMetaLay .idFacebook a", "action_num":28, "ajax_submit": true}, // Facebook Link
    {"css_selector":".idImageGallery .idBacklink a", "action_num":34}, // zurück Link
    {"css_selector":".idImageGallery .idMetaLay .idDialog_idRecContent a", "action_num":30, "ajax_submit": true}, // Fotostrecke empfehlen
    {"css_selector":".idImageGallery .idNext_button, .idMediaStripe .idNext_button", "action_num":42, "ajax_submit": true}, // vor Button
    {"css_selector":".idImageGallery .idPrevious_button, .idMediaStripe .idPrevious_button", "action_num":43, "ajax_submit": true}, // zurück Button
    {"css_selector":".idImageGallery .idCarouselPlayback a", "action_num":44, "ajax_submit": true}, // automatisch abspielen
    {"css_selector":".idImageGallery a.idImgLink", "action_num":45, "ajax_submit": true}, // Bild Klick
    {"css_selector":".idFullWrap .idCarousel a.idImgLink", "action_num":46, "ajax_submit": true}, // Klick Thumbnails
    // Community
    {"css_selector":".reportlink .idTrackerMelden", "action_num":39, "ajax_submit": true}, // Community Kommentar melden
    {"css_selector":".entry-content .idTrackerAntworten", "action_num":40, "ajax_submit": true}, // Community Kommentar antworten
    {"css_selector":".idTrackerPosten", "action_num":05, "ajax_submit": true}, // Community Kommentar veröffentlichen
    {"css_selector":".comment-like-container .idTrackerBewerten .comment-like-button, .comment-like-container .idTrackerBewerten .comment-dislike-button", "action_num":38, "ajax_submit": true}, // Community Like/Dislike Bewertung
    {"css_selector":"#comment-form .ajaxContainer .idTrackerNeuesWort", "action_num":41, "ajax_submit": true}, // Community Captcha unleserlich
    {"css_selector":"#comment-form .idTrackerRegistrieren", "action_num":37} // Community Bereits Registriert Link
  ],
  _eClicked: null,
  init: function() {
    var onBeforeUnload = function(e) {
      if (clickTracking._eClicked && clickTracking._eClicked._actionNum) {
        clickTracking.submitAction(clickTracking._eClicked._actionNum);
      }
    };

    if (typeof jQuery != 'undefined') {
      jQuery(window).bind('beforeunload', onBeforeUnload);

      this._actionMap.each(function() {
        var oActionMapItem = this;
        jQuery(this["css_selector"]).each(function () {
          var $el = jQuery(this);
          $el[0]._actionNum = oActionMapItem["action_num"];
          $el.bind('click', function(e) {
            if (oActionMapItem["ajax_submit"]) {
              clickTracking.submitPageView($el[0]._actionNum);
              if ($el.hasClass('idIVW_Count')) {
                clickTracking.submitIVW();
              }
            } else {
              clickTracking._eClicked = $el[0];
            }
          });
        });
      });

    } else {
    this._actionMap.each(function(oActionMapItem) {
      var aElements = $$(oActionMapItem["css_selector"]);
      aElements.each(function(oElement) {
        oElement._actionNum = oActionMapItem["action_num"];
        oElement.observe('click', function(e) {
            if (oActionMapItem["ajax_submit"]) {
            clickTracking.submitPageView(oElement._actionNum);
            if (oElement.hasClassName('idIVW_Count')) {
              clickTracking.submitIVW();
            }
          } else {
            clickTracking._eClicked = oElement;
          }
        });
      });
    });

      Event.observe(window, 'beforeunload', onBeforeUnload);
    };
  },
  submitAction: function(iAction) {
    // Web Analytics, NUR Action zaehlen
    YWATracker.setAction(iAction);
    YWATracker.submit_action();
  },
  submitPageView: function(iAction) {
    // Web Analytics, Page View UND Action
    YWATracker.setAction(iAction);
    YWATracker.submit();
  },
  submitIVW: function() {
    // IVW
    var urlIVW = IVW,
        imgIVW = new Element("img", {height:"1", width:"1", alt:"szmtag"});

    imgIVW.setAttribute('src', (urlIVW + '?r=' + escape(document.referrer) + '&d=' + (Math.random()*100000)));
    document.body.appendChild(imgIVW);
  }
}

function scrollSkyscraper (pos, $el) {
  try {
    if ((document.all || document.getElementById)) {
      var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body,
          dsoctop = document.all ? iebody.scrollTop : pageYOffset,
          iOffset = dsoctop,
          iHeight = (typeof jQuery != 'undefined') ? $el.height(): $el.getHeight();

      switch (pos) {
        case 1:
          if (typeof(startposSticky2)=='undefined') {
            iOffset = dsoctop;
          } else {
            if (dsoctop + iHeight < startposSticky2) {
              iOffset = dsoctop;
            } else {
              iOffset = startposSticky2 - iHeight;
            }
          }
          break;
        case 2:
          if (typeof(startposSticky2)=='undefined') {
            if (dsoctop > startposSticky2) {
              iOffset = dsoctop;
            } else {
              iOffset = startposSticky2;
            }
          }
          break;
      }

      if (typeof jQuery != 'undefined') {
        $el.css('top', (iOffset + "px"));
      } else {
      $el.setStyle({'top': iOffset + "px"});
    }
    }
  } catch (e) {}
}

window.onload = function () {
  if (typeof jQuery != 'undefined') {
    jQuery('#idBarWrap, .idSkyScraperWrap').each(function() {
      var $el = jQuery(this);
      if (jQuery('.idScollWithPage, .stickySky', $el).length > 0) {
        jQuery(window).bind('scroll', function () {
          scrollSkyscraper(1, $el);
        });
      }
    });

    // Sky2 Mist
    jQuery('.idSkyScraperWrap2').each(function(){
      var $el = jQuery(this),
          startpos = (typeof(startposSticky2) == 'undefined') ? '800' : startposSticky2;
      $el.css('top', (startpos + "px"));
      if (jQuery('.idSky2', $el).length > 0) {
        jQuery(window).bind('scroll', function () {
          scrollSkyscraper(2, $el);
        });
      }
    });

    if (typeof clickTracking != "undefined") {
      clickTracking.init();
    }

  } else if (typeof Prototype != 'undefined') {
    $$('#idBarWrap, .idSkyScraperWrap').each(function($el) {
      if ($el.select('.idScollWithPage, .stickySky').length > 0) {
  //      window.onscroll = function () {scrollSkyscraper(1, $el);};
        Event.observe( window, 'scroll', function () {scrollSkyscraper(1, $el);});
      }
    });
    // Sky2 Mist
    $$('.idSkyScraperWrap2').each(function($el){
      var startpos = (typeof(startposSticky2)=='undefined') ? '800' : startposSticky2;
      $el.setStyle({'top': startpos + "px"});
      if ($el.select('.idSky2').length > 0) {
        Event.observe( window, 'scroll', function () {scrollSkyscraper(2, $el);});
      }
    });

    if (typeof clickTracking != "undefined") {
      clickTracking.init();
    }
  }
}
