/* main.js, Copyright 28.01.10, Weber eBusiness Services GmbH, Jaroslav Herber */
/* Version 1.0.2 */

jQuery.noConflict();

jQuery(document).ready(function()
{
  site_url = "http://www.wutoeschingen.de/";
  
  loadWesJQueryExtensions();
  
  // Accordion plugin
  jQuery('.accordion').accordion({
    autoHeight:false,
    header: 'h3'
    //animated: 'bounceslide'
  });
  
  // If News-Box is present
  if(document.getElementById('news_tab_content')){
    loadHomeNewsAnimatedArrowHandler();
    
    //loadHomeNewsTagHeightHandler();
    // Version 2 is for visiblity:hidden instead of display:none
    loadHomeNewsTagHeightHandler_v2();
    
    if(document.getElementById('news_tabs')) {
      loadHomeNewsHandler();
    }
  }
  loadRootlineHandler();
  loadSmallTeaserHeightHandler();
  loadNavHandler();
  loadSubnavHandler();
  loadUserInteractHandler();
  loadHomeWeatherHandler();
  loadTeaserHoverHandler();
  loadFancyboxHandler();
  loadCatTreeHandler();
  loadCalHandler(site_url);

});

// Handler ------------------------------------------------------------------- 

function loadHomeNewsHandler()
{
  jQuery('.tab_bg:first').show(0);

  jQuery('.news-latest-items h3.headline:first a span.more').hide();
  jQuery('.news-latest-items h3.headline a').click(
    function() {
      if(!jQuery(this).parent().hasClass('selected'))
        jQuery('.news-latest-items h3').filter('h3:not(this)').children('a').children('span.more').fadeIn(300);

        jQuery(this).children('span.more').fadeOut(300);
    }
  );

  var news_tabs = document.getElementById('news_tabs').getElementsByTagName('li');
  
  ClassNames = new Array();
  for(i = 0; i < news_tabs.length; i++) {
    // Remove all links from Tab-Buttons if JS is available
    var link_construction = 'javascript:void(0)';
    news_tabs[i].getElementsByTagName('a')[0].setAttribute('href', link_construction);
    ClassNames[i] = news_tabs[i].className;
  }

  jQuery('#news_tabs li').click(
    function() {
      for(i = 0; i < news_tabs.length; i++){
        if(jQuery('#news_tab_content .tab_content:eq('+i+')').hasClass(jQuery(this).attr('class'))) {
          if(!jQuery(this).hasClass('active')){
            // Abort last animation, if new animation starts
            jQuery('#news_tabs li').stop(true, true);
            jQuery('#news_tab_content .tab_content').stop(true, true);
            
            // Hide the background of non-active Tab-Buttons
            jQuery('.tab_bg').fadeOut(500);
            
            jQuery('#news_tabs li').removeClass('active');
            
            jQuery('#news_tab_content .active').css({
              'position' : 'absolute',
              'z-index' : '1'
            }).fadeOut('slow',
              function() {
                // IE7 Bugfix: fadeOut doesn't set "display: none" to IE7
                jQuery(this).removeClass('active').css('display', 'none');
              }
            );

            jQuery('#news_tab_content .tab_content:eq('+i+')').css({
              'display' : 'none',
              'position' : 'relative',
              'visibility' : 'visible',
              'z-index' : '10'
            }).fadeIn('slow').addClass('active');
            
            jQuery(this).show('fast').addClass('active');
            jQuery('#news_tabs li').filter('li:not(.active)').children('a').children('span');
            jQuery(this).children('a').removeClass('hover').children('span');

            // Background of the active Tab-Button
            jQuery(this).children('.tab_bg').stop(true, true).fadeIn(300);
            
          }
        }
      }
  });
  
  /* change color on tab hover */
  jQuery('#news_tabs ul li').hover(
    function() {
      if(!jQuery(this).hasClass('active')) {
        jQuery(this).stop(true, true).children('a').addClass('hover');
        //jQuery(this).children('a').children('span').stop(true, true).css('color', '#c42e00');
        jQuery(this).children('a').children('span').stop(true, true);
      }
    },
    function(){
      if(!jQuery(this).hasClass('active')) {
        //jQuery(this).children('a').removeClass('hover').children('span').stop(true, true).css('color', '#4c4c4c');
        jQuery(this).children('a').removeClass('hover').children('span').stop(true, true);
      }
    }
  );
  
  /* Hover-effect of the news fields */
  /*
  jQuery('.news-latest-item').hover(
    function(){
      jQuery(this).addClass('hover');
    },
    function(){
      jQuery(this).removeClass('hover');
    }
  );
  */
  /* Link behaviour on click */
  jQuery('.news-latest-item').click(
    function(){
      //window.location.href = jQuery(this).children('.news-latest-item-border').children('h3:first').children('a').attr('href');
    }
  );
}

function loadHomeNewsAnimatedArrowHandler()
{
  // Slide the arrow to position 1
  jQuery('#news_tabs li:eq(0)').click(
    function(){
      if(!jQuery(this).hasClass('active')){
        jQuery('.tab_arrow').stop(true, true).animate({left: "6.25em", color: "blue"}, {duration: 600, easing: 'easeOutBack'});
      }
    }
  );
  
  // Slide the arrow to position 2
  jQuery('#news_tabs li:eq(1)').click(
    function(){
      if(!jQuery(this).hasClass('active')){
        jQuery('.tab_arrow').stop(true, true).animate({left: "20.9em"}, {duration: 600, easing: 'easeOutBack'});
      }
    }
  );
  
  // Slide the arrow to position 3
  jQuery('#news_tabs li:eq(2)').click(
    function(){
      if(!jQuery(this).hasClass('active')){
        jQuery('.tab_arrow').stop(true, true).animate({left: "33.55em"}, {duration: 600, easing: 'easeOutBack'});
      }
    }
  );
}

function loadHomeNewsTagHeightHandler()
{  
  jQuery('.tx-calendar-pi1 .news-latest-item:first').addClass('first');
  /* Set start-height of the news-content div */
  var highest_news_tab_height = jQuery('#news_tab_content .tab_content:first .news-latest-items').height();
  
      // Show all boxes to calculate the highest box
        jQuery('#news_tab_content .tab_content').filter(':not(.active)').css('display', 'block');
        
        for(var i = 0; i < jQuery('#news_tab_content .tab_content').length; i++) {
          if(highest_news_tab_height < jQuery('#news_tab_content .tab_content:eq('+i+') .news-latest-items').height())
            var highest_news_tab_height = jQuery('#news_tab_content .tab_content:eq('+i+') .news-latest-items').height();
        }
        
      // hide all not visible boxes
        jQuery('#news_tab_content .tab_content').filter(':not(.active)').css('display', 'none');

  // IE6 uses high instead of min-height
  if(window.navigator.userAgent.indexOf("MSIE 6") > -1){
    jQuery('#news_tab_content .tab_content .news-latest-items').css('height', highest_news_tab_height);
    
    /* If other news-content boxes are higher, set new height */
    jQuery('#news_tabs li').click(
      function() {
        if(highest_news_tab_height < jQuery('#news_tab_content .tab_content:visible .news-latest-items').height()) {
          highest_news_tab_height = jQuery('#news_tab_content .tab_content:visible .news-latest-items').height();
          jQuery('#news_tab_content .tab_content .news-latest-items').css('height', highest_news_tab_height);
        }
    });
  } else {
    jQuery('#news_tab_content .tab_content .news-latest-items').css('min-height', highest_news_tab_height);
    
    /* If other news-content boxes are higher, set new height */
    jQuery('#news_tabs li').click(
      function() {
        if(highest_news_tab_height < jQuery('#news_tab_content .tab_content:visible .news-latest-items').height()) {
          highest_news_tab_height = jQuery('#news_tab_content .tab_content:visible .news-latest-items').height();
          jQuery('#news_tab_content .tab_content .news-latest-items').css('min-height', highest_news_tab_height);
        }
    });
  }
}

function loadHomeNewsTagHeightHandler_v2()
{
  jQuery('.tx-calendar-pi1 .news-latest-item:first').addClass('first');
  /* Set start-height of the news-content div */
  var highest_news_tab_height = jQuery('#news_tab_content .tab_content:first').height();
        
        for(var i = 0; i < jQuery('#news_tab_content .tab_content').length; i++) {
          if(highest_news_tab_height < jQuery('#news_tab_content .tab_content:eq('+i+')').height())
            var highest_news_tab_height = jQuery('#news_tab_content .tab_content:eq('+i+')').height();
        }

  // IE6 uses high instead of min-height
  if(window.navigator.userAgent.indexOf("MSIE 6") > -1){
    jQuery('#news_tab_content').css('height', highest_news_tab_height);

    jQuery('#news_tabs li').click(
      setNewHeight('height', highest_news_tab_height)
    );
  } else {
    jQuery('#news_tab_content').css('min-height', highest_news_tab_height);
    
    /* If other news-content boxes are higher, set new height */
    jQuery('#news_tabs li').click(
      setNewHeight('min-height', highest_news_tab_height)
    );
  }
}

function loadRootlineHandler() {
  jQuery('#rootline>span').filter('span:not(.item_active)').hover(
    function() {
      if(!jQuery(this).hasClass('last_link'))
        jQuery(this).addClass('hover').prev().prev('span.item').addClass('prev_hover');
      else
        jQuery(this).addClass('last_link_hover').prev().prev('span.item').addClass('prev_hover');
    },
    function() {
      jQuery(this).removeClass('hover').removeClass('last_link_hover').prev().prev('.item').removeClass('prev_hover');
    }
  );
}

function loadSmallTeaserHeightHandler() {
  var teaser_number = jQuery('.small_teaser_container').length;
  var teaser_height = 209;
  
  setTeaserHeight(teaser_height, teaser_number);
  
  jQuery('html').click(
    function() {
      setTeaserHeight(teaser_height, teaser_number);
    }
  );
}

function loadHomeWeatherHandler()
{
  var jahr, monat, tag, stunden, minuten;
  var AktuellesDatum = new Date();
  jahr = AktuellesDatum.getYear()-2000;
  monat = AktuellesDatum.getMonth ()+1;
  tag = AktuellesDatum.getDate();
  stunden = AktuellesDatum.getHours();
  minuten = AktuellesDatum.getMinutes();

  if(jahr < 10){
    if(jahr < 0) {jahr += 1900;}
  } 
  jQuery('.tx-wesweatheralert-info #date').text(tag+"."+monat+"."+jahr+", ");
  
  jQuery('.tx-wesweatheralert-info .details_button').click(
    function(){
      if(window.navigator.userAgent.indexOf("MSIE 6") > -1) {
        jQuery('.tx-wesweatheralert-info .extended').show();
      } else {
        jQuery('.tx-wesweatheralert-info .extended').fadeIn(800,
          function() {
            jQuery(this).css('filter', 'alpha(opacity=100)');
          }
        );
      }
      jQuery('.tx-wesweatheralert-info .weather_info').addClass('extended_weather');
    }
  );

  jQuery('.tx-wesweatheralert-info .close').click(
    function(){
      jQuery('.tx-wesweatheralert-info .extended').stop(true, true).hide();
      jQuery('.tx-wesweatheralert-info .weather_info').removeClass('extended_weather');
    }
  );
  
  var weatherHeight = jQuery('.tx-wesweatheralert-info').height();
  jQuery('.tx-wesweatheralert-info').css('height', weatherHeight);

}


function loadNavHandler()
{
  jQuery('#mainnav li.level1').hover(
    function(){
      jQuery(this).addClass('hover');
    },
    function(){
      jQuery(this).removeClass('hover');
    }
  );
}

function loadSubnavHandler()
{
  jQuery('#subnav li.hasSub').filter('li:not(.level2)').filter('li:not(.hasSub_active1)').hover(
    function() {
      jQuery(this).addClass('hover');
      if(jQuery(this).hasClass('last'))
        jQuery(this).addClass('last_hover');
    },
    function() {
      jQuery(this).removeClass('hover');
      if(jQuery(this).hasClass('last'))
        jQuery(this).removeClass('last_hover');
    }
  );
  
  /* Same as hover, but with Tab-navigation support */
  jQuery('#subnav a.level1').focus(
    function() {
      jQuery('li.hasSub').removeClass('hover').removeClass('last_hover');
    }
  );
  
  jQuery('#subnav li.hasSub').filter('li:not(.level2)').children('a').focus(
    function() {
      jQuery(this).parent().addClass('hover');
      if(jQuery(this).parent().hasClass('last'))
        jQuery(this).parent().addClass('last_hover');
    }
  );
  
  jQuery('#subnav li.hasSub a.level2:last').blur(
    function() {
        
      if(jQuery(this).parent().hasClass('last'))
        jQuery(this).parent().removeClass('last_hover');
    }
  );
}

function openUserInteractBox(justOpen)
{  
  var linked_opener_text = jQuery('#user_interact_opener a span').html();

  if(justOpen == true && jQuery('#user_interact_opener a').hasClass('opened')) {
    jQuery('#top').scrollTo(600);
    return;
  } else {
    // Show login-box
    interactBoxStatusChanger(linked_opener_text);
  }
}

function loadCalHandler(site_url)
{
  jQuery('.event_list_item .event_title, .event_list_item .event_text, .event_list_item .event_date_container').hover(
    function() {
      jQuery(this).parent().addClass('hover');
    },
    function() {
      jQuery(this).parent().removeClass('hover');
    }
  );

/*
  jQuery('.event_location a').hover(
    function() {
      jQuery('.event_list_item').removeClass('hover');
    },
    function() {
      jQuery('.event_list_item').addClass('hover');
    }
  );
  
  jQuery('.event_category a').hover(
    function() {
      jQuery('.event_list_item').removeClass('hover');
    },
    function() {
      jQuery('.event_list_item').addClass('hover');
    }
  );
  */

  jQuery('.event_list_item').click(
    function() {
      redirect_url = jQuery(this).children('.event_title').children('a').attr('href');
      jQuery(window.location).attr('href', site_url + redirect_url);
    }
  );
}


function loadUserInteractHandler()
{
  var linked_opener_text = jQuery('#user_interact_opener a span').html();
  
  // checks cookies on reload and call last status of the interact area (openned/closed)
  interactCookieStatus(linked_opener_text);

  // Show login-box
  jQuery('#user_interact_opener a.icon').click(
    function() {
       interactBoxStatusChanger(linked_opener_text);
    }
  );
  
  jQuery('.ui_open').click(
    function() {
      interactBoxStatusChanger(linked_opener_text);
      /* deactivate links with the class ui_open */
      if(jQuery(this).attr('href')) {
        return false;
      }
    }
  );
 
  // Close User Interact, if click on content
  /*
  jQuery("html").click(function(event) {
    var target = jQuery(event.target);
    if (jQuery('#user_interact').is(':visible') && !target.is("#user_interact_container *") && !target.is('#user_interact_opener a') && !target.is('#user_interact_opener a span') && !target.is('.teaser')) {
      jQuery('#user_interact').slideUp(400);
      jQuery('#user_interact_opener a.icon').removeClass('opened').children('span').html(linked_opener_text);
    }
  });
  */
}

function loadTeaserHoverHandler()
{
  jQuery('#content .teaser').hover(
    function() {
      jQuery(this).addClass('teaser_hover');
    },
    function() {
      jQuery(this).removeClass('teaser_hover');
    }
  );
  
  // Link the whole Box
  jQuery('#content .teaser .text').click(
    function() {
      window.location.href = jQuery(this).parent().children('.title').children('a').attr('href');
    }
  )
  //jQuery('#content .teaser .text').children('p').children('a').attr('href', 'javascript:void(0)');
 
}

// Set min-width to the footer-images in ie6
function ie6_footer_width() {
  if(window.navigator.userAgent.indexOf("MSIE 6") > -1){
    var x;
    x = document.body.clientWidth;
    if(x <= 970)
      jQuery('#bottom_image_layers').css('width', '970px');
    else
      jQuery('#bottom_image_layers').css('width', '100%');
  }
}

function loadFancyboxHandler() {
 
  // copy the rel-attr from <img> into <a>, because impossible in TypoScript
  jQuery('img[rel=image]').parent().parent('a').attr('rel', 'image');
  
  jQuery('a[rel=image]').fancybox({
    'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack',
    'title'         : this.title,
    'titlePosition' : 'inside',
    // inside titlePosition
    'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
      // empty strings, if no title-attr
      if(title == undefined) {
        title = "";
      }
      if(currentArray.length < 2) {
        // no wrap, if no title
        if(title != "") {
          return title;
        }
      } else {
        // wrap Image numbers, if title exists
        return 'Bild ' + (currentIndex + 1) + ' / ' + currentArray.length + ': ' + title;
      }
    }
  });
  
  // FE Editting iframe in fancybox
  jQuery('.edit_entry a.fe_admin').fancybox({
    'width'         : 770,
    'height'        : '75%', 
    'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack',
		'autoScale'     : true, 
    'type'          : 'iframe' 
  });
  
  // 
  jQuery('a.fancy_iframe').fancybox({
    'width'         : 956,
    'height'        : 590, 
    'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack',
		'autoScale'     : true,
		'titleShow'     : false,
    'type'          : 'iframe'
  });
  
}

function loadCatTreeHandler() {
  
  var loader = '<img class="loader_image" src="/fileadmin/images/default/loader.gif" alt="loader" />';
  jQuery('.category_tree_item li a').addClass('loader').append(loader);
  
  // add class="hasSub" on the cat-link if there are sub-categories
  jQuery('.category_tree_item_sub_container').prev().addClass('hasSub');
  
  // keep the second level openned on reload
  jQuery('.category_tree_item_sub .cur').parent().show().parent().parent().parent().addClass('active_sub');

  jQuery('.category_tree_item li a').click(
    function() {
      if(jQuery(this).next().hasClass('category_tree_item_sub_container')) {
        // if already visible, then hide it
        if(jQuery(this).next().is(':visible')) {
          jQuery('.category_tree_item_sub_container').hide().parent('li').removeClass('active_tree_sub');
          
          return false;
        }
        // hide other submenues
        jQuery('.category_tree_item_sub_container').hide().parent('li').removeClass('active_tree_sub');
        jQuery(this).next().show();
        jQuery(this).parent('li').addClass('active_tree_sub');
        return false;
      } else {
        jQuery('.loader_image').fadeOut('fast');
        jQuery(this).children('.loader_image').fadeIn('fast');
        
        // remove loader-image, when finished loading
        jQuery(window).unload(
          function() {
            jQuery('.loader_image').fadeOut('fast');
          }
        );  
      }
    }
  );
  jQuery("html").click(function(event) {
    var target = jQuery(event.target);
    if (!target.is('.category_tree_item') && !target.is('.category_tree_item *')) {
      jQuery('.category_tree_item_sub_container').hide().parent('li').removeClass('active_tree_sub');
    }
  });
  
}

window.onresize = ie6_footer_width;

// Helper Functions ------------------------------------------------------------

function setNewHeight(heightType, highest_news_tab_height)
{
  if(highest_news_tab_height < jQuery('#news_tab_content').height()) {
    highest_news_tab_height = jQuery('#news_tab_content').height();
    jQuery('#news_tab_content').css(heightType, highest_news_tab_height);
  }
}

function setTeaserHeight(teaser_height, teaser_number) {
  if(teaser_number >= 1) {
    for(i = 0; i < teaser_number; i++) {
      if(teaser_height < jQuery('.small_teaser_container:eq('+i+')').height()) {
        teaser_height = jQuery('.small_teaser_container:eq('+i+')').height();
      }
      if(window.navigator.userAgent.indexOf("MSIE 6") > -1){
        jQuery('.small_teaser').css('height', teaser_height);
      } else {
        jQuery('.small_teaser').css('min-height', teaser_height);
      }
    }
  }
}

function interactBoxStatusChanger(linked_opener_text){
  if(jQuery('body').hasClass('fe_login')) {
    if(jQuery('#user_interact_body').is(':hidden')) {
      jQuery.cookie("wes_interact", 1, { path: '/'});
      jQuery('#user_interact_body').slideDown(400);
      jQuery('#top').scrollTo(600);
      jQuery('#user_interact_opener a.icon').addClass('opened').children('span').html('Schliessen');
    } else {
      jQuery.cookie("wes_interact", 0, { path: '/'});
      jQuery('#user_interact_body').slideUp(400);
      jQuery('#user_interact_opener a.icon').removeClass('opened').children('span').html(linked_opener_text);
    }
  } else {
    if(jQuery('#user_interact').is(':hidden')) {
      jQuery.cookie("wes_interact", 1, { path: '/'});
      jQuery('#user_interact').slideDown(400);
      jQuery('#top').scrollTo(600);
      jQuery('#user_interact_opener a.icon').addClass('opened').children('span').html('Schliessen');
    } else {
      jQuery.cookie("wes_interact", 0, { path: '/'});
      jQuery('#user_interact').slideUp(400);
      jQuery('#user_interact_opener a.icon').removeClass('opened').children('span').html(linked_opener_text);
    }
  }
}

function interactCookieStatus(linked_opener_text){
  if(jQuery('body').hasClass('fe_login')) {
    if(jQuery.cookie("wes_interact") == 1) {
      jQuery('#user_interact_body').show();
      jQuery('#user_interact_opener a.icon').addClass('opened').children('span').html('Schliessen');
    } else {
      jQuery('#user_interact_body').hide();
      jQuery('#user_interact_opener a.icon').removeClass('opened').children('span').html(linked_opener_text);
    }
  } else {
    if(jQuery.cookie("wes_interact") == 1) {
      jQuery('#user_interact').show();
      jQuery('#user_interact_opener a.icon').addClass('opened').children('span').html('Schliessen');
    } else {
      jQuery('#user_interact').hide();
      jQuery('#user_interact_opener a.icon').removeClass('opened').children('span').html(linked_opener_text);
    }
  }
}

// Scroll to window position extension
function loadWesJQueryExtensions() {
  jQuery.fn.extend({
    scrollTo : function(speed, easing) {
      return this.each(function() {
        var targetOffset = jQuery(this).offset().top;
        jQuery('html,body').animate({scrollTop: targetOffset}, speed, easing);
      });
    }
  });
}


