jQuery(document).ready(function($) {
  
  /* #################################
  ###### General Browser Detaction ###
  ################################# */

  if ( BrowserDetect.browser == 'Explorer' && BrowserDetect.version <= 7 ) {
    $('#contact_overlay').html('<center><h2 class="headline26 browser_detaction">Sorry!</h2>You are using an outdated browser (MS Internet Explorer ' + BrowserDetect.version + '). For a better experience using this site, please upgrade to a modern web browser.<br /><br />Sie verwenden einen veralteten Browser (MS Internet Explorer ' + BrowserDetect.version + '). Um diese Website vollumfänglich nutzen zu können, updaten Sie bitte ihren Browser auf eine aktuelle Version.<br /><br />Internet Explorer 8 oder 9, Firefox, Safari oder Google Chrome.<br /><br /> <a href="http://windows.microsoft.com/de-DE/internet-explorer/downloads/ie" target="_blank"><img class="browser" src="/wp-content/themes/bbm/images/browser/ie9.jpg" border="0" /></a> <a href="http://www.mozilla.com/" target="_blank"><img class="browser" src="/wp-content/themes/bbm/images/browser/firefox.jpg" border="0" /></a> <a href="http://www.apple.com/safari/download/" target="_blank"><img class="browser" src="/wp-content/themes/bbm/images/browser/safari.jpg" height="40" border="0" /></a> <a href="http://www.google.com/chrome/" target="_blank"><img class="browser" src="/wp-content/themes/bbm/images/browser/chrome.jpg" border="0" /></a></center>');
    $('#dark_overlay').show();
    $('#contact_overlay').toggle();
  }
  // if ( !Modernizr.textshadow ) {
  //   $("h1").textShadow();
  //   $("h1.headline100").textShadow({
  //     color:   "#000000",
  //     xoffset: "3px",
  //     yoffset: "3px",
  //     radius:  "5px"
  //   });
  // }
  /* ###########################################
  ###### Helper functions and variables ########
  ########################################### */
  
  context_is = function(context) {
    if ( $('body.bbm_' + context).length != 0 ) return true;
  }
  
  var theme_path = '/wp-content/themes/bbm/';
  if ( window.location.host == 'manuel-mb.local' ) {
    theme_path = 'http://manuel-mb.local/~manuel/wordpress' + theme_path;
  }
  
  var bbm_color = '#464646';
  if ( Modernizr.rgba ) { bbm_color = 'rgba(170, 170, 170, 0.4)'; }
  
  /* #################################
  ###### DEV Overlay #################
  ################################# */
  
    // img = $('body').attr('class');
    // $('#bbm_overlay').css('background', 'transparent url(' + theme_path + 'images/screens/' + img + '.jpg) no-repeat center top');
    // $('#bbm_overlay').css({'-moz-opacity': '0.65', 'opacity': '0.65', 'z-index': '100', 'width': '100%', 'height': '2000px', 'margin': '0 auto', 'position': 'absolute', 'top': '0px'});
    // 
    // $('#bbm_overlay').css('display', 'none');
    // 
    // $('#bbm_overlay_toggle').css({'position': 'fixed', 'top': '40px', 'width': '40px', 'height': '40px', 'background-color': 'red', 'z-index': '101'});
    // 
    // $('#bbm_overlay_toggle').click(function() {
    //   $('#bbm_overlay').toggle();
    // });


  
  
  /* #################################
  ###### General Layout Fixes ########
  ################################# */
  
  // remove the right border in the right manue
  $('.menu > ul > li:last-child').css('border-right', 'medium none');
  $('.menu > ul > li:first-child').css('border-left', 'medium none');
  
  // add the arrow in the service navi and style it
  $('.menu_left > ul > li:last-child > a, .menu_right > ul > li:first-child > a').append("<img class='arrow_navi' src='" + theme_path + "images/arrow_navi.png' />");
  
  $('.arrow_navi').css({'padding': '2px 0 2px 5px'});
  
  $('#footer .teaser.last .textwidget').css({'border-bottom': 'medium none'});
    
  /* ##################################################
  ###### General Equipment Navigation Behavior ########
  ################################################## */
  
  if ( context_is('equipment') ) {
  
  // add the right hover behavior to the equipment list
  
  $("#sub-navigation").treeview({
  	animated: "fast",
  	collapsed: true,
  	unique: true,
  	persist: "location"
  });
  
  function gup( name )
  {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( location.href );
    if( results == null )
      return "";
    else
      return results[1];
  }
  
  var bbm_tree = gup( 'tree' );
  var bbm_search = gup( 'search' );
  
  // if ( bbm_search ) {
  //   $("#sub-navigation").treeview({collapsed: false});
  //   console.log('collapsed: false');
  // }
  // 
  // if ( bbm_cat ) {
  //   $('#sub-navigation').accordion('option', "active", $('h3.category-' + bbm_cat));
  // }
  // 
  //   
  // 
  // if ( bbm_sub_cat ) {
  //   $('#sub-category-' + bbm_sub_cat).addClass('active');
  // }
  // 
  // if ( bbm_grand_cat ) {
  //   $('#grand-category-' + bbm_grand_cat).addClass('active');
  // }
  // 
  
  // Equipment Kategorie click Behavior
  $('.treeview span').click(function() {
    $('#load_more_items').show();
    
    if ( $(this).attr('data-target') && !$(this).parent().hasClass('active') ) {
      $.get($(this).attr('data-target') + '&action=fs_framework_get_equipment', function(data) {
        if ( data != '' ) {
          $('#equipment_content').html(data);
        }
      });
      history.pushState(null, document.title, $(this).attr('data-target'));
    }
  
      
    if ( $(this).parent().is('li') ) {
      if ( !$(this).parent().hasClass('active') ) {
        $(this).parent().addClass('active');
      }
      
      $(this).parent().parent().find('li').each(function(index, el) {
        $(this).removeClass('active');
        $(this).find('> span').css({'border-top': '1px solid ' + bbm_color});
        $(this).next().find('> span').css({'border-top': '1px solid ' + bbm_color});
        $(this).find('> span').css({'background': 'none'});                  
      });
  
      set_current_style();
      
    }
    
    if ( $('#equipment_content .item').length < 20 ) {
      $('#load_more_items').hide();
    }
    
    return false;
    
  });
  
  $(window).bind('popstate', function() {
    $('#load_more_items').show();
    $.get(location.href + '&action=fs_framework_get_equipment', function(data) {
      $('#equipment_content').html(data); 
    });
  });
  
  
  $('#sub-navigation li span').hover(
    function() {
      $(this).css({'border-top': '1px solid #fff'}); 
      $(this).addClass('hover');
      
      $(this).parent().next().find('> span').css({'border-top': '1px solid #fff'});
      if ( !$(this).hasClass('first-level') ) {
        $(this).css({'background': 'transparent url(' + theme_path + '/images/arrow_right.png) no-repeat 10px 10px'});
      }
      
      set_current_style();
    },
    function() {
      $(this).css({'border-top': '1px solid ' + bbm_color}); 
      $(this).removeClass('hover');
      
      $(this).parent().next().find('> span').css({'border-top': '1px solid ' + bbm_color});
      $(this).css({'background': 'none'});
      
      set_current_style();
    }
  );
  
  set_current_style = function() {
    $('.collapsable').find('> span').css({'border-top': '1px solid #fff'});
    $('.collapsable > ul > li:first-child > span').css({'border-top': '1px solid #fff'});
    
    $('.treeview li.expandable > span.second-level').css({'background': 'transparent url(' + theme_path + '/images/arrow_bottom.png) no-repeat 8px 12px'});
    
    $('.treeview li.collapsable > span.second-level').css({'background': 'transparent url(' + theme_path + '/images/arrow_right.png) no-repeat 10px 10px'});
    
    $('.treeview li.active > span.second-level').css({'background': 'transparent url(' + theme_path + '/images/arrow_right.png) no-repeat 10px 10px'});
    
    $('.treeview li.active > span.second-level').css({'border-top': '1px solid #fff'});
    $('.treeview li.active').next().find('> span').css({'border-top': '1px solid #fff'});      
  }
  set_current_style();
  
  // 
  //   set_current_style();
  // });
  // 
  // $('.treeview li').hover(
  //   function() {
  //       $(this).find('span').css({'border-top': '1px solid #fff', 'color': '#fff'});
  //       $(this).next().find('span.second-level').css({'border-top': '1px solid #fff'});
  //   },
  //   function() {
  //     remove_current_style(this);
  //     set_current_style();
  //   }
  // );
  // 
  // 
  // 
  // // remove the current style
  // remove_current_style = function(el) {
  //   $(el).find('span.second-level').css({'border-top': '1px solid ' + bbm_color, 'color': '#aaa'});
  //   $(el).next().find('span.second-level').css({'border-top': '1px solid ' + bbm_color});
  // }
    
  }
  
  /* #######################################
  ###### General Equipment Behavior ########
  ####################################### */
  
  if ( context_is('equipment') ) {
  
    // slide the description
    $('#content .item .description').live('click', function() {
      var item = $(this).parent();
    
      if ( item.find('.image_wrapper').length == 0 ) {
        item.find('.info').css({'height': '50px'});
      }
      
      var image = item.find('.info > .image_wrapper > img');
        
      if ( image.attr('src') == '' ) {      
        image.attr('src', image.attr('data-load-url'));
      }
      
      if ( item.find('.info').is(':hidden') ) {
        item.find('.info').slideDown('fast');
        item.animate({
          'padding-bottom': '30px',
          'border-top': '1px solid #fff',
          'border-bottom': '1px solid #fff'
          }, 'fast');
      } else {
        item.find('.info').slideUp('fast');
        item.animate({
          'padding-bottom': '0',
          'border': ''
          }, 'fast');
      }
    });
    
    function load_more()
    {
      var finished = false;
      var offset = $('#equipment_content .item').length;
      //$('div#last_msg_loader').html('<img src="bigLoader.gif">');
        if ( window.location.search ) {
          var url_parts_connector = "&";
        } else {
          var url_parts_connector = "?";
        }
        $.get(window.location.href + url_parts_connector + 'action=fs_framework_get_equipment&offset=' + offset,
          function(data){            
            if (data != "") {
              $(data).insertAfter('#equipment_content .item:last-child');
            } else {
              $('#load_more_items').hide();
            }
            if ( offset > $('#equipment_content .item').length ) {
              finished = true;
            }
          }
            //$('div#last_msg_loader').empty();
        );

      return finished;
    };

    $('#load_more_items').click(function(){
      var reload = true;

      if ( reload == false ) {
        return;
      } else {
        reload = false;
        reload = load_more();
      }
    });
    
    if ( $('#equipment_content .item').length < 20 ) {
      $('#load_more_items').hide();
    }
    
  }
  
  
  /* ###########################################
  ###### General Shopping Cart Behavior ########
  ########################################### */
  
  var fs_max_items = 9;
  var fs_carousel_first = 1;
  var fs_carousel_last = 9;
  
  $('#shopping_cart .controlls > .button').live('click', function() {
    var count = $('#shopping_cart .items .item').length;
    
    if ( fs_carousel_last < count ) {
      if ( $(this).hasClass('next') ) {        
        var left = $('#shopping_cart .items').css('left');
        fs_carousel_first = fs_carousel_first + 1;
        fs_carousel_last = fs_carousel_last + 1;
        $('#shopping_cart .items').animate({
          'left': parseInt(left) - 81 + 'px'
        }, 'fast');
      }
    }

    if ( fs_carousel_first > 1 ) {
      if ( $(this).hasClass('back') ) {
        var left = $('#shopping_cart .items').css('left');
        fs_carousel_first = fs_carousel_first - 1;
        fs_carousel_last = fs_carousel_last - 1;
        $('#shopping_cart .items').animate({
          'left': parseInt(left) + 81 + 'px'
        }, 'fast');
      }
    }
    
  });
  
  // show the shopping cart item info
  $('#shopping_cart .wrapper .items .item').live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') {
      position = $(this).offset();
      $(this).find('.info').css({'left': position.left + 10, 'bottom': '65px'});
      $(this).find('.info').show();
    } else {
      $(this).find('.info').hide();
    }
  });
  
  
  /* ###################################
  ###### General Setup Behavior ########
  ################################### */
  
  if ( context_is('setup') ) {
      
    $('#setup_print_button').click(function() {
      window.print();
      return false;
    });
        
  }
  
  
  
  /* ######################################
  ###### General Trucking Behavior ########
  ###################################### */
  
  if ( context_is('trucking') ) {    
  
    $('#content .item .image_wrapper').append('<div class="loupe"></div>');
    $('#content .item .image_wrapper').hover(
      function(){
        $(this).find('.loupe').show();
      },
      function(){
        $(this).find('.loupe').hide();
      }
    );
  
  }
  
  
  /* ##################################
  ###### General Jobs Behavior ########
  ################################## */
  
  if ( context_is('jobs') ) {    
  
    $('#content .item').hover(
      function() {
        $(this).css({'border-top': '1px solid #fff'}); 
        $(this).next().css({'border-top': '1px solid #fff'}); 
        
        if ( $(this).is(':last-child') ) {
          $(this).css({'border-bottom': '1px solid #fff'}); 
        }
      },
      function() {
        $(this).css({'border-top': '1px solid ' + bbm_color}); 
        $(this).next().css({'border-top': '1px solid ' + bbm_color});
        
        if ( $(this).is(':last-child') ) {
          $(this).css({'border-bottom': '1px solid ' + bbm_color}); 
        }
      }
    );
    
  }
  
  /* #############################
  ###### General Behavior ########
  ############################# */
  
  // Select all links that contains lightbox in the attribute rel
  $('a.lightbox, .gallery a').lightBox({
    imageLoading: theme_path + 'images/lightbox/loading.gif',
  	imageBtnClose: theme_path + 'images/lightbox/close.gif',
  	imageBtnPrev: theme_path + 'images/lightbox/prev.gif',
  	imageBtnNext: theme_path + 'images/lightbox/next.gif',
  	imageBlank: theme_path + 'images/lightbox/blank.gif',
    fixedNavigation: true
  });
  
  $('.startlightbox').click(function() {
    $(this).parent().find('a.lightbox').first().trigger('click');    
  });
  
  $('#contact_overlay #contact_form #close').click(function() {
    $('#dark_overlay').fadeOut('slow');
    $('#contact_overlay').fadeOut('fast');
  });

  $('[placeholder]').focus(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
      input.val('');
      input.removeClass('placeholder');
    }
  }).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
      input.addClass('placeholder');
      input.val(input.attr('placeholder'));
    }
  }).blur().parents('form').submit(function() {
    $(this).find('[placeholder]').each(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
      }
    })
  });
  
});
