/**
 * We need the http-host to allow requests from the same host where this file
 * is situated. For instance the json-p ajax call of the sitemap or all plugins
 * loaded by the lazyloader.
 */
var HTTP_HOST = '';
jQuery('script[src]').filter(function() {
    return (this.src.search(/(https?:\/\/[^\/]+)\/.*main\.js$/) > -1);
}).each(function() {
    HTTP_HOST = RegExp.$1;
});

jQuery(document).ajaxError(function (event, XMLHttpRequest, ajaxOptions, thrownError) {
    if (XMLHttpRequest.status == 409) {
        location.reload();
    }
});

jQuery(document).ready(function ($) {

  // WiredMinds - Teaser Tracking - Views for the clip, shopclip and adbar element
  $("div.clip-element, div.shopclip-element, div.adbar-element").each(function() {
      trackTeaser($(this), 0);
  });

  // WiredMinds - Teaser Tracking - Clicks for adbars, intros and clips
  $("div.adbar-element a, ul.intro-elements-container a, div.clip-element a, div.shopclip-element a").bind('click', function () {
      trackTeaser($(this), 1);
  });

  // Track ContentBox button links
  $("div.contentbox div.track-links a", "#main").bind('click', function () {
      trackTeaser($(this), 1);
  });


  // WiredMinds - Global Tracking Function 
  
  //Click Tracking 
  $(".wm-tracking-click", "#main").bind('click', function () {
      trackTeaser($(this), 1, generateTrackPath($(this)));
  });
  
  // View Tracking
  $(".wm-tracking-view", "#main").each(function() {
      trackTeaser($(this), 0,  generateTrackPath($(this)));
  });

  function generateTrackPath(obj) {
    var curPath   =  window.location.pathname;
    var defPath   = 'htdocs';
    defPath      +=  curPath.substring(0, curPath.lastIndexOf("/") + 1);
    defPath      += 'link_' + obj.attr('title').replace(/\s+/g,'_');
    return defPath;
  }
  
  var _msie6 = $.browser.msie && $.browser.version < 7;
  var _msie7 = $.browser.msie && $.browser.version >= 7;
  var _msie = _msie6 || _msie7;
  
  if (_msie6) try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}
  
  /* Styles the ol numbers */
  if (_msie)
  {

    $('ol.numbers li').each(function(i, e) {
        $(e).contents().wrap('<span class="text"></span>');
        $(e).find('.text').before('<div class="point">'+(i + 1)+'</div>');
    });  

    
    $('ol.custom li').each(function(i, e) {
        var curContent  = (i+1);
        
        if ($(e).attr('lang').length > 0) curContent = $(e).attr('lang');
        $(e).contents().wrap('<span class="text"></span>');
        $(e).find('.text').before('<div class="point">'+curContent+'</div>');
    }); 
  }
  
  /**
   * profiles for different popups
   */
  var popups = {
    profile1 : {
      height:400,
      width:600,
      toolbar:0,
      scrollbars:1,
      center:1
    },
    profile2 : {
      height:480,
      width:640,
      toolbar:1,
      scrollbars:1,
      status:1,
      left:100,
      top:100
    },
    profile3 : {
      height:600,
      width:800,
      scrollbars:1,
      center:1
    }
  };

  $('a.disabled').click(function () {
      return false;
  });

  /**
   * prepare plugins for lazy loading
   */
  if ($.lazy) {
    $.lazy(HTTP_HOST + '/inc_common/scripts/js/jquery.popupwindow.min.js','popupwindow');
    $.lazy(HTTP_HOST + '/inc_common/scripts/js/jquery.easytooltip.js','easytooltip');
    $.lazy(HTTP_HOST + '/inc_common/scripts/js/tariff.js','tariffoptions');
    $.lazy(HTTP_HOST + '/inc_common/scripts/js/getSubscribers.js','getsubscribers');
    // use the lazy loader only if no plugin included
    if (!$().contentTabs) {
      $.lazy(HTTP_HOST + '/inc_common/scripts/js/plugins.js','contentTabs');
    }
    if (!$().jCarouselLite) {
      $.lazy(HTTP_HOST + '/inc_common/scripts/js/jcarousellite.js', 'jCarouselLite');
    }
    if (!$().flowplayer) {
      $.lazy(HTTP_HOST + '/inc_common/scripts/js/landingpages/flowplayer-3.2.4.min.js');
    }
    /*
    $.lazy(HTTP_HOST + '/inc_common/scripts/js/jquery.swfobject.min.js', 'swfobject');
    $.lazy(HTTP_HOST + '/inc_common/scripts/js/jquery.tablesorter.min.js', 'tablesorter');
    */
  }


  /* Tariflist */
  $('a.tariff_more').click(function() {
    var next      = $(this).parents('table:first').find("tr.hideTariff").show();
    var btnSwitch = $(this).parents('tr').hide();
    if (!_msie6) btnSwitch.next().show();     
  });
  
  $('a.tariff_less').click(function() {
    var next = $(this).parents('table:first').find("tr.hideTariff").hide();
               $(this).parents('tr').hide().prev().show();
  });
  
  /**
   * init content tabs
   */
  if ($('.content-tabs').length) {
    $('.content-tabs').contentTabs();
  }

  Pathnavigation = function(){

    var active = -1;
    var activating = -1;
    var navigation = $('#path .navigation:not(.sub)');
    var elemSelector = '#path .navigation:not(.sub) > li';
    var elements = $(elemSelector);
    var subNavigation = $('#path .navigation.sub');
    var subElemSelector = '#path .navigation.sub > li';
    var subElements = null;
    var handles = elements.filter('.dropdown');

    init();

    function init() {
      widthControl();
      dropDownCheck();

      if (0 < subNavigation.length) {
        subElements = $(subElemSelector);
        subWidthControl();
        handles = $(elemSelector + ',' + subElemSelector).filter('.dropdown');
      }

      if (_msie6) {
        handles.each(function(index) {
          var handle = $(this);
          if (0 < $('li', handle).length) {
            handle.hover(function() {
              $(this).addClass('hover');
            }, function(ev) {
              $(this).removeClass('hover');
            });
          }
        });
      }
    }

    function dropDownCheck() {
      handles.each(function() {
        if (0 == $('li', this).length) {
          // dropdown list can be empty accordingly to visibility settings for the user
          $(this).removeClass('dropdown');
          $('span.arrow', this).remove();
        }
      });
      elements.filter(':last').addClass('current');
    }

    function widthControl() {
      var i = 0, w = 0, x = 0, el;
      var j = navigation.width();
      if ($('#path .search').length > 0) {
        j -= $('#path .search').width();
      }
      var k = elements;
      var arrow = $(elemSelector + ' > a span.arrow:first');
      var widths = new Array();
      k.each(function(index) {
        el = $(this);
        w = el.width();
        widths[index] = w;
        w += (parseInt(el.css('border-left-width')) + parseInt(el.css('border-right-width')));
        i += w;
      });
      for (x; x < elements.length; x++) {
        if (i < j) {
          break;
        } else {
          el = $(k).get(x + 1);
          $(el).children('a').html('...&nbsp;').append(arrow.clone());
          i += $(el).width();
          i -= widths[x];
        }
      }
    }

    function subWidthControl() {
      var w = 0, allWidth = 0, showWidth = 0, el;
      var c = $('<div class="con"><ul></ul></div>');
      var i = subNavigation.width();

      if (_msie6) {
        $('li:first', subNavigation).css({
          borderWidth : '0'
        });
      }

      subElements.each(function(index) {
        el = $(this);
        w = el.width();
        w += (parseInt(el.css('border-left-width')) + parseInt(el.css('border-right-width')));
        w += (parseInt(el.css('padding-left')) + parseInt(el.css('padding-right')));
        allWidth += w;
        if (allWidth > i) {
          $('ul', c).append(el);
          if (0 == showWidth) {
            showWidth = allWidth - w;
          }
        }
      });
      if (allWidth > i) {
        if (showWidth + 100 > i) {
          // we need a little space between last item and more button
          $('ul', c).prepend($(subElemSelector).filter(':last'));
        }
        subNavigation.append('<li class="dropdown"><a href="#">mehr...&nbsp;</a></li>');
        $('.dropdown a', subNavigation).append($(elemSelector + ' > a span.arrow:first').clone());
        $('.dropdown', subNavigation).append(c);
        $('.dropdown .con', subNavigation).prepend($('.shadow:first').clone());
      }
    }

  };
  $('a[href="#hfoDiv"]').parent().addClass('hfoLIDiv');
  $('.hfoLIDiv').hover(
    function () {
      $(this).find('.con').show();
    },
  	function () {
      $(this).find('.con').hide();
  	}
  );
  
  /**
   * class Sitemap bind an click event on the sitemap icon, initialize the
   * sitemap and provide tabbing functionality
   */
  Sitemap = function() {
    
    var link = $('#sitemap, a[href*="sitemap"]');
    var context = $('#sitemap');
    var con = '#sitemapContainer';
    var tab = '.tab';
    var list = '.con';
    var closeBut = '#sitemapContainer img.closeBut';

    if (0 < link.length) init();

    /**
     * initialize the sitemap object
     */
    function init(){
      initTabs();
      initHFOLayer();

      link.click(function(){
        if (!window.location.pathname.match(/^\/offen.+/i)) { // offener Bereich im HFO ohne Sitemap
          if (!link.hasClass('active')) {
            link.addClass('active');
            if (0 == $(con).length) {
              context.after('<div id="sitemapContainer"><div style="height:300px;" class="loading"></div></div>');
              loadSitemapJSON();
            }
            lightbox(true, $(con));
          } else {
            lightbox(false);
          }
        }
        return false;
      });

      initCloseBut();
    }
    
    function loadSitemapJSON() {
      url = HTTP_HOST + '/ajax/';
      if (window.location.pathname.match(/^\/business/i))
        url += 'business/';
      url += 'sitemap.php' + '?jsonp=?';
      $.getJSON(url, function(data) {
        
        $(con).fadeOut(function() {
        
          $(this).html('<div class="con active"><div class="layer">' + data.headline 
            + data.closebut + '</div></div>');
          
          $(this).prepend($('.shadow:first').clone());
          
          var groups = '<div class="group">', placement = 1, i, item;
          
          for (i = 0; i < data.groups.length; i++) {
            item = data.groups[i];
            /**
             * if there is no headline, the group isn't visible for the user,
             * so hide this block
             */
            if (item.headline) {
              if (Number(item.placement) != placement) {
                groups += '</div><div class="group">';
                placement = Number(item.placement);
              }
              groups += item.headline;
              if (item.items) {
                groups += '<ul><li>' + item.items.join('</li><li>') + '</li></ul>';
              }
            }
            
          };
          groups += '</div>';
          
          if (data.shopGroup) {
            groups += '<div class="group shop-group">'
              + data.shopGroup.headline
              + '<ul><li>' + data.shopGroup.items.join('</li><li>') + '</li></ul>'
              + '</div>';
          }
          $('.layer', con).append(groups);

          $(this).fadeIn('fast');
          initCloseBut();
          initHFOLayer();
        });
    });
    }
    
    function initHFOLayer() {
      if ($('a[href=#hfo]')) {
        $('a[href="#hfo"]').parent().addClass('hfoH3Div');
        $('.hfoH3Div').hover(function() {
          $(this).find(".con").show();
        }, function() {
          $(this).find('.con').hide();
        });
      }
    }
    
    function initCloseBut() {
      if (0 < $(closeBut).length) {
        $(closeBut).click(function() {
          lightbox(false);
          return false;
        });
      }
    }

    /**
     * initialize a simple tabbing behavior
     */
    function initTabs(){
      var tabs = $(tab, con);
      var cons = $(list, con);

      tabs.each(function(i){
        $(this).click(function(){
          if ($(this).not('.active')) {
            $(tabs).removeClass('active');
            $(cons).removeClass('active');
            $(this).addClass('active');
            var el = $(cons).get(i);
            $(el).addClass('active');
          }
        });
      });
    }

    /**
     * show or hide the lightbox and fade the tabs and layers in and out
     *
     * @param {Boolean} show - show or hide the lightbox
     * @param {String} elem -css-selector of the dom-element which controls the sitemap
     */
    function lightbox(show, elem){
      if (show) {
        var el = $('<div id="lightbox"></div>');
        var cont = $('#content');
        var contLeft = parseInt(cont.css('padding-left'));
        var contTop = parseInt(cont.css('padding-top'));
        var bw = 2; // 2 * border-width of the container
        var h = (parseInt(cont.height()) + contTop + parseInt(cont.css('padding-bottom')) + bw) + 'px';
        var w = (parseInt(cont.width()) + 2 * contLeft + bw) + 'px';
        el.css({
          height: h,
          width: w,
          left: '-' + (contLeft + bw /2) + 'px',
          top: '-' + (contTop + bw / 2) + 'px'
        }).click(function(){
          lightbox(false);
        });
        var lPath = parseInt($('#path').css('margin-left'));
        if (0 > lPath) {
          var tmp = parseInt(cont.css('padding-left'));
          tmp += lPath;
          tmp += bw / 2;
          lPath = -tmp;
          el.css({
            left: lPath + 'px'
          });
        }
        if (_msie6) {
          $('#content select, #path div.search').css({
            visibility: 'hidden'
          });
        }
        $('body').append(el);
        if (elem) {
          $(elem).before(el);
        }
        $(elem).fadeIn('fast');
      } else {
        $(con).fadeOut('fast', function(){
          link.removeClass('active');
          $('#lightbox').remove();
          if (_msie6) {
            $('#content select, #path div.search').css({
              visibility: 'visible'
            });
          }
        });
      }
    }

  }
  /**
   * class Tarifftables initialize the behavior for all tarifftables
   */
  Tarifftables = function () {
    var tableType1 = $('table.tariff');
    var tableType2 = $('table.overview');

    var radios = null;
    var checkboxes = null;

    if (0 < tableType1.length)
      radios = $('input[type=radio]', tableType1);
    if (0 < tableType2.length)
      checkboxes = $('input[type=checkbox]', tableType2);

    init();

    function init() {
      tableChecks();
      tableOptions();

      if (0 < tableType1.length)
        $('.infohover', tableType1).hoverInfo({ elem : 'ol' });
      if (0 < tableType2.length)
        $('.infohover', tableType2).hoverInfo({ elem : '.con' });

    }

    function tableChecks() {
      if (null != radios) {
        radios.each(function() {
          $(this).click(function() {
            if ($(this).is(':checked')) {
              $('tr.active', tableType1).removeClass('active');
              $(this).parents('tr:first').addClass('active');
            }
          });
        });
      }

      if (null != checkboxes) {
        checkboxes.each(function(){
          $(this).click(function(){
            if ($(this).is(':checked')) {
              $(this).parents('tr:first').addClass('active');
            } else {
              $(this).parents('tr:first').removeClass('active');
            }
          });
        });
      }
    }

    /**
     * binding events to tariff tables to load tariff options by ajax calls
     */
    function tableOptions() {
      if (0 < $('#tarifwechsel-tariffchange-tariff-dynamisch-0-tariffchange-tariff').length) {
        $('#tarifwechsel-tariffchange-tariff-dynamisch-0-tariffchange-tariff table').filter('.tariffTable').tariffoptions({
          type : 'kuse'
        });
      } else if (0 < $('#retentionTariff').length) {
        $('table').filter('.tariffTable').tariffoptions();
      }
    }
  }

  /**
   * global object initializes and controls the stage
   */
  Stage = function () {
    var navigation = new Pathnavigation();
    var sitemap = new Sitemap();
    var tarifftables = new Tarifftables();

    $('#head input[type=text], #suche-search-complete-0 input[type=text], #path input[type=text]').defaultvalue();

    $('table.serviceCategories .infohover').hoverInfo({ elem : '.con' });
    $('div.detailshover').hover(
	    function () {
	        $(this).find('.con').show();
	      },
	    	function () {
	        $(this).find('.con').hide();
	    	}
	    );

    $('li.dropdown img.bullet, .oie .row a img').pngNavFix();

     // pngfix images with class pngfix
     if ($().pngfix) {
       $('img').filter('.pngfix').pngfix();
       $('.bigBonus > img, .mediumBonus > img, .smallBonus > img, .abstracts .medium img, .shopclip-element .teaser-bg img, .intro-paging .identifier').pngfix();
     }

    // only if there a popup behavior the lazy loader need to load the plugin
    if (0 < $('.popup, .popup1, .popup2, .popup3').length) {
      // see popup-profiles above
      $('.popup').popupwindow(); // use default values or custom parameters in rel-attribute
      $('.popup1, .popup2, .popup3').each(function() {
        var p = popups.profile1;
        if ($(this).hasClass('popup2')) p = popups.profile2;
        else if ($(this).hasClass('popup3')) p = popups.profile3;
        $(this).popupwindow(p); // use accordingly profile
      });
    }

    // Links zum Bestellen von Zusatzoptionen müssen umgeschrieben werden
    if (0 < $('a[rel=Zusatzoption]').length) {
      $('a[rel=Zusatzoption]').each(function(i) {
        this.href += '&option=' + encodeURI(this.title);
        $(this).removeAttr('title');
      });
    }

  }
  /**
   * plugin definitions with global use
   * TODO: move to lib_1st_party
   */
  /* preallocate textfields and textarea */
  $.fn.extend ({
    defaultvalue: function(){
      var element = $(this);
      element.each(function(){
        var el = $(this);
        var def = el.attr('title');
        var defcheck = new RegExp('^\\s*'+def+'\\s*$');
        el.focus(function(){
          if (el.val().match(defcheck)) {
            el.val("");
          }
          el.blur(function(){
            if ("" == el.val() || el.val().match(defcheck)) {
              el.val(def);
            }
          });
        });
      })
    }
  });

  /* provide png transparency and associating css-sprites */
  $.fn.pngNavFix = function(options){

    var o = $.extend({
      sizingMethod : false,
      sprites: false
    }, options);

    if (o.sprites) {
      var e = $(o.sprites, this);
    } else {
      var e = $(this);
    }

    if (!$.browser.msie || ($.browser.msie && $.browser.version >= 7)) {
      return (e);
    }

    if ('a#sitemap' == o.sprites) {
      $('a#sitemap').hover(function(){
        var src = $(this).data('bgImage').replace(/_hv\.([a-z]{3,4})$/, ".$1");
        if ($(this).hasClass('active')) {
          src = $(this).data('bgImage').replace(/_act\.([a-z]{3,4})$/, ".$1");
        }
        src = src.replace(/\.([a-z]{3,4})$/, "_hv.$1");
        setFilter($('b', this), src, "scale");
      }, function(){
        var src = $(this).data('bgImage');
        if ($(this).hasClass('active')) {
          src = src.replace(/\.([a-z]{3,4})$/, "_act.$1");
        }
        setFilter($('b', this), src, "scale");
      });
    }

    function setFilter(el, path, mode){
      var fs = el.attr("filters");
      var alpha = "DXImageTransform.Microsoft.AlphaImageLoader";
      if (fs[alpha]) {
        fs[alpha].enabled = true;
        fs[alpha].src = path;
        fs[alpha].sizingMethod = mode;
      } else {
        el.css("filter", 'progid:' + alpha + '(enabled="true", sizingMethod="' + mode + '", src="' + path + '")');
      }
    }

    return (e.each(function(i) {
      var el = $(this);
      var image = 'img' == this.nodeName.toLowerCase();

      if (!image) {
        var bg = new String(el.css("backgroundImage"));
        var matches = bg.match(/^url\("(.*)"\)$/);
      }

      if ((image && (/\.png/i).test(el.attr("src"))) || (matches && matches.length)) {
        el.css({
          backgroundImage: 'none',
          textIndent: '0'
        });
        if (image) {
          var img = el;
        } else {
          var img = $(new Image());
          img.attr('src', matches[1]);
          el.data('bgImage', matches[1]);
          el.prepend(img);
        }
        img.wrap('<b></b>');

        var con = $('<div></div>');
        con.css({
          position: 'absolute',
          top: '-5000px'
        }).append($(img).clone());
        $('body').append(con);
        var x = {
          h: $('img', con).height(),
          w: $('img', con).width()
        }

        var par = img.parent();
        par.attr('class', img.attr('class'));
        par.addClass('pngfix');
        par.css({
          height: x.h,
          width: x.w,
          display: 'inline-block'
        });
        if(!image)
          o.sizingMethod = false;
        setFilter(par, img.attr('src'), o.sizingMethod);
        con.remove();
        img.remove();

        if (o.sprites) {
          el.addClass('fixed');
        }
      }
    }));
  };

  $.fn.hoverInfo = function(options){

    var e = this;

    var o = $.extend({
      shadow : true,
      shadowPos : 'before',
      elem : 'ul'
    }, options);

    $(e).each(function() {
      var handle = $(this);
      var elem = $(o.elem, this);

      handle.hover(function(){
        if (o.shadow && !$(this).data('shaded')) {
          if (!_msie6) {
            elem = initShadow(elem, this);
          }
          $(this).data('shaded', 'true');
        }
        elem.show();
      }, function(){
        elem.hide();
      });
    });

    function initShadow(el, self) {
      var take = $('.shadow:first').clone();
      var elem = $('<div class="con"></div>');
      $(elem).append(take);
      $(el).removeClass('con').addClass('layer').before(elem);
      $(elem).append(el);
      return elem;
    }
  }

  /**
   * init stage
   */
  stage = new Stage();

  /**
   * specific function and behaviors for internet explorer
   */
  if (_msie) {
    $('ul.mainTabs li, table.tariff tr, table.enableHover tr').each(function(index){
      var handle = $(this);
      handle.hover(function(){
        $(this).addClass('hover');
      }, function(ev){
        $(this).removeClass('hover');
      });
    });
  }

  $.fn.blinkIt = function(time) {
      if ($(this).hasClass('blink')) {
          var self = this;
          setTimeout(function() {
              $(self).fadeOut('slow', function() { $(self).fadeIn('slow').blinkIt(); });
          }, 2000);
      }
  };

  /**
   * quickaccess im page-header
   */
  initQuickAccessList('#head', false);

  $('.blink').blinkIt();

  $('form .buttons button[type=submit]').click(function () {
      var action = $(this).attr('id').replace(/^.*-([^-]+)$/, "$1");
      var form = $(this).parents('form');
      $('input[name=action]').val(action);
   });


  $('a.tableDisplay').click(function() {
    $('.tariffTableDisplay').toggle();
    var newText = $('span.hidden', this).text();
    var oldText = $('span', this).not('.hidden').text();
    $('span.hidden', this).text(oldText);
    $('span', this).not('.hidden').text(newText);
    return false;
  });

  /**
   * Sonderextrafall "PUK vergessen"
   */
  $("input#neue-karte-anfordern-order-simcard-0-order-simcard-reasonCode-puk-vergessen").click(
      function() {
          var __delAdr = $("input#neue-karte-anfordern-order-simcard-0-order-simcard-show-delivery-address-true");
          __delAdr.data('wasChecked', __delAdr.attr("checked")).attr("checked", false).attr("disabled", true);
          $("label.show-delivery-address").removeClass('disabled').addClass('disabled');
          $("fieldset#neue-karte-anfordern-order-simcard-0-delivery-address").fadeOut('fast').removeClass('disabled').addClass('disabled');
          $('input, select, textarea', $("fieldset#neue-karte-anfordern-order-simcard-0-delivery-address")).attr('disabled', 'disabled');
      }
  ).siblings('[name="reasonCode"]').click(
      function(){
          var __delAdr = $("input#neue-karte-anfordern-order-simcard-0-order-simcard-show-delivery-address-true");
          __delAdr.attr("disabled", false).attr("checked",  __delAdr.data('wasChecked'));
          $("label.show-delivery-address").removeClass('disabled');
          if (__delAdr.attr('checked')) {
              $("fieldset#neue-karte-anfordern-order-simcard-0-delivery-address").fadeIn('fast').removeClass('disabled');
              $('input, select, textarea', $("fieldset#neue-karte-anfordern-order-simcard-0-delivery-address")).removeAttr('disabled');
          }
      }
  );

  /**
   * hints bei formularfelder. stehen in den labels und werden von dort in den hintContainer kopiert.
   */
  $('#main form:not(.contact) input, #main form:not(.contact) select, #main form:not(.contact) textarea, #main form label.hasHint').focus(
      function() {
          var handle = this;
          var fieldset = $(handle).parents('fieldset').get(0)
          $(fieldset).css('z-index', '100');
          var _container = $('.hintContainer', fieldset);
          if (!_container.data('shaded')) {
            _container = shadeHint(_container);
          }
          _container.parents('div.hintLayer').css({ display: 'none'});
          var __text = $('label[for="'+handle.id+'"] span.hint', handle.form).html();
          if (__text) {
              _container.html('<p>' + __text + '</p>').fadeIn('fast');
              _container.parents('div.hintLayer').fadeIn('fast');
          }
      }
  ).blur(
      function() {
          var handle = this;
          var fieldset = $(handle).parents('fieldset').get(0)
          $(fieldset).css('z-index', '10');
          var _container = $('.hintContainer', fieldset);
          _container.parents('div.hintLayer').css({ display: 'none'});
      }
  );

  $('#main form label.hasHint').hover(
      function() {
          var handle = this;
          var fieldset = $(handle).parents('fieldset').get(0)
          $(fieldset).css('z-index', '100');
          var _container = $('.hintContainer', fieldset);
          if (!_container.data('shaded')) {
            _container = shadeHint(_container);
          }
          _container.parents('div.hintLayer').css({ display: 'none'});
          var __text = $('span.hint', handle).html();
          if (__text) {
              _container.html('<p>' + __text + '</p>').fadeIn('fast');
              _container.parents('div.hintLayer').fadeIn('fast');
          }
      }
      , function() {
          var handle = this;
          var fieldset = $(handle).parents('fieldset').get(0)
          $(fieldset).css('z-index', '10');
          var _container = $('.hintContainer', fieldset);
          _container.parents('div.hintLayer').css({ display: 'none'});
      }
  );

  function shadeHint(_cont) {
      var take = $('.shadow:first').clone();
      var elem = $('<div class="hintLayer"></div>');
      $(elem).append(take);
      $(_cont).before(elem);
      $(elem).append(_cont);
      _cont.data('shaded', true);
      return _cont;
  }

  $('.pagepeel-element img').mouseover(function () {
    resizePagePeel(this, $(this).width(), $(this).width());
  }).mouseout(function () {
    resizePagePeel(this, 145, 145);
  });

  if ($.browser.msie && 6 == parseInt($.browser.version)) {
    $('.teaserengine-adbar button').filter('.no-caroussel button').each(function () {
        $(this).data('action', $(this).attr('class'));
    });
    $('.teaserengine-adbar button').filter('.no-caroussel button').hover(function () {
        $(this).addClass($(this).data('action')+'-hover');
    }, function () {
        $(this).removeClass($(this).data('action')+'-hover');
    });
  }

  /* Login-Warteanimation */
  jQuery('body').append('<p id="logging-in" class="hidden"><img src="/inc_common/styles/img/ajax-loader-login.gif"  width="32" height="32" alt="Bitte warten" /><br />Sie werden angemeldet.</p>');
  //jQuery('body').append('<p id="logging-in" class="hidden"><img src="/inc_common/styles/img/ajax-loader-login-alt.gif"  alt="Bitte warten" /><br />Sie werden angemeldet.</p>');

  jQuery('#head form#global-login-0, #main form#login-login-0').submit(function(){
      tb_show('TITEL','#TB_inline?height=135&width=300&modal=true&inlineId=garnichts');
      //tb_show('TITEL','#TB_inline?height=175&width=300&modal=true&inlineId=garnichts');
      jQuery('#logging-in').removeClass('hidden').appendTo("#TB_ajaxContent");
      return true;
  })

  $('form.check_disabled').each(function() {
    var form = $(this);
    var inputs = $('input, select', form)
        .not(':disabled')
        .not(':hidden')
        .not(':submit')
        .not(':reset');
    if (0 == inputs.length) {
        $('button.submit, input.submit, a.submit', form)
            .addClass('disabled')
            .click(function () {
                return false;
            });
        form.submit(function () {
            return false;
        });
    }
  });

  /**
   * formcheck handler
   */
  initFormChecker('#main form');
  initFormChecker('#TB_window form');

  /**
   * cockpit pngfix
   */
  if ($.browser.msie && 6 == parseInt($.browser.version)) {
    jQuery('#cockpit #cockpit_kostencheck dl, #cockpit #cockpit_handy div img, #cockpit_handy_wahl div img,  #head div.user-auth form button.link img').pngfix();
  }


  var StageArrow = 
  {
    init:  function () 
    {
      $.easing['jswing'] = $.easing['swing'];

      $.extend( $.easing, 
      {
        easeInOutExpo: function (x, t, b, c, d) 
        {
          if (t==0) return b;
          if (t==d) return b+c;
          if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
          return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
        }
      });
      
      var jqoStage  = $('.stage-arrow');
      
      jqoExtIntro = {
        container: jqoStage,
        main:      $('.intro-elements-control', jqoStage),
        length:    $('.intro-elements-control ul li[class^="teaser"]', jqoStage).length,
        thumb:     $('.intro-paging' , jqoStage),
        h3:        $('.text h3 a', jqoStage),
        navLeft:   $('.intro-paging li:first',jqoStage),
        navRight:  $('.intro-paging li:last', jqoStage),
        navNLeft:  $('<div class="mod"><span class="arrow arrow-left"></span></mod>'),   
        navNRight: $('<div class="mod mod-right"><span class="arrow arrow-right"></span></mod>'),
        changeNav : function () 
        {
          if (this.thumb.find('li').length > 1) 
          {
            this.navLeft .remove();
            this.navRight.remove();
            this.container.append(this.navNRight);
            this.container.append(this.navNLeft);
          }
          
        },
        removeActiveThumb : function () 
        {
          this.thumb.find('li.active').removeClass('active');
          
        }
        
      };
      
      jqoExtIntro.h3.click(function()
      {
        return false;  
      });
      
      jqoExtIntro.changeNav();
      jqoExtIntro.thumb.find('li').each(function(index) 
       {
        $(this).attr('class', 'teaser_' +  index);
        if (index == 0) $(this).addClass('active');
      });
      
      var firstObj = $('.intro-elements-control ul li[class^="teaser"]', jqoStage).get(0);
      $(firstObj).data('hasSeen', true);
      trackTeaser(firstObj, 0);
      
      jqoExtIntro.main.jCarouselLite( 
      {
        afterEnd : function(obj) 
        {
          if (!obj.data("hasSeen") && !obj.data('cloned')) {
              obj.data("hasSeen", true);
              trackTeaser(obj, 0);
          }
          jqoExtIntro.removeActiveThumb();
          jqoExtIntro.thumb.find('li.' + obj.attr('class')).addClass('active');
        },
        easing : 'easeInOutExpo',
        speed : 800,
        visible : 1,
        btnGo : jqoExtIntro.thumb.find("li"),
        btnPrev: jqoExtIntro.navNLeft,
        btnNext: jqoExtIntro.navNRight
      });
            
      if (jqoExtIntro.thumb.find('li').length >= 4) 
      {
        jqoExtIntro.thumb.jCarouselLite( 
        {
            speed : 800,
            visible : 4,
            easing : 'easeInOutExpo',
            btnPrev: jqoExtIntro.navNLeft,
            btnNext: jqoExtIntro.navNRight,
            vertical: (jqoStage.attr('id') == 'stage-v-arrow')
        });
        
        jqoExtIntro.thumb.addClass('init-carousel');
        jqoExtIntro.container.find('.mod').addClass('init-carousel-arrow');
      }
      
      

    }
  };
  
  /**
   * intro-element-rotation und control
   */
  if ($('.stage-arrow').length > 0 ) StageArrow.init();
  else   initIntroControls('div.intro-elements-control');

  
  jQuery('label.agree_advertising a').click(function(){
      window.open(this.href);
      return false;
  });

    $("button.delLi").click(function() {
        delLi($, this);
    });

    $("button.moveLiUp").click(function() {
        moveLiUp($, this);
    });

    $("button.moveLiDown").click(function() {
        moveLiDown($, this);
    });

    $("button.delTr").click(function() {
        //TODO: ersetze parents("tr").eq(0) durch closest("tr") mit jQuery 1.3
        $(this).parents("tr").eq(0).fadeOut("slow", function() {
            $(this).remove();
        });
    });

  $("button.moveTrUp").click(function() {
      //TODO: ersetze parents("tr").eq(0) durch closest("tr") mit jQuery 1.3
      var row = $(this).parents("tr").eq(0);
      if (row) {
          $(row).prev("tr").before(row);
      }
  });

  $("button.moveTrDown").click(function() {
      //TODO: ersetze parents("tr").eq(0) durch closest("tr") mit jQuery 1.3
      var row = $(this).parents("tr").eq(0);
      if (row) {
          $(row).next("tr").after(row);
      }
  });

    $(".autoSubmit").change(function() {
        this.form.submit();
    });

  // tariffchange dynamisch
  $('form#tarifwechsel-tariffchange-tariff-dynamisch-0 input[name="tariff"]').click(function(){
      showHideHomezoneFields($(this).hasClass('homecell'));
      /*
      $('tr.optionen').addClass('hidden').css({display: 'none'});
      // hol die optionen, wenn er optionen hat..
      if (!$(this).data('optionen')) {
          // hols und speichers
          $(this).data('optionen', true);
          $(this.parentNode.parentNode).after('<tr class="hidden optionen" id="option_'+$(this).val()+'"><td>&nbsp;</td><td colspan="6">OPTIONEN</td></tr>');
      }
      $('tr#option_' + $(this).val()).fadeIn('fast', function(){$(this).removeClass('hidden');});
      */
  });

  if ($('form#tarifwechsel-tariffchange-tariff-dynamisch-0').length > 0) showHideHomezoneFields($('form#tarifwechsel-tariffchange-tariff-dynamisch-0 input[name="tariff"]:checked').hasClass('homecell'));

  // frage der woche: HFO homepage und evtl. wie gehabt im debitel-auftritt?
  if ($('div#frageDerWoche').length>0) {
    $.get('/ajax/frage-der-woche.php', function(data){

      if (data.search(/.*##HIDEME##.*/)!=-1) {
          $('div#frageDerWoche').css({ display: 'none' });
      } else {
          $('div#frageDerWoche').html(data);
          $('div#frageDerWoche').data('visible', true);
          controlQuestionOfTheWeek();
          $('div#frageDerWoche button[type="submit"]').click(function(){ return(submitQuestionOfTheWeek());});
          $('div#frageDerWoche button.cancel').click(function(){ return(cancelQuestionOfTheWeek()); });
      }
    });

    function cancelQuestionOfTheWeek() {
          $.get("/ajax/frage-der-woche.php", {showWeeklyQuestion: 'false'});
          var qotw = $('div#frageDerWoche');
          qotw.data('visible', false);
          qotw.animate({height: '0px'}, 'fast', function(){ $(qotw).css({display: 'none'})});
          return false;
    }

    function submitQuestionOfTheWeek() {
        $.post("/ajax/frage-der-woche.php", $("div#frageDerWoche form").serialize(), function(data){
          $('div#frageDerWoche').html(data);
          $('div#frageDerWoche button[type="submit"]').click(function(){return(submitQuestionOfTheWeek())});
          $('div#frageDerWoche button.cancel').click(function(){ return(cancelQuestionOfTheWeek()); });
          controlQuestionOfTheWeek();
        });
        return false;
    }

    // control sliding effect
    function controlQuestionOfTheWeek() {
      var qotw = $('div#frageDerWoche');
      //$(qotw).prepend('<span class="topShadow">&nbsp;</span>');

      $('h3.result', qotw).click(function() {
        if (qotw.data('visible')) {
          qotw.data('visible', false);
        //  if ($('button[type="submit"]', qotw).length>0) { // noch nicht geantwortet
        //      qotw.animate({height: '25px'}, 'fast');
        //  } else {
              qotw.animate({height: '0px'}, 'fast', function(){ $(qotw).css({display: 'none'})});
        //  }
          $.get("/ajax/frage-der-woche.php", {showWeeklyQuestionResults: 'false'});
        } else {
          qotw.animate({height: '100%'}, 'fast', 'linear', function() {
            $(this).data('visible', true);
          });
          $.get("/ajax/frage-der-woche.php", {showWeeklyQuestionResults: 'true'});
        }
      });
    }
  }
  trigger.init();
});

function showHideHomezoneFields(homezoneTariff) {
      // if homezone-tarif!
      if (homezoneTariff) {
          jQuery('form#tarifwechsel-tariffchange-tariff-dynamisch-0 #tarifwechsel-tariffchange-tariff-dynamisch-0-change-homezone-address').slideDown('fast');
          jQuery('form#tarifwechsel-tariffchange-tariff-dynamisch-0 #tarifwechsel-tariffchange-tariff-dynamisch-0-change-homezone-address input').removeClass('disabled').removeAttr('disabled');
      } else {
          jQuery('form#tarifwechsel-tariffchange-tariff-dynamisch-0 #tarifwechsel-tariffchange-tariff-dynamisch-0-change-homezone-address').css({display: 'none'});
          jQuery('form#tarifwechsel-tariffchange-tariff-dynamisch-0 #tarifwechsel-tariffchange-tariff-dynamisch-0-change-homezone-address input').removeClass('disabled').addClass('disabled').attr('disabled', true);
      }
}

/*
jQuery.fn.wait = function(time, type) {
    time = time || 5000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            jQuery(self).dequeue();
        }, time);
    });
};
*/

/**
 * resizePagePeel
 * used in PagePeel swf to flip open/close the pagepeel
 */
function resizePagePeel(id, w, h){
    $elem = jQuery(id).parent();
    $elem.css({
        height: h + 'px',
        width: w + 'px'
    });
}

/**
 * hideFlashLayer
 * used in PagePeel/PowerLayer swf
 */
function hideFlashLayer(id) {
    jQuery(id).parent().hide();
}

function initBookingLayer (selector) {
  var $ = jQuery;
  $(selector).addClass('showOverhead').addClass('booking-layer');
  $('.info a.button:first', selector).hover(function() {
    $('.intro', selector).stop().removeClass('intro-tariff').fadeOut(100, function() {
      $(this).addClass('intro-handy').fadeIn(100);
    })
  }, function() {
    $('.intro', selector).stop().css('opacity', 1).fadeOut(100, function() {
      $(this).removeClass('intro-handy').fadeIn(100);
    })
  });
  $('.info a.button:last', selector).hover(function() {
    $('.intro', selector).stop().removeClass('intro-handy').fadeOut(100, function() {
      $(this).addClass('intro-tariff').fadeIn(100);
    })
  }, function() {
    $('.intro', selector).stop().css('opacity', 1).fadeOut(100, function() {
      $(this).removeClass('intro-tariff').fadeIn(100);
    })
  });

  function hoverStatus(o, s, h) {
    if (o.data('animation')) {
      o.stop();
      o.data('animation', false);
    }
    $('.intro', selector).fadeOut(100, function() {
      if (h)
        $(this).addClass(s).fadeIn(100);
      else
        $(this).removeClass(s).fadeIn(100);
    });
  }
}

function initQuickAccessList(selector, modal) {
  if (modal) {
    jQuery('#TB_ajaxContent').addClass('showOverhead');
  }
  jQuery('.quickAccess > div', selector).hover(
    function() {
      jQuery('.container', this).stop(true, true).slideDown('fast');
    },
    function() {
      jQuery('.container', this).stop(true, true).slideUp('fast');
    }
  );
  jQuery('.quickAccess div p > a', selector).click(
    function(){ return false; }
  ).css({ cursor: 'text'});
  jQuery('.quickAccess div.infoEvents ul a', selector).click(
    function() {
      jQuery('.quickAccess div.infoEvents p', selector).removeClass('blink');
    }
  );
  if (0 < jQuery('div.subscriberSwitch', selector).length) {
    jQuery('.quickAccess div.subscriberSwitch p > a', selector).getsubscribers();
  }
}

function initIntroControls(selector) {

    introControl.selector = selector;
    introControl.identifier = jQuery(selector).hasClass('hasThumbs');
    introControl.totalIntros = jQuery(introControl.selector + ' .intro-elements-container > li').length;

    // WiredMinds - Teaser Tracking -  View for first intro element
    jQuery(introControl.selector + ' .intro-elements-container li.teaser_0').each(function() {
      jQuery(this).data("hasSeen",true);
      trackTeaser(jQuery(this), 0);
    });


    if (introControl.totalIntros>1) {
        introControl.markNav();
        jQuery(introControl.selector + ' .intro-paging ul li a').click(function(){
            window.clearTimeout(introControl.introTimer);
            introControl.introTimer = false;
            var idx = this.className.split('teaserlink_')[1];
            if (idx=='next') {
                introControl.nextIntro();
            } else if (idx=='prev') {
                introControl.prevIntro();
            } else {
                introControl.showElement(idx);
            }
            return false;
        });
        introControl.introTimer = window.setTimeout('introControl.nextIntro()', introControl.timerInterval);
    }
    if (jQuery.browser.msie && 6 == parseInt(jQuery.browser.version)) {
        jQuery(introControl.selector + ' .intro-elements-container .intro-element .addon-medium img').pngfix();
    }
}

var tempSpeed;

var introControl = {
    timerInterval: 7000,
    identifier : false,
    introTimer: false,
    activeControl : null,
    activeElementIdx: 0,
    selector: '',
    speed : 'fast',
    totalIntros: 0,
    showElement: function(idx) {
      if (this.activeElementIdx != idx) {
        this.speed = 'fast';
        if (this.introTimer != false)
          this.speed = 'slow';
        var nextObj = jQuery(this.selector + ' .intro-elements-container > li.teaser_' + idx);
        nextObj.css({
          marginLeft: '0px',
          display: 'none'
        });
        // ie8 has problems with opacity rendering using fadeOut or animate
        // function, so we need a sequence
      
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 8) {
          tempSpeed = this.speed;
          this.speed = 10;
          jQuery(this.selector + ' .intro-elements-container > li.teaser_' + this.activeElementIdx).fadeOut(this.speed, function() {
            nextObj.fadeIn(this.speed);
          });
        } else {
          jQuery(this.selector + ' .intro-elements-container > li.teaser_' + this.activeElementIdx).fadeOut(this.speed);
          // WiredMinds - Teaser Tracking - Views for the intro elements
          nextObj.fadeIn(this.speed);
        }
        if (!nextObj.data("hasSeen")) {
          nextObj.data("hasSeen", true);
          trackTeaser(nextObj, 0);
        }

        this.activeElementIdx = idx;
        this.markNav();
      }
    },
    markNav: function() {
      var $ = jQuery;
      activeControl = $(this.selector + ' .intro-paging ul li a.teaserlink_'+this.activeElementIdx).parent();
      $(this.selector + ' .intro-paging ul li').removeClass('active');
      activeControl.removeClass('active').addClass('active');
      if (this.identifier) {
        var item = activeControl.offset();
        var scope = $(this.selector + ' .intro-paging').offset();
        if ($(this.selector).hasClass('vertical')) {
          // vertical thumbs
          if (0 < this.activeElementIdx) {
            
            // Target ie 8
            if ($.browser.msie && $.browser.version == 8)
            {
              // restore the speed defined previous
              this.speed = tempSpeed
            }
         
            $(this.selector + ' .identifier').animate({
              top : (item.top - scope.top) + 'px'
            }, this.speed);
          } else {
            var _this = this;
            $(this.selector + ' .identifier').fadeOut(this.speed, function() {
              $(this).css('top', (item.top - scope.top) + 'px')
                .fadeIn(_this.speed);
            });
          }
        } else {
          // horizontal thumbs
        }
      }
    },
    nextIntro: function() {
        if ((this.activeElementIdx/1+1) < this.totalIntros)
            this.showElement((this.activeElementIdx/1+1));
        else
            this.showElement(0);
        if ( this.introTimer!=false ) this.introTimer = window.setTimeout('introControl.nextIntro()', this.timerInterval);
    },
    prevIntro: function() {
        if ((this.activeElementIdx/1-1) >= 0)
            this.showElement((this.activeElementIdx/1-1));
        else
            this.showElement((this.totalIntros/1-1));
        if ( this.introTimer!=false ) this.introTimer = window.setTimeout('introControl.prevIntro()', this.timerInterval);
    }
}


var formchecker = {
    init: function(selector) {
        jQuery(selector).data('form_valid', true);

        jQuery(selector + ' button[type="reset"]').click(function(){
          jQuery(this.form).data('form_valid', true);
          jQuery('input, select, textarea, label', this.form).not("[type='hidden']").removeClass('error');
        });

        jQuery(selector + ':not(#activation) button[type="submit"]').not("[name='__RESET_FUZZY__']").click(function(){
          jQuery(this.form).data('form_valid', true);
          jQuery('input, select, textarea', this.form).not("[type='hidden']").each(function(){
            formchecker.formcheck(this);
          });
          return (jQuery(this.form).data('form_valid'));
        });

        jQuery(selector + ' input, ' + selector + ' select, ' + selector + ' textarea').not("[type='hidden']").each(function(){
          var __checktype = false;
          var __checkexp = /(check_)([^\s]*)/;
          __checktype = __checkexp.exec(jQuery(this).attr('class'));
          jQuery(this).data('required', jQuery(this).hasClass('required'));
          try {
            if (!__checktype || !__checktype[2] || __checktype[2] == '')
              jQuery(this).data('checktype', 'undefined');
            else jQuery(this).data('checktype', __checktype[2]);
          } catch (e) {
            jQuery(this).data('checktype', 'undefined');
          }
        }).blur(function(){
          formchecker.formcheck(this);
        });

        jQuery('input[name="wantsConfirmationMail"]').click(function(){
            if (this.checked) {
                jQuery('input[name="confirmationEmail"]', this.form).data('required', true);
            } else {
                jQuery('input[name="confirmationEmail"]', this.form).data('required', false);
            }
        });
    },
    formcheck: function(formfield) {
        if (!jQuery(formfield).attr('disabled')) {
            if (!jQuery(formfield).data('required') && formfield.value=='') {
                jQuery(formfield).removeClass('error');
                jQuery('label[for="'+formfield.id+'"]').removeClass('error');
            } else if (
                   (jQuery(formfield).data('required') && formfield.value=='')
                || (jQuery(formfield).attr('minlength') && formfield.value.length<jQuery(formfield).attr('minlength'))
                || (jQuery(formfield).data('required') && jQuery(formfield).hasClass('option') && jQuery("input.option[name='" + formfield.name + "']:checked", formfield.form).length < 1 )
                || (formfield.value == formfield.title)
                || (formfield.value.search(formchecker.definitions[jQuery(formfield).data('checktype')])==-1)
                || (jQuery(formfield).data('checktype')=='birthday18' && !formchecker.checkBirthday(formfield.value))
              ) {
              jQuery(formfield).removeClass('error').addClass('error');
              jQuery('label[for="'+formfield.id+'"]').removeClass('error').addClass('error');
              jQuery(formfield.form).data('form_valid', false);
            } else {
              jQuery(formfield).removeClass('error');
              var name = jQuery(formfield).attr('name');
              jQuery('input[name='+name+'], select[name='+name+'], textarea[name='+name+']').each(function () {
                jQuery('label[for="'+this.id+'"]').removeClass('error');
              });
             }
        }
    },
    checkBirthday: function(value) {
        var success = false;
        var date = value.split('.');
        if (date.length == 3) {
            var myDate = new Date(date[2], (date[1]-1), date[0]);
            var now = new Date();
            var diff =  now.getTime() - myDate.getTime();
            if (
                  (diff<=0) // zukunft
               || ((myDate.getMonth()+1) != date[1]) // wenn sich der monat geaendert hat, wars ein falsches datum.
               || (diff < (17.9 * 365.25 * 24 * 60 * 60 * 1000)) // 18 pruefen, lieber leger als zu fies 
                                                              // schaltjahre etc. seien dahingestellt..
            ) {
                success = false;
            } else {
                success = true;
            }

        }
        return success;
    },
    definitions: {
          // used by Format.inc.php
          undefined       : /.*/,
          'null'          : /.*/,
          password        : /.*/,
          username        : /.*/,
          salutation      : /^((Herr|Frau)|(Firma))$/,
          name            : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          namewithnumbers : /^[a-zA-Z0-9 \/\._\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{1,40}$/,
          number          : /^\d+([.,]?\d+)?$/,
          msisdn          : /^\d+$/,
          email           : /^[a-zA-Z0-9][a-zA-Z0-9\.\-_]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/,
          phone           : /^\s*((\(?\+?\s?[0-9]*\s?\)|\+?[0-9]*(\s*[\/.]\s*)?)\s*)?([0-9]+\s*[_\-\(\)\/.]\s*)*([0-9]+\s*)+$/,
          zip             : /^([A-Z]-)?[0-9]{4,5}$/,
          //username   : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          //password   : /^[a-zA-Z\u00A1-\uFFFF]+$/, // INCLUDES UTF-8 CHARS
          street          : /^[a-zA-Z \/\.\-\(\)\&\'\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          city            : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          location        : /^[0-9 \/\.\-\(\)]{0,10}[A-Za-z0-9]?$/,
          text            : /^[a-zA-Z0-9 \n\r\u0021-\u03D6\u2013-\u20AC]+$/,
          country         : /^[a-zA-Z \/\._\-\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{1,40}$/,
          bankcode        : /^\d{3}\s{0,1}\d{3}\s{0,1}\d{2}$/,
          truefalsenull   : /^(true|false|)$/,

          // from srm3.0
          alpha      : /^[a-zA-Z\u00A1-\uFFFF]+$/, // INCLUDES UTF-8 CHARS
          decimal    : /^[0-9]+([\.,]{1}[0-9][0-9]?)?$/,
          firstname  : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          lastname   : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          // namenszusaetze:  /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          title      : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          co         : /^[a-zA-Z \/\.\-\(\)\&\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u0178\u0391-\u03D6]{2,40}$/,
          date       : /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/,
          birthday18   : /^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[012])\.(19|20)\d\d$/,
//            geburtsdatum :      /^(([0-2][1-9])|([3][0-1]))\.((0[1-9])|(1[0-2]))\.((19[20-99])|(20[0-1][0-9]))$/,
          websiteurl : /^((http|https):\/\/)?((([A-Za-z0-9][A-Za-z\-_.0-9])*[A-Za-z0-9])+(:((?![:@]).)+)?@)?([A-Za-z0-9\-]+\.)+[A-Za-z0-9]+(:[0-9]{2,4})?(\/[A-Za-z0-9\-_ .\/%\&=]*)?(\?([A-Za-z0-9\-_ .\/\&='"])+(%[0-9a-fA-F]{2})*([A-Za-z0-9\-_ .\/\&='"])+)?$/,
          anyurl     : /^((http|https|ftp|mailto):\/\/)?((([A-Za-z0-9][A-Za-z\-_.0-9])*[A-Za-z0-9])+(:((?![:@]).)+)?@)?([A-Za-z0-9\-]+\.)+[A-Za-z0-9]+(:[0-9]{2,4})?(\/[A-Za-z0-9\-_ .\/%\&=]*)?(\?([A-Za-z0-9\-_ .\/\&='"])+(%[0-9a-fA-F]{2})*([A-Za-z0-9\-_ .\/\&='"])+)?$/
      }

}


/**
 * backward compatibility
 * coding rule: do not spoil the global namespace
 * TODO: check for usage, and replace all occurences with the formchecker.init
 * then remove this function.
 * @param selector
 */
function initFormChecker(selector) {
    formchecker.init(selector);
}

var trigger = {
    init: function () {
        var $ = jQuery;
        $('#main form input[type="checkbox"].trigger, #main form input[type="radio"].trigger,' +
          '#TB_window form input[type="checkbox"].trigger, #TB_window form input[type="radio"].trigger').click(function() {
              trigger.toggle(this, false);
        });
        /**
         * triggers. fieldsets can be triggered only by options
         * forms without checked triggers should display no triggered fieldsets
         */
        $('#main form input.trigger, #TB_window form input.trigger').each(function() {
              var triggerdata = {show:[], hide:[]};
              var triggers = $(this).attr('class').split(' ');
              $.each(triggers, function() {
                if (this.match(/(hide|show)__/)) {
                  var trigger = this.split("__");
                  triggerdata[trigger[0]].push($('#'+trigger[1]));
                }
              });

              $(this).data('triggers', triggerdata);
              trigger.toggle(this, true);
        });

        $('#main form input[type="radio"].trigger, #TB_window form input[type="radio"].trigger').each(
          function() {
            var _myTrigger = this;
            $(this).siblings('[name="'+this.name+'"]').not('.trigger').click(
            function(){
              trigger.toggle(_myTrigger, false);

            });
        });
    },
    toggle: function (aTrigger, init) {
       var $ = jQuery;
       var triggerdata = $(aTrigger).data('triggers');
       $.each(triggerdata.show, function () {
          if (aTrigger.checked) {
            this.fadeIn('fast').removeClass('disabled');
            $('input, select, textarea', this).removeAttr('disabled');
            $('label[for='+this.attr('id')+']').fadeIn('fast');
            this.removeAttr('disabled');
          } else {
            this.fadeOut('fast').removeClass('disabled').addClass('disabled');
            $('input, select, textarea', this).attr('disabled', 'disabled');
            $('label[for='+this.attr('id')+']').fadeOut('fast');
            this.attr('disabled', 'disabled');
          }
        });

        $.each(triggerdata.hide, function () {
          if (aTrigger.checked) {
            this.fadeOut('fast').removeClass('disabled').addClass('disabled');
            $('input, select, textarea', this).attr('disabled', 'disabled');
            $('label[for='+this.attr('id')+']').fadeOut('fast');
            this.attr('disabled', 'disabled');
          } else if (!init){
            this.fadeIn('fast').removeClass('disabled');
            $('input, select, textarea', this).removeAttr('disabled');
            $('label[for='+this.attr('id')+']').fadeIn('fast');
            this.removeAttr('disabled');
          }
        });
      }
};


var thickbox = {
    initForm: function () {
        formchecker.init('#TB_ajaxContent form');
        trigger.init();
        var $ = jQuery;
        $('form .buttons button[type=submit]').click(function () {
            var action = $(this).attr('id').replace(/^.*-([^-]+)$/, "$1");
            var form = $(this).parents('form');
            $('input[name=action]').val(action);
        });
        $('#TB_ajaxContent form').submit(function () {
            var form = $(this);
            var method = $(this).attr('method');
            var action = $(this).attr('action');
            var params = $('input, textarea, select', this).serialize();
            $[method](action, params, function(data) {
                if ('reload' == data) {
                    location.reload();
                } else if ('close' == data) {
                    tb_remove();
                } else {
                    $('#TB_ajaxContent').html(data);
                }
            });
            return false;
        });
    }
}

/* carousel hfo kampagne.. aber vllt. kann mans woanders noch brauchen? */
var carousselFunctions = {
    beforeStartKampagne: function(elems, typ) {
        if (typ!='tarife') {
            jQuery('.caroussel .details > div').fadeOut();
            jQuery('span.type, span.stoerer, h6', elems.eq(1)).fadeOut();
        } else {
        }
    },
    afterEndKampagne: function(elems, typ) {
        if (typ!='tarife') {
            jQuery('span.type, span.stoerer, h6', elems.eq(1)).fadeIn();
            jQuery('.caroussel .details div#details_'+elems.get(1).id.replace('item_', '')).fadeIn();

        } else {
            jQuery('div#id_' + elems.attr('class').split('__')[1] + ' .lefthero .hwdetails').css({display: 'none'});
            jQuery('div#id_' + elems.attr('class').split('__')[1] + ' .lefthero .'+elems.attr('class').split('__')[0]).css({display: 'block'});
           try{
            if (jQuery('div#id_' + elems.attr('class').split('__')[1] + ' .lefthero div.cluster_' +  elems.find("span[class!=preis]:first").attr("class") ).length != 0) {
            jQuery('div#id_' + elems.attr('class').split('__')[1] + ' .lefthero div.cluster').hide();
            jQuery('div#id_' + elems.attr('class').split('__')[1] + ' .lefthero div.cluster_' +  elems.find("span:first").attr("class") +  ':first').show();
        } } catch(error){
           }

       }
    }
}


function delLi($, button) {
    //TODO: ersetze parents("li").eq(0) durch closest("li") mit jQuery 1.3
    $(button).parents("li").eq(0).fadeOut("slow", function() {
        $(this).remove();
    });
}

function moveLiUp($, button) {
    //TODO: ersetze parents("li").eq(0) durch closest("li") mit jQuery 1.3
    var row = $(button).parents("li").eq(0);
    if (row) {
        // wenn es einen vorgänger gibt...
        $(row).prev("li").not(".hidden").each(function () {
            // merken...
            var prev = this;
            // ursprüngl. zeile ausblenden...
            $(row).slideUp("slow", function() {
                // und dann eins davor wieder einfügen und einblenden.
                $(prev).before(this);
                $(this).slideDown("slow");
            });
        });
    }
}

function moveLiDown($, button) {
    //TODO: ersetze parents("li").eq(0) durch closest("li") mit jQuery 1.3
    var row = $(button).parents("li").eq(0);
    if (row) {
        $(row).next("li").not(".hidden").each(function() {
            var next = this;
            $(row).slideUp("slow", function() {
                $(next).after(this);
                $(this).slideDown("slow");
            });
        });
    }
}

/* WiredMinds - Teaser Tracking - Tracking function */
function trackTeaser(obj, method, dynPath) {

  /* View Event */
  if (method == 0) {
    trackEvent = (dynPath  == undefined) ? jQuery(obj).find("a[rel]").attr("rel") : dynPath;
    if (trackEvent != undefined) {
      trackEvent = "TE-Views/" + trackEvent;
      try {
          wiredminds.push(['trackEvent', trackEvent]);
      } catch(e) {;}
    }
    
    /* Click Event*/
  } else {
    trackEvent = (dynPath  == undefined) ? jQuery(obj).attr("rel") : dynPath;
    if (trackEvent != undefined) {
      trackEvent = "TE-Clicks/" + trackEvent;
      try {
          wiredminds.push(['trackEvent', trackEvent]);
      } catch(e) {;}
      return false;
    }
  }

}

/* WIREDMINDS DOWNLOADS TRACKING */
var types = ['pdf', 'doc', 'zip', 'xls', 'ppt', 'exe', 'flv'];

jQuery.each(types, function() {
  var _this = this;
  jQuery('a[href$=.'+ _this +']').click(function() {
   var link = this.href;
   var pattern = new RegExp("(.*\/)([\\w\-]+\." + _this + ")$", "i");
   var result = link.match(pattern);
   var regExp = RegExp.$2;

   try {
       wiredminds.push(['count', regExp]);
   } catch (e) {;}

  });
});
/* /WIREDMINDS DOWNLOADS TRACKING */

