
/*jQuery.extend(jQuery.validator.messages, {
	required: "Dies ist ein Pflichtfeld",
	remote: "Bitte überprüfen Sie Ihre Eingabe.",
	email: "Bitte geben Sie eine gültige E-Mail-Adresse ein.",
	url: "Bitte geben Sie eine gültige URL ein.",
	dateISO: "Please enter a valid date (ISO).",
	date: "Bitte geben Sie ein gültiges Datum ein.",
	number: "Bitte geben Sie eine Nummer ein.",
	digits: "Please enter only digits",
	creditcard: "Please enter a valid credit card number.",
	equalTo: "Please enter the same value again.",
	accept: "Please enter a value with a valid extension.",
	maxlength: $.format("Bitte geben Sie maximal {0} Zeichen ein."),
	minlength: $.format("Bitte geben Sie mindesten {0} Zeichen ein."),
	rangelength: $.format("Please enter a value between {0} and {1} characters long."),
	range: $.format("Please enter a value between {0} and {1}."),
	max: $.format("Please enter a value less than or equal to {0}."),
	min: $.format("Please enter a value greater than or equal to {0}.") 
});*/

//spd = spd || {};
var spd = spd || {} ;

spd.toggleReplies = function() {
    $('a.btn-toggle-discussion-replies').each(function(a,b) {

          $(b).data('initial_text', $(b).text());
          $(b).data('replies_container', $(b).parents('li.item').find('ul.discussion-reply'));
          $(b).data('replies_container').hide();

          if($(b).data('replies_container').length == 0) {
                  $(b).remove();
          }

          $(b).click(function(e) {
                  e.preventDefault();
                  if($(this).data('replies_container').is(':visible')) {
                          $(this).data('replies_container').hide();
                          $(this).text($(this).data('initial_text'));
                  } else {
                          $(this).data('replies_container').show();
                          $(this).text('Antworten auf diesen Beitrag verbergen');
                  }
          });

  });
}

// inspired by http://www.w3schools.com/js/js_cookies.asp
spd.cookieHelper = {
  getCookie: function(c_name) {
    if (document.cookie.length>0) {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1) {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
      }
    }
  return "";
  },

  setCookie: function (c_name,value,expiredays,path) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    completeVal = c_name+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
    if (path != undefined && path != null && path != "") {
      completeVal += "; path=" + path;
    }
    document.cookie=completeVal;
  }

}

spd.myAccount = {
  COOKIE_NAME: "spd_mahmh",

  messageHeader: {
    doHideHeader: function() {
      var hideCookie = spd.cookieHelper.getCookie(spd.myAccount.COOKIE_NAME);
      return (hideCookie == "true");
    },
    setHideCookie: function() {
      spd.cookieHelper.setCookie(spd.myAccount.COOKIE_NAME, "true", 31, "/");
    },
    deleteHideCookie: function() {
      spd.cookieHelper.setCookie(spd.myAccount.COOKIE_NAME, "", 31, "/");
    }
  }
}


$(document).ready(function() {



	//
	//	TAB ENGINE
	//
	$('div.tab-wrapper').each(function(a, b) {
	
		if (!$(b).parents('div.social-networks-static-wrapper').length) {
			$(b).find('div.tab-content').hide().first().show();
			$(b).find('ul.tabs a:first').addClass('active');
		} else {
			$(b).find('div.tab-content').hide();
		}
		
		
		$(b).find('ul.tabs a').click(function(e) {
		
			e.preventDefault();
			if (!$(this).parents('div.social-networks-static-wrapper').length) {
				$(this).parents('ul.tabs').find('a').removeClass('active');
				$(this).addClass('active');
				$(this).parents('div.tab-wrapper').find('div.tab-content').hide();
				$(this).parents('div.tab-wrapper').find(this.hash).show();
				$(this).blur();
			} else {
				var active = $(this).hasClass('active');
				$(this).parents('ul.tabs').find('a').removeClass('active');
				$(this).parents('div.tab-wrapper').find('div.tab-content').hide();
				if (!active) {
					$(this).addClass('active');
					$(this).parents('div.tab-wrapper').find(this.hash).show();
				};
				$(this).blur();
			}
		});
		
	
	});
	





	//
	//	TOPIC CLOUD SEARCH FORM
	//
	$('ul#topthemen-cloud form').each(function(a, b) {
	
		$(b).data('labeltext', $(b).find('label').text());
		$(b).find('#searchterm').val($(b).data('labeltext')).focus(function() {
			if($(this).val() == $(b).data('labeltext')) $(this).val('');
		}).blur(function() {
			if($(this).val() == '') $(this).val($(b).data('labeltext'));
		});
	
	});

    
	
	



	//
	//	"IN DER NÄHE" SEARCH FORM
	//
  $('input[type="text"], textarea').each(function(index, node) {
   if ($(node).hasClass("keep-text")) return;
   if ($(node).hasClass("word_count")) $(node).val("");
	 var val = $(node).val();
	 if (!val) return;
   $(node).data('default', $(node).val()).focus(function() {
	   if ($(this).val() == $(this).data('default')) $(this).val("");
   }).blur(function() {
     if ($(this).val() == "") $(this).val($(this).data('default'));
   });
  });



	//
	//	RATING STARS ENGINE
	//
	$('ul.rating-stars').rating();






	//
	// WCharacter Counter for discussion form
	//
	$('.word_count').each(function() {
		var maxlimit = 4000;

		// get current number of characters
		var length = $(this).val().length;

		if(length >= maxlimit) {
			$(this).val($(this).val().substring(0, maxlimit));
			length = maxlimit;
		}

		// update count on page load
		$(this).parent().find('.counter').html( 'Noch ' + (maxlimit - length) + ' Zeichen');

		// bind on key up event
		$(this).keyup(function() {
			// get new length of characters
			var new_length = $(this).val().length;
			if(new_length >= maxlimit) {
				$(this).val($(this).val().substring(0, maxlimit));
				//update the new length
				new_length = maxlimit;
			}

			// update count
			$(this).parent().find('.counter').html( 'Noch ' + (maxlimit - new_length) + ' Zeichen');
		});
	}); 

  spd.imagelightbox = {
    open: function(url, alt, caption) {

      if(url == undefined || url == "") {
        return;
      }

      $('body').prepend('<div id="lightbox" style="display: none;"><div class="lightbox-content"><div class="content-head">' +
	       '<p id="ilb_headline"/>' +
	       '<p class="overview"><a href="#" onclick="spd.imagelightbox.close(); return false;" class="btn-close-lightbox">Schließen</a></p>'+
         '</div><div class="light-box"><p id="ilb_image"/><p id="ilb_caption"/></div></div></div><div id="lightbox-dimmer" style="display: none;">&nbsp;</div>');

      $('#lightbox-dimmer').fadeTo(500, 0.5);

      $('#lightbox').fadeIn(500, function() {
        //$(this).find('.btn-close-lightbox').focus();
      });

      $('#lightbox-dimmer').click(function() {
        $('#lightbox-dimmer, #lightbox').fadeOut(500, function() { $(this).remove(); });
      });

      var h4 = $('.article-head h4');
      //fallback for different DOM in campaigns
      if (h4 == undefined || h4 == null || h4.html() == null) {
        h4 = $('.bereich-body h3.subhead').clone();
      }
      $('#ilb_headline').replaceWith(h4.clone());
      $('#ilb_image').replaceWith('<img src="' + url + '" border="0" alt="'+alt+'" />');
      $('#ilb_caption').replaceWith($('#'+caption).clone());

      // scroll to top
      $(window).scrollTop(0);

    },
    close: function() {
      $('#lightbox-dimmer, #lightbox').fadeOut(500, function() { $(this).remove(); });
    }

  }


	
	
	
	
	
	//
	//	ARTICLE IMAGES
	//
	$('.article-image').find('.item:last').addClass('item-last');
	$('span.article-image').each(function(a, b) {
		if($(b).position()['top'] == 0) { $(b).addClass('article-image-first-row'); }
	});
	$('.article-image .image a').prepend('<span class="btn-zoom">&nbsp;</span>');
	$('.article-image .image a').bind('mouseover focus', function(e) { $(this).parents('.item').addClass('article-image-item-hover'); });
	$('.article-image .image a').bind('mouseout blur', function(e) { $(this).parents('.item').removeClass('article-image-item-hover'); });
	
	


	//
	//  THEME MATRIX DISPLACEMENT
	//
	(function() {
		var parent = document.getElementById('main-bottom');
		if (!parent) return;
		for (var i = 0, item = parent.childNodes[0]; item; item = parent.childNodes[++i]) {
			if (item.className != 'five-columns-set') continue;

			(function(node) {
				var col = [], len = 0;
				for (var i = 0, item = node.childNodes[0]; item; item = node.childNodes[++i]) {
					if (item.nodeType != 1 || item.className.slice(0, 3) != "col") continue;
					var index = parseInt(item.className.slice(4));

					col[index] = function(node) {
						var val = [];
						for (var i = 0, item = node.childNodes[0]; item; item = node.childNodes[++i]) {
							if (item.nodeName.toLowerCase() != 'h3') continue;
							val.push(item);
						};
						return val;
					}(item);

					if (col[index].length > len) len = col[index].length;
				};
				for (i = 0; i < len; i++) {
					(function(col, index) {
						var max = 0;
						for (var i = 1, j = col.length; i < j; i++) {
							var column = col[i];
							if (!column) continue;
							var item = column[index];
 							if (!item || item.offsetTop < max) continue;
							max = item.offsetTop;
						};
						for (i = 1, j = col.length; i < j; i++) {
							column = col[i];
							if (!column) continue;
							item = column[index];
							if (!item || item.offsetTop == max) continue;
							item.style.marginTop = 18 + (max - item.offsetTop) + "px";
						};
					})(col, i)
				};
			})(item);

		};
	})();

	
	
	
	//
	//	ARTICLE DISCUSSION
	//
	spd.toggleReplies();



	

	//
	//	RSS ACCORDION
	//
	$('.accordion').accordion({ 
		active: false, 
		header: '.head', 
		navigation: true, 
		event: 'click',  
		animated: 'easeslide',
		clearStyle: true,
		collapsible: true
	});


	//
	// Closable Messageboxes
	//
	$('div#message').prepend('<a id="message-button-hide" href="#">Informationen ausblenden</a>').after('<div id="message-show"><a id="message-button-show" href="#">Informationen einblenden</a></div>');
	$('a#message-button-hide').click(function(e) {
		$('div#message').hide();
		$('div#message-show').show();
		e.preventDefault();
                spd.myAccount.messageHeader.setHideCookie();
	});
	$('a#message-button-show').click(function(e) {
		$('div#message').show();
		$('div#message-show').hide();
		e.preventDefault();
                spd.myAccount.messageHeader.deleteHideCookie();
	});
        if (spd.myAccount.messageHeader.doHideHeader()) {
          $('div#message').hide();
          $('div#message-show').show();
        }


  //
  // Suggestions
  //
  $('input.jSuggest, input.suggestions').autocomplete({
	  source : ["test", "spd", "callback", "partei", "abc"],
	  open : function(e) {$(e.target).autocomplete("widget")[0].style.width = e.target.clientWidth.toString() + "px";}
  })


  //
  // Checkboxes & Radiobuttons
  //
  
  $('input[type="checkbox"]').custCheckBox();
  $('input[type="radio"]').custCheckBox();

	
	
	//
	// Select Dropdown
	//
	
	$('select').msDropDown();
	//
	// Pagination
	//
	$('div.sidebar-box-discussion-subscriptions').pagination();

	//
	// Tooltip
	//

	$('.tooltip').each(function() {
		var anchorAttr = 'tooltip-holder';
		var boxAttr = 'tooltip-content';
		var titleAttr = 'tooltip-title';
		var closeAttr = 'tooltip-close';
		var textAttr = 'tooltip-text';

		var titleText = "Information";
		var closeText = "Schliessen";

		var $this = $(this);
		var tooltip = document.createElement('span');
		tooltip.className = anchorAttr;

		var node = document.createElement('span');
		node.className = boxAttr;

		var child = document.createElement('strong');
		child.className = titleAttr;
		child.appendChild(document.createTextNode(titleText));
		node.appendChild(child);

		child = document.createElement('span');
		child.className = closeAttr;
		child.appendChild(document.createTextNode(closeText));
		node.appendChild(child);

		child = document.createElement('span');
		child.className = textAttr;
		child.appendChild(document.createTextNode($this.attr('title')));
		$this.removeAttr('title');
		node.appendChild(child);

		tooltip.appendChild(node);
		$this.data('tooltip', tooltip);
		$this.mouseover(function(e) {
			e.preventDefault();
			$this.append($this.data('tooltip'));
			$this.find('.' + boxAttr).mouseleave(function(e) {
				e.preventDefault();
				$(this).parent().remove();
			}).find('.' + closeAttr).click(function(e) {
				e.preventDefault();
				$(this).parent().parent().remove();
			});
		}).click(function(e) {e.preventDefault();});
	})

        var trackbackControl = document.getElementById('trackback-control');
        var trackbackLink = document.getElementById('trackback-link');
        if (trackbackControl && trackbackLink) {
          var visible = false;
          trackbackLink.style.display = 'none';
          $(trackbackControl).click(function(e) {
            if (visible) {
              $(trackbackLink).hide();
              visible = false;
            } else {
              $(trackbackLink).show();
              visible = true;
            }
            e.preventDefault();
          })
        }

});// end of document.ready

// appends html to the last element with class teaserBox
function fillAutofillBox(loadMoreLink, linkTarget, urlAjaxLoader, i18nAjaxLoader) {
  var $link = $(loadMoreLink);
  var $parent = $link.parent();
  $parent.empty().append('<img src="' + urlAjaxLoader + '" alt="' + i18nAjaxLoader + '" class="loading" />');
  $.ajax({
          url: linkTarget,
          success: function(html) {
                  $('.teaser-box:last').after(html);
                  $parent.hide();
                  // initialise rating
                  $('ul.rating-stars').rating();
          }
  });
};

/**
 * Use this function if you want to use functionality for each booked container
 * appends html to the element identified by the given id 
 * @param loadMoreLink
 * @param linkTarget
 * @param urlAjaxLoader
 * @param i18nAjaxLoader
 * @param id
 */
function fillAutofillBoxWithId(loadMoreLink, linkTarget, urlAjaxLoader, i18nAjaxLoader, id) {
  var $link = $(loadMoreLink);
  var $parent = $link.parent();
  $parent.empty().append('<img src="' + urlAjaxLoader + '" alt="' + i18nAjaxLoader + '" class="loading" />');
  $.ajax({
          url: linkTarget,
          success: function(html) {
                  $('#'+id).after(html);
                  $parent.hide();
                  // initialise rating
                  $('ul.rating-stars').rating();
          }
  });
};

function loadMoreComments(node, url, imgSrc, i18n, replace) {
  var $node = $(node).parent();
  $node.empty().append('<img src="' + imgSrc + '" alt="' + i18n + '" class="loading" />');
  $.ajax({
    url : url,
    success : function(html) {
      //$(html).last().addClass("item-last");
      var $fragment = $(document.createElement('div'));
      var button;  
      $(html).each(function(index, node) {
        if (node.nodeType != 1) return;
        if (node.nodeName.toLowerCase() == 'li') {
          $fragment.append(node);
          return
        };
        if (button || node.nodeName.toLowerCase() != 'div' || node.className != "load-more-wrapper") return;
        button = node;        
      });
      if (replace) $('ul.discussion').empty().append($fragment.html());
      else $('ul.discussion li.item-last').removeClass('item-last').after($fragment.html());
			$('ul.discussion li').last().addClass('item-last');
			$('ul.discussion').after(button);
			$node.remove();
			spd.toggleReplies();
	  }
  });
};


function loadMoreTrackbacks(node, url, imgSrc, i18n, replace) {
  var $node = $(node).parent();
  $node.empty().append('<img src="' + imgSrc + '" alt="' + i18n + '" class="loading" />');
  $.ajax({
    url : url,
    success : function(html) {
      //$(html).last().addClass("item-last");
      var $fragment = $(document.createElement('div'));
      var button;
      $(html).each(function(index, node) {
        if (node.nodeType != 1) return;
        if (node.nodeName.toLowerCase() == 'li') {
          $fragment.append(node);
          return
        };
        if (button || node.nodeName.toLowerCase() != 'div' || node.className != "load-more-wrapper") return;
        button = node;
      });
      if (replace) $('ul.trackbacks').empty().append($fragment.html());
      else $('ul.trackbacks li.item-last').removeClass('item-last').after($fragment.html());
			$('ul.trackbacks li').last().addClass('item-last');
			$('ul.trackbacks').after(button);
			$node.remove();

    }
  });
};
//
// SWFObject
//
swfobject.registerObject("audioplayer", "9.0.0", "expressInstall.swf");

  
