/* --- Global Timeout --- */

var logoutTimoutID = 0;
var intLogout      = 30 * 60 * 1000;

jQuery(function($) {
    if ( $('form#global-logout').length ) {
        // call first time the logout
        setLogout();

        // Set human interaction capture to set the interval back
        document.onkeydown   = interAction;
        document.onmousedown = interAction;
    }

});


jQuery(function($) {

    var ajaxCalls = [];

    // dirty: host detection via DOM
    var host = '';
    var js = /(https?:\/\/[^\/]+)\/.*portal\.js$/;
    $('script[src]').filter(function() {
        return (this.src.search(js) > -1);
    }).each(function() {
        host = RegExp.$1;
    });

    // portal.css laden
    $('head').append($('<link href="'+host+'/inc_common/styles/css/portal.css" type="text/css" rel="stylesheet" media="screen, print" />'));

    if (/^\/online-shop\/handys.*/.test(window.location.pathname)
        || /action=devicedetail/.test(window.location.search))
    {
        $('#telesales').before('<div id="bn_handy_page"></div>');
    }
    if (/^\/online-shop\/tarife.*/.test(window.location.pathname)
        || /action=tariffdetail/.test(window.location.search))
    {
        $('#telesales').before('<div id="bn_tariff_page"></div>');

    }

    // baynote.js in den DOM inject'n
    if (/^\/online-shop.*/.test(window.location.pathname)
        || /action=devicedetail|action=tariffdetail/.test(window.location.search))
    {
        $('body').append('<script type="text/javascript" src="'+host+'/inc_common/scripts/js/baynote.js" defer="defer"></script>');
    }
    

    /* TeleSales Shop Layer */
    
    $.fn.telesales = function(options) 
    {

      var settings = $.extend({
        container : false,
        content   : '/ajax/telesales-box.php',
        css       : '/inc_common/styles/css/telesales.css',
        //js        : '/inc_common/scripts/js/telesales.js',
        smallBox  : false
      }, options);

      var _this = $(this);

      init();

      function init() 
      {
   
        if ($('body').attr('id') != 'online-shop') 
          settings.smallBox = true;
        
        $('head').append('<link rel="stylesheet" href="'+host + settings.css + '" />');
        if (settings.container) 
        {
          // load and insert content for telesales controls
          $.getJSON(host + settings.content + "?jsonp=?",
            function(data) 
            {
              _this.html(data);
             initTabs();
             var jqoLink = _this.find('a.thickbox');
             
             jqoLink.attr('href' ,  host +  jqoLink.attr('href'));
            
             tb_init('#telesales .thickbox');
            }
          );
        }
        
        if (settings.smallBox) 
        {
          _this.addClass('smallbox');
          $('.tabs span', _this).each(function(i) 
          {
            $(this).attr('title', $(this).text());
          });
        }
      }

      function initTabs() {

        var activeContent = $('.tabscontainer li.active', _this);
        var animation = false;
        var contents = $('.tabcontainer li', _this);
        var controls = $('.tabs li', _this);

        controls.click(function() {

          var self = $(this);

          if (!animation && !self.hasClass('active')) {

            animation = true;
            var nextContent = $(contents.get(controls.index(self)));

            contents.filter('.active').fadeOut('fast', function() {
              controls.filter('.active').removeClass('active');
              $(this).removeClass('active');
              self.addClass('active');
              nextContent.addClass('active').fadeIn('fast', function() {
                animation = false;
              });
            });
          }
          return false;
        });
      }

    }; /*/ fn.telesales */


    // Kommentarleiste
    var commentBar = {
        sichtbar: '',
        lightboxed: false,
        closeComments: function() {
            this.sichtbar = '';
            this.lightbox(false, "#commentbarResult");
        },
        toggleComments: function(zuZeigendes) {
            if (this.sichtbar==zuZeigendes) {
                this.closeComments();
            } else {
                $("#commentbarDialog").html('<p>Bitte warten...</p>');
                this.showComments(zuZeigendes);
            }
        },
        expandComment: function(aLi) {
            $("p" , aLi).slideToggle( 200 );
        },
        closeLeiste: function() {
            $('body').animate({ paddingTop: "0px" });
            $('#commentbar').slideUp( 200 );
            this.closeComments();
        },
        showComments: function(zuZeigendes, abgeschlossen, absenden) {
            var self = this;
            this.sichtbar = zuZeigendes;
            if (zuZeigendes == 'showComments') {
                abgeschlossene = (abgeschlossen) ? 0 : 1;
                $.getJSON(host+"/ajax/comment-function.php?jsonp=?",
                    {
                        funktion: "doList",
                        pathFilter: window.location.pathname+window.location.search,
                        finished: abgeschlossene
                    },
                    function(data) {
                        $("#commentbarDialog").html(data);
                        $("#commentbarDialog a.closeButton").click(function() {
                            self.closeComments();
                        });
                        $("#commentbarDialog li").click(function() {
                            self.expandComment(this);
                        });
                        $("#check_finished").click(function() {
                            self.showComments('showComments', this.checked);
                        });
                        $("#commentSubmitButton").click(function() {
                            self.showComments('submitComment', 0, true);
                            return false;
                        });
                        $("#displayTitle").html( document.title );
                        self.lightbox(true, "#commentbarResult");
                    }
                );
            } else if ( zuZeigendes == 'submitComment') {
                if (absenden) {
                    if (window.location.search=='') var queryStr = ' ';
                    else var queryStr = window.location.search;
                    _title = $('#kommentar_myTitle').attr('value');
                    _text = $('#kommentar_myText').attr('value');
                    _cbNumber = $('#kommentar_cbNumber').attr('value');
                    _cbMail = $('#kommentar_cbMail').attr('value');
                    if (window.innerWidth!=undefined) {
                        _browser_size = window.innerWidth+'x'+window.innerHeight;
                    } else {
                        _browser_size = document.body.clientWidth+'x'+document.body.clientHeight;
                    }

                    _params = {
                        funktion: "doComment",
                        pathFilter: window.location.pathname+window.location.search,
                        aktion: "absenden",
                        myTitle: ((_title!=undefined)?_title:''),
                        myText: ((_text!=undefined)?_text:''),
                        cbNumber: ((_cbNumber!=undefined)?_cbNumber:''),
                        cbMail: ((_cbMail!=undefined)?_cbMail:''),
                        scriptname: window.location.pathname,
                        querystring: queryStr,
                        monitor_resolution: screen.width+'x'+screen.height,
                        browser_size: _browser_size
                    };
                } else {
                    _params = {
                        funktion: "doComment",
                        pathFilter: window.location.pathname+window.location.search
                    };
                }
                $.getJSON(
                    host+"/ajax/comment-function.php?jsonp=?",
                    _params,
                    function(data) {
                        $("#commentbarDialog").html(data);
                        $("#commentbarDialog a.closeButton").click(function() {
                            self.closeComments();
                        });
                        $("#commentbarDialog li").click(function() {
                            self.expandComment(this);
                        });
                        $("#check_finished").click(function() {
                            self.showComments('showComments', this.checked);
                        });
                        $("#commentSubmitButton").click(function() {
                            self.showComments('submitComment', 0, true);
                            return false;
                        });
                        $("#displayTitle").html( document.title );
                        self.lightbox(true, "#commentbarResult");
                    }
                );
            }
        },
        lightbox: function(show, elem) {
            if (show && !this.lightboxed) {
                this.lightboxed = true;
                var el = $('<div id="lightbox" class="fixed"></div>');
                $('body').append(el);
                if ($.browser.msie && $.browser.version < 7) {
                    $('#lightbox.fixed').css({
                        height: $("body").height()+22
                    });
                    $('#content select').css({
                        visibility: 'hidden'
                    });
                }
                if (elem) {
                    $(elem).before(el);
                }
                $(elem).fadeIn('fast');
            } else if (!show) {
                this.lightboxed = false;
                $(elem).fadeOut('fast', function(){
                    $('#lightbox').remove();
                });
                if ($.browser.msie && $.browser.version < 7) {
                    $('#content select').css({
                        visibility: 'visible'
                    });
                }
            }
        }
    };

    if ($('body').not('.hideFeedback').length) {
      $.getJSON(
          host+"/ajax/comment-bar.php?jsonp=?",
          function(data) {
              if (data) {
                  $('body').append(data).animate({paddingTop: '23px'});
                  $('#commentbar').slideDown();
                  $('#commentbarCommentIt a').click(function(){
                      commentBar.toggleComments('submitComment');
                  });
                  $('#commentbarShowComments a').click(function(){
                      commentBar.toggleComments('showComments');
                  });
                  $('#commentbar a.closeButton').click(function(){
                      commentBar.closeLeiste();
                  });
              }
          }
      );
    }

    // Suggest
    //$('#global-search-0-search-search').unbind('keydown').unbind('keyup');
    // Autocomplete abschalten:
    $('#global-search-0-search-search').attr('autocomplete', 'off');
    $('#global-search-0-search-search').each(function() {
        // Charset erzwingen (damit auch auf ISO-Seiten UTF-8 verschickt wird):
        $(this.form).attr('accept-charset', 'UTF-8');
        // Erstmal dieses dumme hidden input-Feld entfernen, da wir sonst
        // die Formular-Action nicht ändern können:
        $("input:hidden[name='action']", this.form).remove();
        // Dann die Formular-Action hart setzen, damit das URL-encoding nicht
        // beim Redirect kaputt geht:
        $(this.form).attr('action', function() {
            return $(this).attr('action').replace(/.*\/redirect\/portal/, host);
        });
    });

    // Keydown-Events: Timer clearen, Cursor-Events verarbeiten, Enter
    // selektiert Ergebnis
    $("#global-search-0-search-search").keydown(function(e) {
        if (document.searchTimer) clearTimeout(document.searchTimer);
        switch (e.which) {
            case 13: // Enter
                var container = $("div.suggestions:visible");
                if (container.length) {
                    // finde ein markiertes li
                    var li = $("li.active", container).eq(0);
                    if (li.length) {
                        e.preventDefault(); // damit das Formular nicht submittet wird
                        // klicke den ersten link im li
                        $("a", li).eq(0).each(function() {
                            location.href = $(this).attr("href");
                        });
                    }
                }
                break;
            case 40: // Cursor hoch
            case 38: // Cursor runter
                var cursorUp = (e.which == 40);
                var cursorDown = (e.which == 38);
                var container = $("div.suggestions").filter(":visible");
                if (container.length) {
                    // alle lis im container
                    var lis = $("li", container);
                    // finde ein markiertes li
                    var li = $("li.active", container).eq(0);
                    var next;
                    if (li.length) {
                        li.removeClass("active");
                        // index des li in der liste:
                        var index = lis.index(li);
                        if (cursorUp) {
                            if (index < lis.length-1) next = lis.eq(index+1);
                            else next = lis.eq(0);
                        } else {
                            if (index > 0) next = lis.eq(index-1);
                            else next = lis.eq(lis.length-1);
                        }
                    } else {
                        if (cursorUp) next = lis.eq(0);
                        else next = lis.eq(lis.length-1);
                    }
                    next.addClass("active");
                }
        }
    });

    // Keyup-Events: Eingabe im Suchfeld triggert AJAX-Suche,
    // ESC schließt Layer
    $("#global-search-0-search-search").keyup(function(e) {
        switch (e.which) {
            case 27: // ESC
                $("div.suggestions").hide();
                break;
            default:
                var val = $(this).val();
                if (val && (!document.lastSearch || val != document.lastSearch)) {
                    document.lastSearch = val;
                    var div = $("div.suggestions");
                    if (!div.length) {
                        var code = '<div class="suggestions">'
                            + '<div class="suggesttype shop"></div>'
                            + '<div class="suggesttype top"></div>'
                            + '<div class="suggesttype fulltext"></div>'
                            + '<form class="static" method="get" action="suche.php">'
                            + '<button type="button" class="submit">'
                            + 'Weitere Ergebnisse&nbsp;&raquo;</button>'
                            + '</form></div>';
                        div = $(code).appendTo($("#path"));
                        $("button.submit", div).click(function() {
                            $("#global-search-0-search-search").get(0).form.submit();
                        });
                    }
                    div.hide();
                    // alle noch laufenden Requests abbrechen:
                    $(ajaxCalls).each(function(index) {
                        if (this.abort
                            && this.readyState != 0
                            && this.readyState != 4) {
                            // der Call wartet noch auf Antwort, also abbrechen:
                            //console.log("aborting request "+index);
                            this.abort();
                        }
                    });
                    // alle alten Calls wegschmeißen
                    ajaxCalls = [];
                    document.searchTimer = setTimeout(function() {
                        var search = $("#global-search-0-search-search").val();
                        var params = {search: search};
                        var shopContainer = $("div.suggesttype.shop", div);
                        shopContainer.empty();
                        var nutchContainer = $("div.suggesttype.fulltext", div);
                        nutchContainer.empty();
                        ajaxCalls.push($.getJSON(
                            host+"/ajax/suche.php?"+$.param(params)+"&jsonp=?",
                            function(data) {
                                nutchContainer.append($('<h3>'+data.title+'</h3>'));
                                var ul = $('<ul />');
                                $.each(data.results, function(i, item) {
                                    var li = '<li tabindex="'+(i+1)+'">'
                                        +'<a class="searchhit" href="'+item.target+'" title="'+item.title+'">'
                                        +item.name+'</a>'
                                        +'<p class="searchdesc">'+item.description+'</p>'
                                        +'</li>';
                                    ul.append($(li));
                                });
                                nutchContainer.append(ul);
                                if (data) nutchContainer.parent().show();
                            }
                        ));
                        var topContainer = $("div.suggesttype.top", div);
                        topContainer.empty();
                        ajaxCalls.push($.getJSON(
                            host+"/ajax/toptreffer.php?"+$.param(params)+"&jsonp=?",
                            function(data) {
                                topContainer.append($("<h3>"+data.title+"</h3>"));
                                var ul = $('<ul />');
                                $.each(data.results, function(i, item) {
                                    var li = '<li tabindex="'+(i+1)+'">'
                                    +'<a class="searchhit" href="'+item.target+'" title="'+item.title+'">'
                                    +item.name+'</a>'
                                    +'<p class="searchdesc">'+item.description+'</p>'
                                    +'</li>';
                                ul.append($(li));
                                });
                                topContainer.append(ul);
                                if (data) topContainer.parent().show();
                            }
                        ));
                    }, 300);
                }
        }
    });

    // Clicks außerhalb des Suggest-Layers registrieren und den Layer schließen
    $(document).click(function(e) {
        if ($("div.suggestions:visible").length) {
            var clickedElement = e.target;
            var allowedElements = $("div.suggestions")
                                  .find('*')
                                  .add("#global-search-0-search-search");
            if (allowedElements.index(clickedElement) == -1) {
                $("div.suggestions").hide();
            }
        }
    });

    /* chl: Abbrecher-Popup erstmal wieder raus, damit alles andere live kann
    //Funktionalität Abbrecher-Thickbox im Shop
    var href = location.pathname;
    var abbrecherPages = ['/online-shop/warenkorb/', '/online-shop/persoenliche-daten/', '/online-shop/bestellpruefung/'];

    //aktuelle Seite kommt in abbrecherPages vor
    if ($.inArray(href, abbrecherPages) > -1) {
        $('a').click(function() {
            href = $(this).attr('href');

            // this.href kommt nicht in abbrecherPages vor
            if ($.inArray(href, abbrecherPages) == -1) {
                // erweitere this.href um get-Parameter abbruch=1;
                if (href.indexOf("?") != -1) {
                    href = href + "&abbruch=1"
                } else {
                    href = href + "?abbruch=1"
                }
                $(this).attr('href', href);
            }
        });
    } else {
        // in der aktuellen URL ist der GET-Parameter abbruch mit Wert 1
        function getUrlParams() {
            var params = {};
            window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
                params[key] = value;
            });
            return params;
        }
        var params = getUrlParams();
        if (params.abbruch == "1") {
            // Öffne Abbrecher-Thickbox
            tb_show("",host+"/iframes/abbrecher.php?width=836&height=500&TB_iframe=true");
            $("#TB_iframeContent").css({
                'overflow-y' : 'hidden'
            });
        }
    }
    */
    
  /* OneClick Order - Booking-Layer */
  (function($)
  { 
    var bookingLayer = function()
    {
      var pub= {},loc = {},ajax = {},book = {},jqoLink = {}; 
      
      ajax.booking  = '/iframes/o2o-order.php?id=%bid%&KeepThis=true&TB_iframe=true&height=540&width=600';
      ajax.base     = '/ajax/booking-layers/custom.php';
      ajax.auth     = ajax.base + '?jsonp=?&authstate=true';
      ajax.login    = ajax.base + '?width=583&height=385&shopUrl=';
      ajax.canbook  = ajax.base + '?jsonp=?&checkbook=true';
      jqoLink.obj   = false;
      
      loc.param     = window.location.search;
      loc.site      = window.location.pathname;
      loc.JSHost    = host;
      
      /* binding click event of an anchor, which contains the magic parameter */
      pub.bindBooking = function() {
        var jqoBookingLink = $('a[href*="booking=bid"]');   

        jqoBookingLink.bind('click', function() 
        {
            book.openLayer ($(this));    
            return false;
        });
      }; /* fun: bindBookingClick */
      
      
      /* func to check -> if its possible to show the layer? */
      book.canBooking = function () 
      {
        $.getJSON(loc.JSHost + ajax.canbook,
            function(auth) 
            { if (auth == 'true') return true;}
          );  
      }; /* func: canBooking */
      
      /* open layer func - there is the magic */
      book.openLayer = function (jqoObj)
      {
        if (typeof(jqoObj) != "undefined") 
        {
    
          jqoLink.bid    =  jqoObj.attr('href').split('booking=bid')[1];
          jqoLink.title  =  jqoObj.attr('title');
          jqoLink.obj    =  true;
          ajax.login     += escape(jqoObj.attr('href')); 
          ajax.login     += '&targetUrl=' + loc.site + '&curBID=' + jqoLink.bid;
          ajax.booking   =  ajax.booking.replace('%bid%', jqoLink.bid);
                
        } else 
        {
          jqoLink.bid    =  loc.param.split('booking=bid')[1];
          ajax.booking   =  ajax.booking.replace('%bid%', jqoLink.bid);
        }
 
        
        $.getJSON(loc.JSHost + ajax.auth,
            function(auth) 
            {
              if  (auth == 'true') 
              { 
                // if (book.canBooking()) {} lib not working yet.. 
                tb_show("Ihre Bestellung",  loc.JSHost + ajax.booking,   '', 'customBooking');                    
              } else if (jqoLink.obj)     {  tb_show(jqoLink.title ,     loc.JSHost + ajax.login    , '', 'customBooking');  }
            }
          );         
      }; /* func: openLayer */
      
      /* func to check if uri has param to show booking layer */
      pub.checkBooking = function () 
      {
        if  (loc.param.length == 0)                    return false;     
        if  (loc.param.search(/booking=bid/) == -1)    return false;
        book.openLayer ();      
      }; /* func: checkBooking */
      
      return pub;
      
    }();
    
    /* finally func calling */
    bookingLayer.checkBooking();
    bookingLayer.bindBooking();
    
  })(jQuery);

});


function setLogout() {
    logoutTimoutID = setTimeout ( "logout()", intLogout );
}


// logout function
function logout (){
    $("form#global-logout").submit();
}

function interAction (e) {
    clearTimeout ( logoutTimoutID );
    setLogout();
}

jQuery(document).ready(function($) {

  if ($('#telesales').length) {
    // on sites with controls we load the controls
    $('#telesales').telesales({
      container : true
    });
  } 

});

/**
 * scripts only for md.de
 */
//social Plugins function

function appendSocialPlugins() {
  var code = '<div class="social-plugin">'    
    + '<span><iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.mobilcom-debitel.de%2F&amp;send=false&amp;layout=standard&amp;width=84&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=24" scrolling="no" frameborder="0" class="facebook-like" style="border:none; overflow:hidden; height:24px;" allowTransparency="true"></iframe></span>'
    + '<script type="text/javascript" src="https://apis.google.com/js/plusone.js">{lang: "de"}</script>'
    + '<iframe width="100%" scrolling="no" frameborder="0" title="+1" vspace="0" tabindex="-1" class="google_1" style="position: static; left: 0pt; top: 0pt; width: 38px; margin: 0px; border-style: none; height: 24px; visibility: visible; vertical-align: top;" src="https://plusone.google.com/u/0/_/+1/fastbutton?url=http%3A%2F%2Fwww.mobilcom-debitel.de%2F&amp;size=standard&amp;count=false&amp;annotation=&amp;hl=en-US&amp;jsh=r%3Bgc%2F23980661-3686120e#id=I6_1317376706959&amp;parent=http%3A%2F%2Fwww.google.com&amp;rpctoken=572545949&amp;_methods=onPlusOne%2C_ready%2C_close%2C_open%2C_resizeMe" name="I6_1317376706959" marginwidth="0" marginheight="0" id="I6_1317376706959" hspace="0" allowtransparency="true"></iframe>';
    + '</div>';
//$("#head, #header").append(code);
}


/*
(function($) {

  if ("22614" == window.location.port || /.-debitel\.de/.test(window.location.hostname)) {
    
    appendSocialPlugins();
        
  }

})(jQuery);

*/




