/* ON LOAD PROCESSING */
$(window).load(function(){

  if($('#ad-blocks .items *').length > 0) { // if there are ad blocks, process them and activate the slider
	processAdSlider();
  }
  
  if($('#big-cycler').length > 0) { // if there are images in the big slider (in content) activate the slider
	processBigCycler();
  }
  
  if($('.special-offer .so-right').length > 0) { // if there are elements in the special offer slider, process them and activate the slider
	processSpecialOfferCycler();
  }
  
  if($('.icontainer').length > 0) { $('.product-title').css("margin-top", "65px"); processIconBox(); } // if there is an iconbox in the page, process it and activate it
  
  add_mouseover_to_product_links(); // add MO effects to PDF, Mail and Print in product detail display
  
  create_contact_handles(); // process the contact handles for the quick contact form
  
  $(window).scroll(function() { adjustContactHandle()}); // adjust handle position on page scroll
  
  processBottomSlider(); // process the bottom slider if there are elements
  
  setTimeout("adaptMainContentHeight()", 1000); // adapt content height so everything fits in nicely

  removeAnfrage(); // remove the deprecated anfrage button from the old templates
  
  activateFooterContact(); // activate the footer contact form and ready it for processing the data to fileadmin/templates2011/php/process_footer_contact.php
  
  normalizeSidebarImages(); // process images in the sidebar so they are not treated equally to the 90px sidebar images
  
  processLogo();
  
  initMainMenu();

  $('.mail-icon').hover(
    function(){
      if($('.contact-folder-handle').height() == "270") {
        $(this).attr("src", "/fileadmin/templates2011/images/mailiconclose.jpg");
      }
    },
    function(){
      $(this).attr("src", "/fileadmin/templates2011/images/mailicon.png");
    }
  );
  
  //setTimeout("browsercompat()", 1); // activate browser compatibility fixes after 1 sec.
  browsercompat();
  adjustContactHandle();
});


/* FUNCTIONS */
function prod_hide_empty_links() {
  $('.product-links a').each(
    function() { 
      if($(this).attr('href') == "") { 
        $(this).css('visibility','hidden'); 
      }
    }
  );
  $('#links a').each(
    function() { 
      if($(this).attr('href') == "") { 
        $(this).css('visibility','hidden'); 
      }
    }
  );
}

function beta_send_page() {
  var loc = window.location.href;
  
  window.location.href="mailto:?subject=Besuchen Sie BETA Wellness!&body=Folgender Link koennte Sie interessieren: " + loc;
}

function prod_calculate_count_boxes() {
  var size = $('.product-slider .items img').size(); 
  var x; 

  for(x=1;x<=size;x++) { 
    $('.product-slider-count > div').append('<span></span>'); 
  }
}

function add_mouseover_to_product_links() {
$('#links a:nth-child(1)').hover(
  function(){
	$(this).parent().append("<div id='link-icon-tip'>PDF downloaden</div>"); 
  },
  function(){
	$('#link-icon-tip').remove();
  }
);

$('#links a:nth-child(2)').hover(
  function(){
	$(this).parent().append("<div id='link-icon-tip' style='padding-left: 10px;'>E-Mail senden</div>"); 
  },
  function(){
	$('#link-icon-tip').remove();
  }
);

$('#links a:nth-child(3)').hover(
  function(){
	$(this).parent().append("<div id='link-icon-tip' style='padding-left: 60px;'>Drucken</div>"); 
  },
  function(){
	$('#link-icon-tip').remove();
  }
);
}

function create_contact_handles() {
  $('#contact-form').append('<div class="contact-folder-handle"><p id="contact-handle-headline">Unverbindliche Beratung <img src="/fileadmin/templates2011/images/mailicon.png" class="mail-icon" /></p></div>');
  $('#contact-form').append('<div class="contact-folder-handle-static"><p id="contact-handle-headline">Unverbindliche Beratung <img src="/fileadmin/templates2011/images/mailicon.png" class="mail-icon" /></p></div>');

  var o = $('#content-inner').offset();
  $('.contact-folder-handle').css('left', o.left + 'px');
  
  $('.contact-folder-handle').bind("click", function() {
    contact_handle_grow();
  });
  
  $('#footer-contact-form input').live("focus", function() {
    $(this).val('');
  });
  
  $('#footer-contact-form textarea').live("focus", function() {
    $(this).html('');
  });
  
  
  $('.mail-icon').bind("click", function() {
    contact_handle_shrink();
  });
}

function checkTargetScroll() {
  var wH = $(window).height();
  var bH = $("body").height();
  var fH = 250;
  
  var targetScroll = bH - wH - 300;
  
  return targetScroll;
}

function adjustContactHandle() {
  if($(window).scrollTop() >= checkTargetScroll() || $(window).height() < 600) {
    $('#footer-contact-form').appendTo($('#contact-form'));
    $('.contact-folder-handle-static').show();
    $('.contact-folder-handle').hide();
  }
  else {
    $('.contact-folder-handle').show();
    if($('.contact-folder-handle').height() == "270") {
      $('#footer-contact-form').appendTo($('.contact-folder-handle'));
    }
    $('.contact-folder-handle-static').hide();
  }
}

function contact_handle_grow() {
  if($('.contact-folder-handle').height() < 250) {
    $('#footer-contact-form').appendTo($('.contact-folder-handle'));
    $('.contact-folder-handle').animate({
      height: '270px'
      }, 1200);
    $('.contact-folder-handle form').show();
  }
}

function contact_handle_shrink() {
  if($('.contact-folder-handle').height() >= 250) {
    $('.contact-folder-handle').animate({
      height: '17px'
      }, 1200, function(){
    $('#footer-contact-form').appendTo($('#contact-form'));
   });
  }
}

function browsercompat() {
  
  if($.browser.msie == true && $.browser.version == "7.0")
  {
    $('#footer').css('clear', 'both');
    $('.equalize').equalHeights(410,100000000).css('overflow', 'hidden');
  }
  else if($.browser.msie == true && $.browser.version == "8.0") {
    $('.contact-folder-handle-static').css('bottom', '175px');
    $('.equalize').equalHeights(410,100000000).css('overflow', 'hidden');
  }
  else if($.browser.msie == true && $.browser.version == "9.0") {
    $('.contact-folder-handle-static').css('bottom', '175px');
    $('.equalize').equalHeights(410,100000000).css('overflow', 'hidden');
  }
  else if($.browser.safari) {
    $('.contact-folder-handle-static').css('bottom', '175px');
    setTimeout("$('.equalize').equalHeights(500,100000000).css('overflow', 'hidden')", 1000);
  }
  else {
    $('.equalize').equalHeights(410,100000000).css('overflow', 'hidden');
  }
}

function targets(targetString) {
  if(targetString != "all") {
    var targetIds = targetString.split(",");
    for(x=0;x<=targetIds.length;x++) {
      showIcon(targetIds[x]);
    }
  }
  else {
    for(x=1;x<=31;x++) {
      showIcon(x);
    }
  }
}

function showIcon(el) {
  $("#i" + el).show();
}

function processIconBox() {
	var toffset = $('.iconbox').offset();
	$('.icon').bind('mouseover', function() {
	  var tpos = $(this).position();
	  $('.tip').hide();
	  $("#t" + $(this).attr("id")).css({top: tpos.top - 350, left: 0}).fadeIn();
	});
	$('.icon').bind('mouseout', function() {
	  $('.tip').fadeOut();
	});
	if($('#target-field').val() != "") {
	  targets($('#target-field').val());
	}
}

function processBottomSlider() {
  if($('#fullwidth .prod-slider-bottom-element').size() > 0) { // check if there are pool bottom elements
    $('#fullwidth').wrapInner('<div class="fullwidth-slider"></div>');
	$('.fullwidth-slider').wrapInner('<div class="fullwidth-slider-inner"></div>');
	
	if(calcBSLength() != -144 && $('#fullwidth .prod-slider-bottom-element').size() > 7) {
	  $('.fullwidth-slider > div:first').before('<div class="fw-slider-navi-left"></div>');
	  $('.fullwidth-slider > div:last').after('<div class="fw-slider-navi-right"></div>');
	}
  else {
    $('#fullwidth .prod-slider-bottom-element:first').css("margin-left", "0px");
    $('.fullwidth-slider-inner').css("padding", "0px");
  }
	
	var leftInt = 0; // left interval
	var rightInt = 0; // right interval

	$('.fw-slider-navi-left').hover(
	  function() {
	    leftInt = setInterval("$('.fullwidth-slider-inner').animate({left: '+=10'}, 1); positionBSArrows();", 50);
		return leftInt;
	  },
	  function() {
	    clearInterval(leftInt);
	  });	
	
	$('.fw-slider-navi-right').hover(
	  function() {
	    rightInt = setInterval("$('.fullwidth-slider-inner').animate({left: '-=10'}, 1); positionBSArrows();", 50);
		return rightInt;
	  },
	  function() {
	    clearInterval(rightInt);
	  });
  }
}

function processAdSlider() {
  if($('#ad-blocks .items').size() > 0) { // check if there are ad elements
	//$('#ad-blocks .items > .ad:nth-child(2)').wrap('<div class="ad-slider"></div>');
	processAdBlocks();
	$('#ad-blocks .items').cycle({fx: "scrollHorz", speed: 2000, timout: 15000 });
  }
}

function positionBSArrows() { // position bottom slider arrows according to BS position
  var pos = $('.fullwidth-slider-inner').position();
  pos = pos.left;
  if(pos < 0) { $('.fw-slider-navi-left').fadeIn();  $('.fw-slider-navi-right').fadeIn();}
  if(pos == 0) { $('.fw-slider-navi-left').hide(); $('.fw-slider-navi-right').fadeIn();  }
  if(pos <= calcBSLength()) { $('.fw-slider-navi-right').hide(); }
}

function calcBSLength() { // calculate BS elements total length
  var len = 0;
  $('.fullwidth-slider-inner .prod-slider-bottom-element').each(function() { len = len - $(this).width(); });
  return len + 620;
}

function positionFolder() { // position main menu accordingly
  var offset = $('#menu ul').position();
  offset = offset.top;
  
  $('#folder').css("top", offset - 70 + "px");
}

function adaptMainContentHeight() {
  var hc = $('#content-inner').height();
  var hs = $('#sidebar').height();
  
  if($('#fullwidth').children().size() > 0) {
    if(hc < hs) {
      $('#content').height(hs + $('#fullwidth').height() + 10);
    }
    else {
    $('#content').height(hc + $('#fullwidth').height() + 10);
    }
  }
  else {
    if(hc < hs) {
      $('#content').height(hs);
    }
    else {
    $('#content').height(hc);
    }
  }
}

function processAdBlocks() {
	var results =[];
	var elements = $("#ad-blocks .items").children('.ad');
	$.map( elements  , function(i, n){
		if( n%3 === 0 ){
			results.push(n);
		}
	});
	$.each( results , function(i,v){
		elements.slice(v, v+3).wrapAll('<div class="ad-slider"></div>');
	});
}

function processBigCycler() {
  if($('#big-cycler img:first').height() == 458) {
      $('#big-cycler').css("margin-bottom", "200px");
  }
  $('#big-cycler').cycle({ fx: "fade", speed: 2500, pause: false, timout: 5000});
}

function processSpecialOfferCycler() {
  $('.special-offer .so-right-images').each(function() { $(this).cycle({ fx: "scrollHorz", speed: 1500, pause: false, timout: 5000}); });
}
	
function removeAnfrage() {
  $('.produktpraes form').remove();
}

function normalizeSidebarImages() {
  if($('#sidebar').width() > 90) {
    $('#sidebar img').css({position: 'relative', margin: '20px 0px 0px 0px'});
  }
}

function activateFooterContact() {
  $('.footer-contact-submitter').css("cursor", "pointer");
  $('.footer-contact-submitter').live("click", function() {
    $.post("/fileadmin/templates2011/php/process_footer_contact.php", {
                            name: $('#cfname').val(),
                            mail: $('#cfmail').val(),
                            phone: $('#cfphone').val(),
                            zip: $('#cfzip').val(),
                            message: $('#cfmessage').val(),
                            location: window.location.href},
      function(callbackdata) {
        var cbhtml = ""; // the html string to inject into the callback div
        if(callbackdata == "1") {
          // print message
          cbhtml = '<span class="fcerror">Sie haben eine ung&uuml;ltige E-Mail-Adresse eingetragen - bitte korrigieren Sie diese.</span>';
          $('.footer-contact-message').html(cbhtml).fadeIn();
          setTimeout("$('.footer-contact-message').fadeOut()", 4000);
        }
        if(callbackdata == "2") {
          // print message
          cbhtml = '<span class="fcerror">Sie haben leider nicht alle Felder korrekt ausgef&uuml;llt - bitte korrigieren Sie Ihre Eingaben und versuchen Sie es erneut.</span>';
          $('.footer-contact-message').html(cbhtml).fadeIn();
          setTimeout("$('.footer-contact-message').fadeOut()", 4000);
        }
        if(callbackdata == "3") {
          // redirect to thank you page
          window.location.href='/index.php?id=143';
        }
      }
    );
  });
}

function foldOut(id) { // show specific folder and apply css rules
  if(id != 5 && id != 3) {
    $('#folder').removeClass();
    $('#folder').addClass('folder-' + id);
    $('#folder-content-inner').children().hide();
    $('#f' + id).show();
    $('#folder').show();
  }
}

function resetMenuItems(el) {  // reset all folder highlights (menu item MOs)
  $('#menu ul li img').each(
  function() {
    $(this).attr('src', "/fileadmin/templates2011/images/menu/" + $(this).attr("id") + ".png");
    $(this).bind("mouseout", function() { $(this).attr('src', "/fileadmin/templates2011/images/menu/" + $(this).attr("id") + ".png") });
  });
}

function initMainMenu() { // do all menu initialization
  $('#folder-closer').bind("click", function() {  // close folder and reset menu MO effects
    $('#folder').hide(); 
    resetMenuItems();
  });

  $('#menu ul li img').hover( // apply correct MO images and settings
    function() {
      $(this).attr('src', "/fileadmin/templates2011/images/menu/" + $(this).attr("id") + "mo.png");
    },
    function() {
      $(this).attr('src', "/fileadmin/templates2011/images/menu/" + $(this).attr("id") + ".png");
    }
  );

  $('#menu ul li img').bind("click", function() { // bind the right MO to the click and open the folder with specified settings
    resetMenuItems();
    positionFolder();
    foldOut($(this).attr("id"));
    $(this).unbind("mouseout");
    $(this).attr('src', "/fileadmin/templates2011/images/menu/" + $(this).attr("id") + "mo.png");
  });

  $('#m5').unbind("click");
  $('#m3').unbind("click");
  
}

function processLogo() {
  $('#header-left').css("cursor", "pointer").bind("click", function() { window.location.href="/"; });
  $('#header-left img').hover(
    function() {
      $(this).attr("src", "/fileadmin/templates2011/images/logohover.jpg");
    },
    function() {
      $(this).attr("src", "/fileadmin/templates2011/images/logo.jpg");
    }
  );
}
