
/*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();
    }
    var toggle = function() {
      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');
      }
      return false;
    };

    $(b).click(toggle);

    toggle.apply(b); // show by default (SPD-954)

  });
};

// 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();
	 var val = node.getAttribute('value');
	 if (!val) return;
		var defaultFieldName = "#default-"+$(node).attr("id");
		var defaultContent = $(defaultFieldName).val();
	 $(node).data('default', val).focus(function() {
	  if ($(this).val() == defaultContent) $(this).val("");
   }).blur(function() {
    if ($(this).val() == "") $(this).val(defaultContent);
   });
  });



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






	//
	// WCharacter Counter for discussion form
	//
	$('.word_count').each(function() {
		var maxlimit = $(this).attr('data-max-length');
                if ( !maxlimit ) {
                  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 = $('<h4>').text(alt);
//      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'); });

	$('.image-result a').prepend('<span class="icon"></span>').bind('mouseover focus', function(e) {
		$(this).addClass('hover');
	}).bind('mouseout blur', function(e) {
		$(this).removeClass('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 $this = $(this);
    var tooltip = $('<span>').addClass('tooltip-holder');
    var node =$('<span>').addClass('tooltip-content');

    $('<strong>').addClass('tooltip-title').text("Information").appendTo(node);
    var closeButton = $('<span>').addClass('tooltip-close').text("Schliessen").appendTo(node);
    $('<span>').addClass('tooltip-text').text($this.attr('title')).appendTo(node);
    $this.removeAttr('title');

    node.appendTo(tooltip);
    tooltip.appendTo($this);
    tooltip.hide();

    $this.mouseover( function (e) {
          e.preventDefault();
          tooltip.show();
      // no idea what this is good for, but it doesn't seem to hurt...
          if (node[0].childNodes[0].offsetLeft < 0) {
            //debugger;
            node[0].childNodes[0].style.left = "-1.5em";
          }
    });

    node.mouseleave(function(e){
      e.preventDefault();
     tooltip.hide();
    });

    closeButton.click(function(e) {
      e.preventDefault();
      tooltip.hide();
    });

    $this.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();
          })
        }

		/*		
				ATTACHMENTS (Blogposts, Freitextseiten)		
		*/
		
		/*
				removes attachment block. If the last attachment block is removed, it adds a new one,
				so there are never zero attachment blocks
		*/
		$('.blog-settings-link > .blog-settings-control-remove').live('click', function(event){
          event.preventDefault();
					var parent = $(this).parent();
					if(parent.siblings('.blog-settings-link').length == 0){
						parent.remove();
						addAttachmentForm();
					} else {
						parent.remove();
					}
		});
		
		// binds click event for adding an attachment block
		$('#blog-attachments > .blog-settings-control-add').click(function(event){
				event.preventDefault();
				addAttachmentForm();
		});
		
		/*
				adds an attachment block and gives it an incrementally higher class name than the last
				existing attachment block
		*/
		function addAttachmentForm(){
				var lastIDName = $('#blog-attachments > .blog-settings-link:last > div > label:first').attr("for");
				var newID = 1;
				if(lastIDName){
						var lastIDPos = lastIDName.lastIndexOf("-");
						newID = parseInt(lastIDName.substr(lastIDPos+1))+1;
				}
				var attachmentForm = '<div class="blog-settings-link dotted-border-top"><div class="both">		<label for="blog-attachment-text-'+newID+'">Beschreibung der Datei</label>													<input id="blog-attachment-text-'+newID+'" type="text" name="blog-attachment-text-'+newID+'" value="Beschreibung der Datei eingeben" /><label for="blog-attachment-file-'+newID+'">Datei</label>	<input type="file" id="blog-attachment-file-'+newID+'" name="blog-attachment-file-'+newID+'" /></div><div class="blog-settings-control-remove">löschen</div></div>';
				$('#blog-attachments > .blog-settings-control-add').before(attachmentForm);
		}
		
		/*
				
			FREITEXT-ÜBERSICHT	
		
		*/
				
		// generates toggle button and hides sub-items		
		$('.freitextlist .freitext-sub').each(function(){
				var subAmount = $('li', this).length;
				var toggleString = "";
				if(subAmount == 1){
						toggleString = "1 Unterpunkt aufklappen";
				} else {
						toggleString = subAmount + " Unterpunkte aufklappen";
				}
				$(this).before('<span class="sub-toggle toggle-closed">'+toggleString+'</span>');
				$(this).toggle();
		});
		
		// opening behaviour
		$('.freitextlist .toggle-closed').live('click', function(event){
				event.preventDefault();
				$(this).removeClass('toggle-closed');
				$(this).addClass('toggle-open');
				$(this).html($(this).html().replace("auf", "zu"));
				$(this).parent().children('ul.freitext-sub').slideToggle(500);
		});
		
		// closing behaviour
		$('.freitextlist .toggle-open').live('click', function(event){
				event.preventDefault();
				$(this).removeClass('toggle-open');
				$(this).addClass('toggle-closed');
				$(this).html($(this).html().replace("zu", "auf"));
				$(this).parent().children('ul.freitext-sub').slideToggle(500);
		});
		
		$("#institutions-navi-wrapper").show();
		if(jQuery().jCarouselLite){
				$("#institutions-navi").jCarouselLite({
						btnNext: ".next",
						btnPrev: ".prev",
						scroll: 4,
						visible: 4,
						circular: false,
						speed: 1000
				});
		}
		
		$('.institution-list a.more').click(function(event){
				event.preventDefault();
                                $(this).siblings('span.less').toggle();
				$(this).siblings('span.more').toggle();
				$(this).siblings('a.less').toggle();
				$(this).toggle();
		});
		
		$('.institution-list a.less').click(function(event){
				event.preventDefault();
                                $(this).siblings('span.less').toggle();
				$(this).siblings('span.more').toggle();
				$(this).siblings('a.more').toggle();
				$(this).toggle();
		});
				
});// 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.replaceWith(html);
                  // 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();

    }
  });
};

/*
		AKTIONSBOERSE
*/

// Handles character count. Gets maximum char limit from the text of a TinyMCE sibling with the class ".maxchars"
function onTinyMCEChange(editor){
		var editorInstance = '#'+editor.editorId;
		if(!$(editorInstance).hasClass('restricted')) return;
		if(!$(editorInstance).siblings('.maxchars')) return;
		var maxChars = parseInt($(editorInstance).siblings('.maxchars').text());
                var textWithoutHtml = tinyMCE.activeEditor.getContent().replace(/<[^>]+>/g, '');
                var charAmount = $('<div>').html(textWithoutHtml).text().length;  // decode HTML entities to normal chars.
		var remaining = maxChars - charAmount;
		var indicators = $(editorInstance).siblings('p.restriction-indicator').children('.chars-remaining-amount');
		if(!indicators) return;
		if(remaining < 0){
				$(indicators).addClass("warn");
		} else {
				$(indicators).removeClass("warn");
		}
		$(indicators).text(remaining);
}

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


// header countdown for 150jahrespd.de
$(function() {
  var refreshCountDown = function() {
    var countDownElement = $('#c_dateCountDown');
    if (countDownElement.length) { // only if element exists
      var rightNow = new Date();
      var targetDate = new Date(2013,1,1);
      var differenceInMillis = targetDate.getTime() - rightNow.getTime();
      if ( differenceInMillis > 1000 * 60 ) { // we do minute like
        var remainingMillis = differenceInMillis;
        var remainder = remainingMillis % (24 * 60 * 60 * 1000);
        var days =  (remainingMillis-remainder) / (24 * 60 * 60 * 1000);

        remainingMillis = remainder;
        remainder = remainingMillis % (60 * 60 * 1000);
        var hours = (remainingMillis - remainder) / (60*60*1000);

        remainingMillis = remainder;
        remainder = remainingMillis % (60 * 1000);
        var minutes = (remainingMillis - remainder) / (60*1000);

        var formattedString = "In ";
        if ( days > 0 ) {
          formattedString += days + " Tag" + (days > 1 ? 'en ' : ' ');
        }

        if ( hours > 0 ) {
          formattedString += hours + " Stunde" + ( hours > 1 ? 'n ' : ' ');
        }

        if ( minutes > 0 ) {
          formattedString += minutes + " Minute" + (minutes > 1 ? 'n ' : ' ');
        }


        $(countDownElement).text(formattedString);

        setTimeout(refreshCountDown, 60 * 1000); // refresh once per minute
      }
    }
  };
  refreshCountDown();

});

$(function(){
  // replace spdcode fragments with their real contents
  $('code.spdcode').each(function(idx,obj) {
   $(obj).replaceWith($('<div>').html($(obj).text()));
  });
});



