/* 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.rosenfeld.de/";
  
  loadWesJQueryExtensions();

  loadFancyboxHandler();
  //loadCatTreeHandler();
  loadCalHandler(site_url);
  
  loadHomeWeatherHandler();

  loadLiveSearch();

});

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

function loadHomeWeatherHandler() {
  jQuery('.tx-wesweatheralert-pi2').parent().css('z-index', '100');
  
  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 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'         : 958,
    'height'        : 590, 
    'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack',
		'autoScale'     : true,
		'titleShow'     : false,
    'type'          : 'iframe'
  });
  
}

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_list_item').click(
    function() {
      redirect_url = jQuery(this).children('.event_title').children('a').attr('href');
      
      //alert(redirect_url);
      jQuery(window.location).attr('href', site_url + redirect_url);
      
    }
  );
}

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');
    }
  });
  
}

function loadLiveSearch() {
  jQuery('#jq-primarySearchForm').show();
  if( jQuery('#jq-primarySearch').is(':visible') ) {
    jQuery('#jq-primarySearch').liveUpdate('#content .table tbody').focus();
  }
}

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

// 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);
      });
    }
  });
  
  // Needed for search
  jQuery.fn.liveUpdate = function(list){
  	list = jQuery(list);
  
  	if ( list.length ) {
  		var rows = list.children('tr'),
  			cache = rows.map(function(){
  				return jQuery(this).text().toLowerCase();
  			});
  		
  		this
  			.keyup(filter).keyup();
  	}
  
    function callback() {
      var moreLists = list.slice(1);
  
      callback = (moreLists.length) ? function() {
        moreLists.prev('h2').toggle(!!moreLists.children(':visible').length);
      } : function() {};
      
    };
  		
  	function filter(){
  		var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
  		
  		if ( !term ) {
  			rows.show().addClass('keynav withoutfocus');
  		} else {
  			rows.hide().removeClass('keynav withfocus withoutfocus');
  
  			cache.each(function(i){
  				if ( this.indexOf( term ) > -1 ) {
  					jQuery(rows[i]).show().addClass('keynav withoutfocus');
  				}
  			});
  		}
      
      // Added support for our facilitiy-tables, Jaroslav Herber
      jQuery('#content .table tbody').each(
        function() {
          if( jQuery(this).children('tr:visible').length > 0 ) {
            jQuery(this).parent().show().next().show().next('br').css('position', 'static').css('display', 'inline').next('br').css('position', 'static').css('display', 'inline');
          } else {
            jQuery(this).parent().hide().next().hide().next('br').css('position', 'absolute').css('display', 'none').next('br').css('position', 'absolute').css('display', 'none');
          }
        }
      );
  		
  		if( jQuery('#content').find('.table:visible').length == 0 ) {
        if( !jQuery('p.empty_hint').is(':visible') ) {
          jQuery('#content').append('<p class="empty_hint"><strong>Ihre Live-Suche in der Unternehmensliste ergab keine Treffer. Bitte geben Sie einen anderen Begriff ein.</strong></p>');
        }
      } else {
        jQuery('p.empty_hint').remove();
      }
  		
  	  callback();
  	}
  	return this;
  };

}

function openPic(url,winName,winParams)	{
	var theWindow = window.open(url,winName,winParams);
	if (theWindow) {theWindow.focus();}
}

