/** folding of groupheader **************************************************/
$(document).ready(function(){
  // Section for toggle in and out of Barmer contracts descriptions on the quick search page
  if ($('.barmer-contract-description').length > 0) {
    // Hides the all barmer contracts descriptions  on the loading of the page with
    // the exception of the first contract
    var nodePosition = 0;
    $(".barmer-contract-description span.toggle").each(function() {
      var content = $(this).html();
      var position = content.indexOf('.');
      var displayedText = '';
      var hiddenText = '';
      if (position == -1) {
        displayedText = content;
      } else {
        displayedText = content.substr(0, position + 2);
        hiddenText = content.substr(position + 2);
      }
      if (hiddenText.length > 0) {
        $(this).html(displayedText + '<span style="display: none;">' + hiddenText + '</span>');
        $(this).siblings('a.toggle-link').html(foldQSearchInText);
        $(this).parent().append('<a class="toggle-link" href="#">' + foldQSearchInText + '</a>');
      } else {
        $(this).siblings('a.toggle-link').remove();
      }
      nodePosition++;
    });

    // Toggle on and out the barmer contract descriptions by the clicking on the toggle link
    var clickHandler = function(){
      if ($(this).siblings('span.toggle').children('span').is(':hidden')) {
        $(this).html(foldQSearchOutText);
      } else {
        $(this).html(foldQSearchInText);
      }
      $(this).siblings('span.toggle').children('span').slideToggle(null, function() {
        if (! $(this).is(':hidden')) {
          $(this).attr('style', 'display: inline;');
        }
      });
      return false;
    };
    $('a.toggle-link').click(clickHandler);
  }


  if ($('.groupheader').length > 0) {

    var foldOut = '<span class="toggle">[' + foldOutText + ']</span>';
    var foldIn = '<span class="toggle">[' + foldInText + ']</span>';

    // init groupheaders
    var groupsOmmit=":first";
    if ($('.quicksearchfilter').length > 0) {
      groupsOmmit="";
    }
    if (document.location.hash != '') {
      // don't close the anchor we navigated to
      var id=document.location.hash.replace(/^#/,'');
      groupsOmmit=":has(a[name="+id+"])";
    }

    // this enables use of classes start-open and start-close to determine state at load
    if ($('.groupheader.start-close').length > 0) {
      groupsOmmit = "";
    }

    // initialization
    $(".groupheader")
      .addClass("groupheader-javascript")
      .find("a")
        .attr("href","javascript://fold")
        .append(foldIn)
      .end()
      .not(groupsOmmit)
        // close them
        .addClass("groupheader-open")
        .next()
          .hide()
        .end()
        .parents("tbody").next()
          .hide()
        .end().end()
        .find(".toggle")
          .replaceWith(foldOut);

    // on the quicksearch open those with active searches again
    if ($('.quicksearchfilter').length > 0) {
      $('.filter-container :checkbox:checked')
        .add('.filter-container :text[value!=""]')
        .add('.filter-container :radio:checked')
        .add('.filter-container select option[value!="-42"]:selected')
          .not('option[value="min"]')
        .parents('.filter-container')
        .show()
        .prev()
          .removeClass("groupheader-open")
          .find(".toggle")
            .replaceWith(foldIn);
    }

    if ($('.selection-list-new-formatted').length > 0) {
      $('.selection-list-new-formatted :checkbox:checked')
      .parents('.selection-list-new-formatted')
      .show()
      .prev()
        .removeClass("groupheader-open")
        .find(".toggle")
          .replaceWith(foldIn);
    }

    if(document.location.hash != '') {
      // if by folding we moved the viewport away from the anchor, jump back
      document.location.hash = document.location.hash;
    }

    $(".groupheader").click(function(){
      // toggleGroupHeaders
      $(this)
        .toggleClass("groupheader-open")
        .filter(".groupheader-open").find(".toggle")
          .replaceWith(foldOut)
        .end().end()
        .not(".groupheader-open").find(".toggle")
          .replaceWith(foldIn)
        .end().end()
        .next()
          .slideToggle("fast")
        .end()
        .parents("tbody").next()
          .toggle();
       if($(this).parents("tbody").next().find("div").hasClass("geoMap")){
         $(this).parents("tbody").next().find("div[@class = 'geoMap']").toggle();
       };

       // with clickhelp, trigger the open state request
       if ($('.click-help-box').length > 0) {
         if ($('.groupheader-open').length > 0) {
           state = 'close';
         } else {
           state = 'open';
         }
         sendOpenStateRequest(state);
      }
    });

    function sendOpenStateRequest(state) {
      if (state != 'open' && state != 'close') {
        return false;
      }
      if (typeof toggleOpenStateParams['url'] != 'undefined') {
      params = toggleOpenStateParams['param'] + '=' + toggleOpenStateParams[state];
        jQuery.ajax({
          type: "POST",
          dataType: "xml",
          url: toggleOpenStateParams['url'],
          data: params
        });
      }
    }
  }
});

/** javascript capability ping **********************************************/
$(document).ready(function(){
  if (typeof JSPingUrl != 'undefined' && JSPingUrl != '') {
    jQuery.ajax({
      type: "GET",
      url: JSPingUrl,
      cache: false
    });
  }
});

/** folding for loginbox ****************************************************/
$(document).ready(function(){

  if ($('.wizard-top').length > 0) {

	  // action functions
	  function openLoginBox() {
		$('.loginContent')
		  .slideDown('fast')
		  .removeClass('close')
		  .addClass('open');
		loginBoxState = 'open';
		$('.tabContent a.openLogin')
		  .text(closeButton)
		  .removeClass('close')
		  .addClass('open')
		  .attr('href', closeUri);
	  }

	  function closeLoginBox() {
		$('.loginContent')
		  .slideUp('fast')
		  .removeClass('open')
		  .addClass('close');
		loginBoxState = 'close';
		$('.tabContent a.openLogin')
		  .text(loginButton)
		  .removeClass('open')
		  .addClass('close')
		  .attr('href', openUri);
	  }

	  function toggleLoginBox() {
		if ($('.openLogin').hasClass('open')) {
		  closeLoginBox();
		} else {
		  openLoginBox();
		}
	  }

	  // initializing
	  if (loginBoxState == 'close') {
		//closeLoginBox();
	  } else if (loginBoxState == 'open') {
		$('.tabContent a.openLogin')
		  .text(closeButton)
		  .addClass('open')
		  .attr('href', closeUri);
		$('.loginContent').show();
	  }

		// function binding
	  if ($('.notLoggedIn').length > 0) {
		$('.favoritesAddBox').bind('click', function() {
		  openLoginBox();
		  return false;
		});
	  }

	  $('.openLogin').bind('click', function () {
		toggleLoginBox();
		return false;
	  });

  }

});

/** effects for the genericButton *******************************************/
jQuery.fn.extend({
  bindButton : function() {

    return this.bind('mouseover', function () {
      if(true != $(this).find('.generic-button-inner').hasClass('button-disabled')) {
        $(this).addClass('genericButtonHover');
      }
    }).bind('mouseout', function () {
      $(this).removeClass('genericButtonHover');
    }).bind('keydown mousedown', function () {
      if(true != $(this).find('.generic-button-inner').hasClass('button-disabled')) {
        $(this).addClass('genericButtonActive');
      }
    }).bind('mouseup keyup', function () {
      $(this).removeClass('genericButtonActive');
    }).bind('click', function () {
      if(true != $(this).find('.generic-button-inner').hasClass('button-disabled')) {
        $(this).find('.generic-button-inner').click();
      }
    }).find('.generic-button-inner')
      .bind('focus', function () {
        $(this).parents('.genericButton').addClass('genericButtonFocus');
      }).bind('blur', function () {
        $(this).parents('.genericButton').removeClass('genericButtonFocus').removeClass('genericButtonActive');;
      });
  }
});
jQuery.fn.extend({
  findBindButton : function() {
    return this.find('.genericButton').bindButton().end();
  }
});
$(function () {
  $('.genericButton').bindButton();
});

/** checkbox selection buttons in assistant **********************************/
$(document).ready(function () {
  if ($('div.box-selection-list div.list-buttons').length > 0) {
    $("div.box-selection-list:has(div.list-buttons):has(li input.checkbox) div.list-buttons")
      .append('<span class="genericButton ">' +
              '<span class="t"/>' +
              '<span class="cl">' +
              '<span class="cr">' +
              '<span class="c">' +
              '<button id="select-all" class="generic-button-inner" name="select-all" type="submit">' +
              buttonSelectAll +
              '</button>' +
              '</span>' +
              '</span>' +
              '</span>' +
              '<span class="b"/>' +
              '<span class="tl"/>' +
              '<span class="tr"/>' +
              '<span class="br"/>' +
              '<span class="bl"/>' +
              '</span>' +
              '<span class="genericButton ">' +
              '<span class="t"/>' +
              '<span class="cl">' +
              '<span class="cr">' +
              '<span class="c">' +
              '<button id="select-none" class="generic-button-inner" name="select-none" type="submit">' +
              buttonSelectNone +
              '</button>' +
              '</span>' +
              '</span>' +
              '</span>' +
              '<span class="b"/>' +
              '<span class="tl"/>' +
              '<span class="tr"/>' +
              '<span class="br"/>' +
              '<span class="bl"/>' +
              '</span>'
              )
      .findBindButton()
      .find("#select-all")
        .click(function(){
          $("div.box-selection-list li input.checkbox").attr("checked","checked");
          return false;
        })
      .end().find("#select-none")
        .click(function(){
          $("div.box-selection-list li input.checkbox").attr("checked","");
          return false;
        });
  }
});

/** close window link for popups ********************************************/
$(document).ready(function(){
  // TODO make this translateable
  var closeWindowText = 'Fenster schließen';
  var closeWindowHTML = '<a href="#">' + closeWindowText + '</a>'
  $('.close-window')
    .append(closeWindowHTML)
      .click(closeWindow);
});
function closeWindow() {
  window.close();
}

/** some links selected by class should be opened in a popup ****************/
$(document).ready(function(){
  $('a.glossaryTermLink').click(openPopupClick);
  $('a.popup').click(openPopupClick);
});
function openPopupClick() {
  var height = 350;
  var width  = 600;
  if($(this).hasClass('popup1024x600')) {
    height = 600;
    width  = 1024;
  }
  var target = $(this).attr("target") ? $(this).attr("target") : "_blank";

  return openPopup($(this).attr("href"), target, width, height, "yes", "yes", "no", 100, 100);
}

/** used by the paging in the quicksearch ***********************************/
function sendFormByPagingLink(displayTarget) {
  document.getElementById('displayid').value = displayTarget;
  document.getElementById('quicksearch_result').submit();
}

/** search by location image hover ******************************************/
$(document).ready(function(){
  if($('div.staatemapping map[name=germany]').length > 0) {
    $('div.staatemapping map area').mouseover(
      function(){
        var state = "";
        switch( $(this).attr("alt") ) {
          case "Brandenburg":
            state = "br";
            break;
          case "Berlin":
            state = "be";
            break;
          case "Baden-Württemberg":
            state = "bw";
            break;
          case "Bayern":
            state = "by";
            break;
          case "Bremen":
            state = "hb";
            break;
          case "Hessen":
            state = "he";
            break;
          case "Hamburg":
            state = "hh";
            break;
          case "Mecklenburg-Vorpommern":
            state = "mv";
            break;
          case "Niedersachsen":
            state = "ni";
            break;
          case "Nordrhein-Westfalen":
            state = "nw";
            break;
          case "Rheinland-Pfalz":
            state = "rp";
            break;
          case "Schleswig-Holstein":
            state = "sh";
            break;
          case "Saarland":
            state = "sl";
            break;
          case "Sachsen":
            state = "sn";
            break;
          case "Sachsen-Anhalt":
            state = "st";
            break;
          case "Thüringen":
            state = "th";
            break;
          default:
            return false;
            break;
        }
        $('#map-image').attr("src",PAGE_THEME_PATH+"pics/maps/bghover_"+state+".png");
      });
	$('div.staatemapping map area').mouseout(
	  function(){
        $('#map-image').attr("src",PAGE_THEME_PATH+"pics/maps/staatline105.png");
      }
    );
    var imageObjs = new Array();
    var images = new Array("br","be","bw","by","hb","he","hh","mv","ni","nw","rp","sh","sl","sn","st","th");
    // start preloading
    for(var i=0; i<images.length; i++) {
         imageObjs[i] = new Image();
         imageObjs[i].src=PAGE_THEME_PATH+"pics/maps/bghover_"+images[i]+".png";
    }
  }
});


/**
 * Hover Effect for FeedbackBox
 */
$(function(){
  $('.feedbackBox')
    .addClass('pale')
    .hover(function() {
      $(this).removeClass('pale');
    },function() {
      $(this).addClass('pale');
    });
});

/**
 * Eyecandy stuff for diagnosis translator results
 */
$(document).ready(function(){
  $('.buttonlike').hide();
  $('div.searchResult').hover(
    function(){
      $(this).addClass('resultHover');
      $(this).find('.buttonlike').show();
    },
    function(){
      $(this).removeClass('resultHover');
      $(this).find('.buttonlike').hide();
    }
  );
});

/**
 * Slide Effect for yourOpinionBox
 */
$(function() {
  $('.yourOpinionTeaser')
    .find('.handle')
      .click(function() {
        $(this)
          .parent()
            .not(':animated')
              .filter('.open')
                .animate({width:'32'}, 500, 'swing', function () {
                  $(this).removeClass('open')
                })
              .end()
              .not('.open')
                .animate({width:'380'}, 500, 'swing', function () {
                  $(this).addClass('open')
                });
      })
    .end()
    .hover(function(event) {
      if(this.timeOutHover) {
        clearTimeout(this.timeOutHover)
      }
    }, function() {
      var hide = function(elem) {
        return function() {
          $(elem).filter('.open').find('.handle').click()
        }
      }(this);
      this.timeOutHover = window.setTimeout(hide, 1000);
    })
});

$(document).ready(function(){
  $('.checklistButton a').wrapInner('<span />');
});
