function debug(obj){try{console.log(obj);}catch(e){}}

/**
 * TNT Express
 * Collected scripts
 *
 * @created 20081202
 */
 
var siteroot = "http://www.tnt.com";

var TNT = {

  version: "0.1",

  /**
   * Binds the accordion
   */
  initAccordion: function() {
    
    
  },
  
  
  /**
   * Draws the breadcrumb
   */
  drawBreadCrump: function(listeLinks, listeNamen) {
	listeNamen = listeNamen.replace(/<br \/>/g, ' ');
	listeNamen = listeNamen.replace(/  /g, ' ');
	
    var links = listeLinks.split("||");
    var namen = listeNamen.split("||");
    // als erstes die Startseite
    document.write('<li><a href="'+links[0]+'" title="TNT Deutschland">Home</a></li>');
    
    for (var i = 1; i < links.length-1; i++) {
      var link = links[i];
      if (link === "") {
        document.write('<li>'+namen[i]+'</li>'); 
      } else {
        document.write('<li><a href="'+ link +'#" title="'+namen[i]+'">'+namen[i]+'</a></li>');
      }
    }
    
    // jetzt noch die aktuelle Seite:
    document.write('<li>'+namen[links.length-1]+'</li>');
    
  }
  
};

function toggleIFrame() {
  if(jQuery.browser.msie === true && jQuery.browser.version < 7) {
    if( $('#HPSend select').is(':visible') ) {
      $('#HPSend select').hide();
    } else {
      $('#HPSend select').show();
    }
  }
}

function goURL(url){location.href=url;}

// HoverIntent Plugin
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

// Cookies
function createCookie(name,value,days){
    var expires="";
    if(days) {
        var date=new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires=+date.toGMTString();
    }
    
    document.cookie=name+"="+value+expires+"path=/";
}

function readCookie(name){
  var nameEQ=name+"=";
  var ca=document.cookie.split(';');
  for(var i=0;i<ca.length;i++) {
    var c=ca[i];
    while(c.charAt(0)==' ') {
        c=c.substring(1,c.length);
    }
    
    if(c.indexOf(nameEQ) === 0) {
        return c.substring(nameEQ.length,c.length);
    }
  }
  return null;
}

function eraseCookie(name){
  createCookie(name,"",-1);
}

function normaliseHeight(cssSelector)
{
    var largestSize=0;
    $(cssSelector).css("height","");
    $(cssSelector).each(function() {
        height=$(this).height();
        if(height>largestSize) {
            largestSize=height;
        }
    });
    
    if($(cssSelector).size()) {
        $(cssSelector).height(largestSize+"px");
    }
}

function normaliseHeights()
{
    var hiddenPanels = [];
    var n = 0;
    $(".hpApplicationBox").each(function() {
        var div = $(this);
        var hidden = div.css("display") == "none";
        if (hidden) {
            hiddenPanels[n++] = div;
            div.show();
        }
    });
    
    normaliseHeight(".bodyTop");
    //normaliseHeight(".hpApplicationBox h3");
    normaliseHeight(".App h3");
    normaliseHeight(".lowerFooter");
    normaliseHeight("#HPMyTNT .lowerTop");
    normaliseHeight(".bodyFooter");
    normaliseHeight(".App");
    //normaliseHeight(".tabs");
    if(jQuery.browser.msie === true && jQuery.browser.version < 7) {
        $(".HelpTip").css("position","absolute");
        $(".HelpTip").css("position","relative");
    }
    
    for(var i=0;i<n;i++) {
        hiddenPanels[i++].hide();
    }
}

function switchSize(styleSize){
    try {
        var large=$('#styleSize').attr('name').split('-')[0];
        var small=$('#styleSize').attr('name').split('-')[1];
    } catch (err) {
        var large = 'Text groß';
        var small = 'Text klein';
    }
    
  if(styleSize==large){
    $('body').css('font-size','12pt').find('#styleSize').html(small);
    styleSize=large;
    $('#siteWideNavigation a.hasMenu').css('padding-bottom','9px');
  } else {
    $('body').css('font-size','10pt').find('#styleSize').html(large);
    styleSize=small;
    $('#siteWideNavigation a.hasMenu').css('padding-bottom','11px');
  }
  normaliseHeights();
  createCookie('style',styleSize,365);
}

function checkboxFix() {
  $('div.rememberMe label').css('line-height','100%').hide().show().css('display','inline');
  $('div.rememberMe input').hide().show().css('float','right');
  $('div.rememberMe span').hide();
  $('fieldset label').hide().show();
  $('fieldset label select').css('position','relative');
}

function jsonRenderCountries(jsonURL){$('#countriesScript').attr('src',jsonURL).appendTo('head');}

function toggleSites(){
  var link=$('#siteWideNavigation').find('.change');
  var open=link.attr('name').split('-')[0];
  var close=link.attr('name').split('-')[1];
  if(link.attr('isOpen')!='true'){
    link.attr('isopen','true');
    link.html(close);
    if($('#popup').find('div.countries').size()>0){
      $('#popup div.body').slideDown({duration:400});
    } else {
      var loadedHtml="";
      debug(countriesHtmlUrl());
      try{
        jsonRenderCountries(countriesHtmlUrl());
      }catch(e){
        debug(e);
      }
      $('#popup div.body').slideDown({duration:400});
      $(this).slideDown({duration:400});
    }
    toggleIFrame();
  } else {
    $('#popup div.body').slideUp({duration:400});
    link.attr('isopen','false');
    link.html(open);
    toggleIFrame();
  }
  return false;
}

function setupGerman() {
  $(".promo").filter(function(i){
    return($(this).find("img").attr("src") === undefined);
  }).remove();
  $(".promo > a").filter(function(i) {
    return ($(this).attr("href") === undefined);
  }).click(function(){
    return false;
  });
  var temp="";
  var pos=0;
  var cont=1;
  $("#qm0").children("li").addClass("qmparent");
  $(".quicklink:last").addClass("last");
  $("#pageMenu").children("ul").removeClass("disabled");
  $("#pageMenu").children("ul").children("li").children("a").removeClass("disabled");
  if(posComplete !== ""){
    $("#main"+posComplete.substr(0,2)).addClass("active");
    do {
      pos=posComplete.indexOf("_",pos+1);
      if(pos==-1) {
        cont=0;
    }
      if(cont) {
        temp=posComplete.substring(0,pos);
      }
      else {
        temp=posComplete;
    }
      $("#"+temp).parent("ul").removeClass("disabled");
      $("#"+temp).children("a").removeClass("disabled");
      $("#"+temp).parent("ul").children("li").children("a").removeClass("disabled");
      if($("#"+temp).children("ul").length !== 0) {
        $("#"+temp).children("a").addClass("active");
        $("#"+temp).addClass("open");
        $("#"+temp).children("ul").removeClass("disabled");
        $("#"+temp).children("ul").children("li").children("a").removeClass("disabled");
      } else {
        $("#"+temp).children("a").addClass("selected");
      }
    } while(cont==1);
  }
  $("#pageMenu ul").filter(function(i){
    return $(this).hasClass("disabled");
  }).remove();
  $("#pageMenu ul").filter(function(i){
    if($(this).find("ul").length !== 0) {
        return false;
    }
    if($(this).parent("li").length === 0) {
        return false;
    }
    if($(this).parent("li").nextAll("li").length !== 0) {
        return false;
    }
    
    return true;
  }).addClass("last");
  $("h2:first").addClass("top");
}



// Setup
function setup() {
  $('#otherSites').unbind().hoverIntent({
      sensitivity:1,
      interval:150,
      over: function(){
          $(this).children('ul').find('a').css('height','2.45em');
          $(this).children('ul').slideDown({
              duration:300,
              complete:function(){
                  $(this).find('a').css('height','auto');
              }
          });
      },
      timeout:150,
      out:function(){
          $(this).children('ul').find('a').css('height','2.45em');
          $(this).children('ul').slideUp({
              duration:300,
              complete:function(){
                  $(this).find('a').css('height','auto');
              }
          });
  }});
  $('#otherSites .hasMenu').click(function(){return false;});
  $('#popup div.body').hoverIntent({
      sensitivity:1,
      interval:100,
      over:function(){},
      timeout:100,
      out:function(){
          toggleSites();
          $('#popup div.body').slideUp({duration:300});
      }
  });
  normaliseHeights();
  $('#styleSize').click(function(){
      switchSize($(this).html());
      return false;
  });
  $('#siteWideNavigation').find('.change').click(toggleSites);
  var c=readCookie('style');
  if(c) {
    switchSize(c);
  } else {
    switchSize('Text klein');
  }
  setupGerman();
  
}

function tabsSetup(){

  $.each($('.tabs'), function(){
    var thisObj=$(this);
    thisObj.find('ul').replaceWith(thisObj.find('li:first').html()+thisObj.find('li:last').html());
    thisObj.find('a:first').wrap('<td class="tdLeft tdLeftActive"></td>');
    thisObj.find('a:last').wrap('<td class="tdRight"></td>');
    thisObj.find('td').wrapAll('<table ><tr></tr></table>');
    thisObj.find('a').click(function(){
      if(!$(this).parent().hasClass('tdLeftActive')&&!$(this).parent().hasClass('tdRightActive')) {
        var divGroupHolder=$(this).parent().parent().parent().parent().parent();
        $(divGroupHolder).siblings().toggle();
        divGroupHolder.find('td:eq(0)').toggleClass('tdLeftActive');
        divGroupHolder.find('td:eq(1)').toggleClass('tdRightActive');
        checkboxFix();
      }
    return false;});
  });
  
  $('.hpBody').find('button').mousedown(function(){
    $(this).addClass('active');
  });
  $('.hpBody').find('button').mouseup(function(){
    $(this).removeClass('active');
  });
  $('.hpBody').find('button').mouseout(function(){
    $(this).removeClass('active');
  });
  if(jQuery.browser.mozilla === true){
    $('button').addClass('FireFoxButton');
  }
}














function concat(a,b){
  var result= [].concat(a).concat(b);
  return result;
}

function inPath(currentPath,path){var minlength=Math.min(currentPath.length,path.length);
var subpath=currentPath.length<=path.length;
for(var i=0;i<minlength;i++){if(currentPath[i]!=path[i]){return false;}}
return subpath;}

function pathAreEqual(path1,path2){if(path1.length!=path2.length){return false;}
for(var i=0;i<path1.length;i++){if(path1[i]!=path2[i]){return false;}}
return true;}

function jsonRenderQuickLinks(jsonURL){$('<script/>').attr('src',jsonURL).appendTo('head');}

function renderQuickLinkLi(link){var li=$('<li/>');li.attr('class','quicklink');var href=link.href;if((typeof(siteroot)!="undefined")&&(href.charAt(0)=="/")){href=siteroot+href;}
li.html('<a href="'+href+'">'+link.title+'</a>');return li;}

function doQuickLinks(root){$('#quicklinks_default').empty();var div;try{div=$('<div/>');$('<div class="header"><h4>'+root.title+'</h4></div>').appendTo(div);if(!root.links||root.links.length === 0){return;}
var body=$('<div class="body"/>');var ul=$('<ul/>');body.append(ul);div.append(body);for(var i=0;i<root.links.length;i++){var link=root.links[i];var li=renderQuickLinkLi(link);if(i==root.links.length-1){li.attr('class','quicklink last');}
li.appendTo(ul);}}catch(ex){div=null;}
if(div){$('#quicklinks_default').replaceWith(div);}}

function jsonRenderNavigation(jsonURL,path){
    var pathParameter='[';
    for(var i=0;i<path.length-1;i++){
        pathParameter+="'"+path[i]+"',";
    }
    pathParameter+="'"+path[path.length-1]+"']";
    $('<script/>').attr('src',jsonURL).appendTo('head');
}

function renderPrimaryNavigationLi(node){
  var li=$('<li/>');
  var href=node.href;
  if(typeof(siteroot)!="undefined"){
    href=siteroot+href;
  }
  li.html('<a href="'+href+'" title="'+node.title+'">'+node.render+'</a>');return li;
}

function renderSubNavigationNode(root,currentPath,path,ignoreLevels){
  var ul_last=path.length==4;
  var ignoredLevel=currentPath.length<=ignoreLevels;
  var ul=$('<ul '+(ul_last?'class="last"':"")+'/>');
  for(var i=0;i<root.length;i++){
    var node=root[i];
    var nodePath=concat(currentPath,node.label);
    var elementInPath=inPath(nodePath,path);
    var renderSubNodes=node.children&&elementInPath;
    var li_open=renderSubNodes;
    var a_selected=pathAreEqual(path,nodePath);
    var a_active=!a_selected&&elementInPath;
    var a_class="";
    if(a_selected){
      a_class='class="selected"';
    }else if(a_active){
      a_class='class="active"';
    }
    var li=$('<li '+(li_open?'class="open"':'')+'/>');
    var href=node.href;
    if(typeof(siteroot)!="undefined"){
      href=siteroot+href;
    }
    if(!ignoredLevel){
      li.html('<a href="'+href+'" title="'+node.title+'" '+a_class+'>'+node.render+'</a>');
      li.appendTo(ul);
    }
    if(renderSubNodes){
      var renderedNode=renderSubNavigationNode(node.children,nodePath,path,ignoreLevels);
      if(ignoredLevel){
        ul=renderedNode;
      }else{
        renderedNode.appendTo(li);
      }
    }
  }
  return ul;
}

function doNavigation(data,path){
  ul=$('#qm0');
  ul.empty();
  for(var i=0;i<data.length;i++){
    var node=data[i];
    var li=renderPrimaryNavigationLi(node);
    if(typeof(path)!='undefined'&&path.length>0&&path[0]==node.label){
      li.attr("class","active");	  
    }
	else {
	  li.attr("class","inactive");
	}
    li.appendTo(ul);
    var renderSubNodes=node.children;
    if(!renderSubNodes){continue;}
    var subul=$('<ul/>');
    for(var j=0;j<node.children.length;j++){
      renderPrimaryNavigationLi(node.children[j]).appendTo(subul);
    }
    subul.appendTo(li);
  }
  setupMainNavigation();
  if((typeof(path)!='undefined')&&(data.length>0)){
    var pageMenuDiv=$('<div />');
    pageMenuDiv.attr('id','pageMenu');
    renderSubNavigationNode(data,[],path,-1).appendTo(pageMenuDiv);
    $('#pageMenuWrapper').empty();
    pageMenuDiv.appendTo('#pageMenuWrapper');
  }
}





function jsonRenderOtherSites(jsonURL){$('<script/>').attr('src',jsonURL).appendTo('head');}

function doOtherSites(data){var ul=$('<ul id="inOtherSites"/>');$.each(data,function(i,item){var li=$('<li/>');var a=$('<a/>');a.attr('style','background: url("'+item.image+'") left no-repeat;');a.attr('href',item.href);a.attr('onmouseover','style.backgroundColor="#EEEEEE"');a.attr('onmouseout','style.backgroundColor="#FFFFFF"');a.attr('onclick','return window.open(this.href)');a.attr('title',item.title+' - '+item.summary);var strong=$('<strong/>');strong.text(item.title);strong.appendTo(a);a.append('<br />'+item.summary);a.appendTo(li);li.appendTo(ul);});if(ul){$('#inOtherSites').replaceWith(ul);}}



function doCountries(data){
  target=$('#popup div.body');
  $('#popup div.body div.countries').empty();
  countries=$('<div class=\'countries\'/>');
  $.each(data,function(k,items){
    div='';
    if(k==data.length-1){
      div=$("<div class=\"last\">");
    }else{
      div=$('<div/>');
    }
    for(var i=0;i<items.length;i++){
      var href=items[i].href;
      if(href.indexOf("http")==-1){
        if(typeof(siteroot)!="undefined"){
          href=siteroot+href;
        }
      }
      link=$("<a href=\""+href+"\">"+items[i].render+"</a><br />");
      link.appendTo(div);
    }
    div.appendTo(countries);
  });
  countries.appendTo(target);
}


//Dynamic text using DIV/SPAN
function displayElement(divName,textDesc,dummyRef) {
	//if (document.all) {
	//	tmp = eval('document.all.' + divName);
	//	tmp.innerHTML = textDesc;
	//}
	//else
	
	//IE5+ and NS6+
	if ((document.getElementById) && (document.getElementById(divName)) && (document.getElementById(divName))) {
			document.getElementById(divName).innerHTML = textDesc;
	}
	//NS4.*
	else if ((document.layers) && (document.layers[divName]) && (document.layers[dummyRef])) {
		refDiv = eval('document.layers.' + dummyRef);
		var refDivDoc = refDiv.document;
		tmp = eval('document.layers.' + divName);
		refDiv.left = tmp.pageX;
		refDiv.top = tmp.pageY;
			refDivDoc.open();
			refDivDoc.write(textDesc);
			refDivDoc.close();
		refDiv.visibility = 'visible';
		refDiv.style.color = 'red';
	}
}

function showHelp(helpString) {	
	var helpWindow = window.open("","helpWindow", "width=300,height=50,status=no,resizable=no,scrollbars=no,screenX=100,left=100,screenY=200,top=200");	
	helpWindow.document.open();
	helpWindow.document.write('<html><head><title>TNT</title><link href="/corporate/css/global.css" rel="stylesheet" type="text/css" /></head>');
	helpWindow.document.write('<body bgcolor="#eeeeee" leftmargin="1" topmargin="0" marginheight="0" marginwidth="1" link="#cc4000" vlink="#660000" alink="#999999" text="#000000" onblur="window.close()">');
	helpWindow.document.write('<center><table border="0" width="300" height="100%" cellspacing="5" cellpadding="0" bgcolor="#eeeeee">');
	helpWindow.document.write('<tr valign="top" class="sectionheading">');
	helpWindow.document.write('<td><img src="/corporate/images/im_help.gif" width="40" height="40" alt="?" border="0" /></td>');
	helpWindow.document.write('<td>');
	helpWindow.document.write(helpString);
	helpWindow.document.write('</td></tr></table></center></body></html>');
	helpWindow.document.close();
}

//Rounding number (X) to decimal places (N)
function RoundToNdp(X, N) { 
	var T = Number('1e'+N);
  	return Math.round(X*T)/T;
}


function addMainMenuBehaviour() {
	
	$("#nav_main_insert li").mouseover(function() {
		$("#ul" + this.id + "_01").show();
		$("#ul" + this.id + "_01").css('z-index', 999);
		$("#ul" + this.id + "_01").contents().css('z-index', 999);
	});

	$("#nav_main_insert li").mouseout(function() {
		$("#ul" + this.id + "_01").hide();
	});
}


function replaceContentHeader() {
    var prefix = "/Inter2008/tnt_admin_filecontainer/";
    var rndMin = 1;
    var rndMax = 3;
    
    if ($('#col3_content #content .header').hasClass('noflash')) {
        return;
    }
    
    var keystring = $('#col3_content #content .header .header_image').val();
    var txt = $('#col3_content #content .header .header_title').val();
    
    if (!keystring) {
        return;
    }
    
    var keys = keystring.split(':');
    var flashNo, img;
    
    flashNo = keys[0];
    
    if (keys.length == 2) {
        flashNo = keys[0];
        img = keys[1];
    } else {
        img = keys[0];
        var rand = rndMin + (Math.random() * (rndMax - rndMin));
        flashNo = rand.toFixed(0);
    }
    
    var img1 = prefix + img + "1.jpg";
    var img2 = prefix + img + "2.jpg";
    
    // Get random header flash file

    
    var headerFlash = prefix + "TNT_Header_" + flashNo + ".swf";
    
    var width = 510; // original: 514
    var height = 104; // original: 104
    
    if (flashNo == 4) {
        width = 718;
    }
    
    $('#col3_content #content .header').flash({
        swf: headerFlash,
        height: height,
        width: width,
        allowScriptAccess: 'sameDomain',
        allowFullScreen: false,
        quality: 'high',
        wmode: 'transparent',
        flashvars: {
            _image1: img1,
            _image2: img2,
            _headline: txt
        }
    });
}

function loadMarketingBoxes() {
    $('.marketingboxes input.marketingbox').each(function(index, item) {
        var url = $(item).val();
        if (!url) {
            return;
        }
        
        $.get(url, function(data) {
            $('.marketingboxes').append('<div class="tnt-divider"></div>');
            $('.marketingboxes').append(data);
        });
    });
}

function weiterfuehrendeLinks() {
    var elDivLinks = $('.links_more');
    
    if (!elDivLinks) {
        return;
    }
    
    if ($(elDivLinks).find('a').length > 0) {
        // Add "Weiterführende Links" to top of the div
        $(elDivLinks).prepend('<h3>Weiterführende Links</h3>');
        $(elDivLinks).before('<div class="tnt-divider"></div>');
    }
    
    return true;
}

function foldableDefinitionLists() {
	$('dl.foldable dt').click(function() {
		// Hide everything
		$('dl.foldable dt').removeClass('active');
		$('dl.foldable dd').hide();
		
		// Show this one, please
		$(this).toggleClass('active');
		$(this).next('dd').toggle();
	});
}

function prepareSearchForm() {
	// Setup seach form
    $('#search a').click(function() {
        $(this).parents('form').submit();
    });
  
    $('#search .text').keydown(function(e) {
        if (e.keyCode == 13) {
            $(this).parents('form').submit();
            return false;
        }
    });
    
    var searchWord = 'suchen';
    
    $('#search .text').blur(function(e) {
        if ($(this).val() == '') {
            $(this).val(searchWord);
            $(this).css('color', '#999');
        }
    });
    
    $('#search .text').focus(function(e) {
        if ($(this).val() == searchWord) {
            $(this).css('color', '#000');
            $(this).val('');
        }
    });
    
    $('#search .text').val(searchWord);
    $('#search .text').css('color', '#999');
}



//onload actions
$(document).ready(function() {
  $('a.show_description_long').click(function() {
    $('.description_short').slideUp();
    $('.description_long').slideDown();
    return false;
  });
  
  replaceContentHeader();
  
  loadNavigation();
  addMainMenuBehaviour();
  loadMarketingBoxes();
  
  setup();
  tabsSetup();
  
  trackLinksForETracker();
  
  prepareSearchForm();
  foldableDefinitionLists();
  
    
  // Products Accordion
  $('#products dd').addClass('hide-options');
  $('dt.has-content').click(function() {
    
    saveClass = $(this).hasClass('open'); 
    $('#products dt').removeClass('open');

    if (saveClass) {
      $(this).removeClass('open');
    } else {
      $(this).addClass('open');
    }
    
    $(this).next('dd.hide-options').slideToggle('fast').siblings('dd.hide-options:visible').slideUp('fast');
    
  });
  
  weiterfuehrendeLinks();
});