$(document).ready(function(){
	new OrderService();
});

var OrderService = function(){
	var checkboxes = $(":checkbox[name*=order]");
	var einabled = false;
	
	var errors = {
		orderlist: {
			de: "Bitte wählen Sie mindestens eine Publikation aus der Bestell-Liste aus",
			en: "Please select at least one Publication from the list"
		},
		address: {
			de: "Bitte füllen Sie alle Pflichtfelder aus",
			en: "Please fill out all compulsory fields"
		},
		email: {
			de: "Bitte geben Sie eine korrekte E-Mail-Adresse ein",
			en: "Please fill in your correct e-mail address"
		}
	};
	
	var handleErrors = function(args){
		
		var orderlist = args[0];
		var address = args[1];
		var email = args[2];

		var lang = __lang();
		var error = "";
		!orderlist ? error += errors.orderlist[lang]+"\n\n" : true; 
		!address ? error += errors.address[lang]+"\n\n" : true;
		if(!email){
			error += errors.email[lang];
		}
		
		if(!(args[0] && args[1] && args[2])) alert(error);
		return (args[0] && args[1] && args[2]);
	};
	
	
	if(checkboxes.size() > 0){
		var elements = {};
		elements.checkboxes = checkboxes;
		
		elements.inputs = $(":input[name=name], :input[name=surname], :input[name=street], :input[name=zip], :input[name=city], :input[name=country], :input[name=email]");
		elements.submit = $(":input[name=submit]");
		
		elements.submit.click(function(){
			if(handleErrors(change())){
				this.form.submit();
			}else{
				return false;
			}
		});

		var change = function(e){
			var einabled_1 = false;
			$.map(elements.checkboxes, function(element){
				return element.checked ? einabled_1 = true : true;
			});

			var einabled_2 = true;
			for(var i=0; i<elements.inputs.length; i++){
				elements.inputs[i].value.length == 0 ? einabled_2 = false : "";
			}
			
			var einabled_3 = /@/.test($(":input[name=email]").val());

			(einabled_1 && einabled_2 && einabled_3) ? elements.submit.einable() : elements.submit.disable();
			return [einabled_1, einabled_2, einabled_3];
		};
		change();
		
		$.each(elements, function(){
			this.change(function(){
				change();
			}); 
		});
	}
};

$.fn.disable = function(){
	this.each(function(){
		$(this).addClass("disabled");
	});
	
	return $(this);
};

$.fn.einable = function(){
	this.each(function(){
		$(this).removeClass("disabled");
	});
	return $(this);
};

(function(){
	$.fn.historyManager = function(years, next, back){
		var hash = window.location.hash;
		var dl = $(this);
		var yearRange  = dl.find("dt > .date").filter(function(index){

			if($(this).parent().parent().attr("id") != undefined){
        var id = this.innerHTML.replace(/ – /, "-").split(" ").join("-");
				$(this).parent().next().attr("id", "history-"+(id));
				if(hash.substr(1, hash.length) != ("history-" + id)){
					$(this).parent().hide();
					$(this).parent().next().hide();
				}
				return true;
			}
			return false;
		}).parent().clone();
		
		
		var yearNavigation = dl.before('<h2>'+years+':</h2><p class="history_navi"></p>').prev();

		yearRange.each(function(index){
			if(index != 0) yearNavigation.append('<span class="history_pfeil">></span>');

			var span = $(this).find("span");
			var id = span.text().replace(/ – /, "-").split(" ").join("-");
			var innerHTML = span.text();
			yearNavigation.append($(this).find("span").wrap("<a href='#history-"+id+"' title='"+innerHTML+"'></a>").parent());
			
			$("#history-"+id+"").append('<ul class="history_navi_year"><li class="next"><a title='+next+' class="date">'+next+'</a></li><li class="back"><a title='+back+' class="date">'+back+'</a></li></ul>');
			$("#history-"+id+"").find(".back, .next").hide();
			
			if(index != 0){
				$("#history-"+id+"").find(".back").show().find("a").attr("href", "#"+($("#history-"+id+"").prev().prev().attr("id"))+"");
			}
			
			if(index+1 != yearRange.length){
				$("#history-"+id+"").find(".next").show().find("a").attr("href", "#"+($("#history-"+id+"").next().next().attr("id"))+"");
			}
		});
		
		if(dl.find("dd[id^='history']:visible").length == 0){
			var dd = dl.find("dd[id^='history']").eq(0,1).show();
			dd.prev().show();
		}
		if(window.location.hash.length > 0) $(".history_navi a[href*="+window.location.hash+"]").addClass("active");
		
		$("body").click(function(event){
			if(event.target.className == "date"){
				switch(event.target.nodeName.toLowerCase()){
					case "span":
						var id = $(event.target).parent().attr("href");
						id = id.split("#")[1];
					break;
					default:
						var id = (event.target.href.split("#"))[1];
					break;
				}
				var oldDl = $("dd[id^='history']:visible");
				var dl = $("#"+id);
				var a = $(".history_navi a[href*="+id+"]");
				$(".history_navi .active").removeClass("active");
				a.addClass("active");
				

				if(oldDl[0] != dl[0]){
					oldDl.toggle().prev().toggle();
					dl.toggle().prev().toggle();
				};
			}
		});
		
	};
	
	$.fn.sitesMananger = function(){
		var hideDlDt = function(id){
			$("#"+id).hide().next().hide();
		};
		
		var createCaption = function(element){
			$(element).wrap('<div class="image"></div>').parent().append('<p></p>').find("p").hide();
		};
		
		return this.each(function(){
			var parent = $(this);
			var caption = $(".ansberg", this).each(function(){
				createCaption(this);
			}).next();

			$("a", this).each(function(){
				hideDlDt(this.href.split("#")[1]);

				$(this).hover(function(){
					caption.text($(this).text());
					caption.fadeIn(200);
				}, function(){
					caption.fadeOut(200);
					caption.text("");
				}).click(function(e){
					parent.find("a.active").removeClass("active");
					$(this).addClass("active");
					parent.find("dt:visible").hide().next().hide();
					$("#"+this.href.split("#")[1]).show().next().show();
				});
			});
		});
	};
	
})(jQuery);


jQuery(function($){
  var TABS = function(element){ //  Class Tabs created
    this.element = element;
    this.anchors = [];
    this.wrapParens();
    this.buildNavigation();
    this.setCurrent();
    this.display();
  };
  TABS.prototype = {
    wrapParens: function() {
      var _this = this;

      $(this.element).find("dt").each(function(){
        
        
        var id = _this.element.id+'_'+this.innerHTML.split(" ").join("").replace(/|\n|\t/, "-").replace(/ü|ö|ä|Ö|Ä|Ü|ß/g, function(buchstabe){
           return { "ü": "ue", "ö": "oe", "ä": "ae", "Ü": "Ue", "Ö": "Öe", "Ä": "Ae", "ß": "ss" }[buchstabe];
         }).replace(/[^\w]/g, "");
      
        $(this).next().attr("id", id);        
        _this.addAnchor($(this).wrapInner("<a href='#"+id+"'></a>").find("a").bind("click", function(){
          _this.setCurrent(this.href);
          _this.display();
        }));
        $(this).hide();
        
      });

    },
    
    addAnchor: function(anchor) {
      this.anchors.push($(anchor).clone(true));
    },
    
    buildNavigation: function(){
      var navigation = $("<ul class='anchor_list'></ul>");
      var length = this.anchors.length;
      
      $.each(this.anchors, function(index){
        var li = $("<li></li>");
        li.append(this);
        if(index == 0) li.addClass("first");
        if(index == length-1) li.addClass("last");
        navigation.append(li);
      });
      
      $(this.element).find("dl").before(navigation);
    },
    
    setCurrent: function(str){
      if(str){ 
        this.current = this.getHash(str);
        return;
      }
      
      this.current = this.current || "";
      if(window.location.hash.length) {
        var insideOfThis = $(this.element).find(window.location.hash);
        if(insideOfThis.length){
          this.current = window.location.hash.split("#")[1];
          return;
        }
      }      
      this.current = this.anchors[0][0].href.split("#")[1];      
    },
    display: function(){
      var id;
      for (var i=0; i < this.anchors.length; i++) {
        if((id = this.getHash(this.anchors[i].attr("href"))) != this.current) {
          $("#"+id).hide();
          this.anchors[i].removeClass("active");
        } else {
          $("#"+id).show();
          this.anchors[i].addClass("active");
        }
      };
    },
    
    getHash: function(str){
      if(str.indexOf("#") != -1) return str.split("#")[1];
      return str;
    }
    
  }
  
  $.fn.tabs = function(){
    $.each(this, function(index){
      this.id = this.id || "tab_"+(index+1);
      new TABS(this);
    });
  };
  $(".tabs").tabs();
});

jQuery(function(){
  jQuery(".sidebox p img").parent().css("text-align", "center");
});