$(function(){
	initNivoSlider();
	initSlidingMenu();
	initFastEntry();
	initTargetBlank();
	initNewsletterForm();
	initAccordeon();
	arcSelect('.arc_select');	
	$('.arc_select a').attr('target','map_iframe');
	
	$('.print a').click(function(){
		print();
	});
	
	setTimeout(function(){$('#teaser .twtr-widget').css('position','static'); 
						  $('#teaser .twtr-widget .twtr-join-conv').css('display','block')},
						  1300);
	
	
});

function initTargetBlank() {
	var h = window.location.host.toLowerCase();
	$("a[href^='http']:not(a[href^='http://" + h + "']):not(a[href^='http://www." + h + "']), a[href$='.pdf'], .download_list a").attr("target", "_blank");
}

function initAccordeon() {
	
	var acc = $('.accordeon');
	var h1 = acc.find('h1');
	
	acc.each(function(){
		var $this = $(this);
		var h1 = $this.find('h1');
		
		h1.click(function(){
			var next = h1.nextAll();
			if (next.eq(0).is(':hidden')) {
				acc.filter('.open')
					.removeClass('open')
					.children()
					.not('h1, :hidden')
					.slideUp('fast');

				next.slideDown('fast');
				$this.addClass('open');
			}
			else {
				next.slideUp('fast');
				$this.removeClass('open');
			}
		});
		
		if ($this.is('.open')) return true;
		
		$this.children().not('h1, :hidden').hide();
	});
}

function initNivoSlider(){
	
	var multimedia = $('.template_2 #multimedia');
	var items      = multimedia.find('article');
	
	if (items.length < 1) return false;
	
	var nivo = $('<div id="nivo"></div>').prependTo(multimedia);

	items.each(function(){
		var $this = $(this)
		var img   = $this.find('img').hide();
		img.clone().appendTo(nivo);
		if (items.length < 2)
			img.css('visibility','visible').show();
		else
			img.css('visibility','hidden');
	});
		
	if (items.length < 2) return false;
	
	
	$(window).load(function() {
		nivo.nivoSlider({
			effect:'boxRain,boxRainReverse',
			controlNav:false,
			startSlide:0,
	        boxCols: 8, // For box animations
	        boxRows: 1, // For box animations
	        animSpeed:300, 
	        pauseTime:6000,
			directionNavHide:false,
			afterLoad: 	  function(){ items.eq(0).addClass('current');
									},
			beforeChange: function(){ if ($.browser.msie && $.browser.version < 8) {
										nivo.find('.nivo-slider-bg').hide(); 
									  } else {
										  nivo.find('.nivo-slider-bg').fadeOut('slow'); 
									  }
									  items.removeClass('current');
									},
			afterChange:  function(){ var cur = $(this).data('nivo:vars').currentSlide;
								      var src = $(this).data('nivo:vars').currentImage.attr('src');
									  items.eq(cur).addClass('current');
									  nivo.find('.nivo-slider-bg').css('background-image', 'url('+src+')').show();
									  nivo.find('.nivo-box').hide();
								    }		
		});
	});	
}

function initSlidingMenu(){
	
	var timeout  = null;	
	var duration = [900, 8000];
	var total_w  = 715;
	var body     = $('body'); // NEW
	var content  = $('#content');
	var main_nav = $('#main_nav');
	var is_open  = false;	
	var links    = main_nav.find('ul li a:not(ul li ul li a)');
	var sublinks = $('#main_nav ul > li > ul > li > a');	
	var current  = links.filter('.current');	
	
	var openSub = function(el) {
		//clearTimeout(timeout);
		var sub = el.next();		
		if (sub.length == 0) return true;
		var delay = closeSub(false);
		sub.delay(delay).slideDown(duration[0]);
		current = el;
		if (!is_open) {
			content.animate({'margin-top': '59px'},duration[0]/1.5);
			is_open = true;
		}
		autoClose();		
		return false;
	};
	
	if (!is_open) {
		content.css('margin-top','0');
	}
	
	var closeSub = function(close_body) {
		if (!is_open) return 0;
		var sub = current.next();
		sub.slideUp(duration[0]/3);
		if (is_open && close_body) { 
			content.animate({'margin-top': '0'}, duration[0]);
			is_open = false;
			current = null;
		}
		return duration[0]/2;
	};
	
	var toggleSub = function(el) {
		var sub = el.next();
		if (sub.length != 1) return true;
		if (sub.is(':hidden') && (el != current || current == null)) {
			openSub(el);
			return false;
		}		

		closeSub(true);	
		return false;
	};	
	
	var autoClose = function() {
		return false;
		clearTimeout(timeout);
		timeout = setTimeout(function(){closeSub(true)}, duration[1]);
	};
	
	var initSubLinks = function(elm){

		var position  = elm.position();		
		var width     = elm.width();
		var bg_offset = (position.left+width/2-291);	
		var ul        = elm.next();
		var li        = ul.children();
		var data      = [];
		var li_w      = 0;
		
		li.each(function(i){
			
			data[i] = {
				a 		: $(this).find('a'),
				new_text: '',
				count   : 0,
				width   : 0 
			};
			data[i].text = data[i].a.html().replace(/-/g,'- ');
			data[i].text = data[i].text.split(' '),
			
			$.each(data[i].text, function(index, value) { 
				var space =  (value.match(/-$/)) ? '' : ' ';
				data[i].new_text += '<span>'+value+'</span>'+space;
				data[i].count++;
			});
			
			data[i].a.html(data[i].new_text);
			data[i].width = data[i].a.parent().css('width').replace(/px/,'')*1;
			li_w += data[i].width;
		});
		
		var count = 0;
		var temp_w = 0;
		
		while(li_w > total_w-15 && temp_w != li_w && count < 30) {
			
			var m=0, i;
			count++;
			temp_w = li_w;
			
			$.each(data, function(index, value) { 
				
				var h = data[index].a.parent().css('height').replace(/px/,'')*1;
				
				if (m < value.width && value.count > 1 && h < 40) {
					i = index;
					m = value.width;
				}
			});	

			if (typeof i != 'undefined') {
				
				var span = data[i].a.find('span');
				var left_l = 0;
				var right_l = 0;
				span.each(function(index) { 
					left_l  += span.eq(index).css('width').replace(/px/,'')*1;
					right_l += span.eq(span.length-index-1).css('width').replace(/px/,'')*1;				

					if (right_l > left_l) {
						return true;
					}
					data[i].count -= 1;
				});
				
				data[i].a.find('span').eq(data[i].count).addClass('block');
				
				li_w -= data[i].width;
				data[i].width = data[i].a.parent().css('width').replace(/px/,'')*1;
				li_w += data[i].width;
			}
		}

		if (li_w > total_w) {
			bg_offset -= total_w-li_w;
			ul.css('margin-left', total_w-li_w+'px');
		}

		ul.css('background-position',  bg_offset+'px 0')
		  .hide();
		setTimeout(function(){ ul.css('visibility','visible');},20);
	};

	
	links.each(function() {
		var $this = $(this);
		
		if (!$this.next().is('ul')) return true;
		
		$this
			.attr('href','#')
			.click(function(){
				toggleSub($this);
				return false;
			});
		
		initSubLinks($this);
		
	});
	
	sublinks.click(function() {
		clearTimeout(timeout);
		closeSub(true);
		return true;
	});
	
	main_nav
		.mousemove(function() {
			autoClose();
			return false;
		});
	
}

function initFastEntry() {
	
	var overlay;
	
	var fast_entry = $('#fast_entry');
	var cookie     = 'ARCHIWARE_FAST_ENTRY';
	var is_opened  = jaaulde.utils.cookies.get(cookie);		
	
	var openOverlay = function(pos) {

		var item      = fast_entry.children().eq(pos);
		var headline  = item.find('h2').text();
		var html      = item.find('.textblock').html();

		jaaulde.utils.cookies.set(cookie, pos);
		
		overlay = $('<div class="overlay">'+
					'<h2>'+headline+'</h2>'+
					html+
					'<a href="#" class="close" '+
					'title="[translate: close]">[translate: close]</a>'+
					'</div>').appendTo(fast_entry)
							 .show(200,function(){
								overlay
									.find('.close')
									.fadeIn(200)
									.click(function(){ 
										closeOverlay($(this));
									});
							 });
	};
	
	var closeOverlay = function(el) {
		el.fadeOut(200, function(){
			overlay.hide(200,function(){
				overlay.remove();
			});
		});
		jaaulde.utils.cookies.del(cookie);
	};
	
	if (is_opened != null) {
		openOverlay(is_opened);
	}
	
	fast_entry
		.find('h2 a')
		.click(function (){
			$this = $(this);
			item = $this.parentsUntil('.item').parent();
			prev = item.prevAll();
			openOverlay(prev.length);
	});
}

function initNewsletterForm() {
	
	var nl = $('#nl_subscribe form');
	
	if (nl.length < 1) return false;
	
	initFormLabelToDefault();
	
	$('#nl_archive ul > li').each(function(){
		var $this = $(this);
		var html = $this.html().replace(/, /,'');
		$this.html(html);
	});

	
}


function initFormLabelToDefault() {
	
	var forms = $('form');
	
	forms.find('label').hide();
	
	forms.submit(function(){
		$(this)
			.find('input[type="text"], textarea')
			.each(function(){
				toggleLabel($(this), 'remove')
			});
	})	
	.find('input[type="text"], textarea')
	.each(function() {
		
		var $this = $(this);
		var title = clearLabelStr($this.attr('title'));
		var label = clearLabelStr($this.parent().parent().find('label').text());
		
		if (label != title) {
			title = label;
			$this.attr('title',title);
		}			

		toggleLabel($this, 'add');
		
		$this.blur(function() {
			toggleLabel($this, 'add');
		});
		
		$this.focus(function() {
			toggleLabel($this, 'remove');
		});			
	});
	
	forms
		.find('select')
		.each(function() {
			var $this = $(this);
			var first = $this.children().eq(0);
			var title = clearLabelStr($this.attr('title'));
			var label = clearLabelStr($this.parent().parent().find('label').text());
			
			if (label != title) {
				title = label;
				$this.attr('title',title);
			}
			
			if (first.text() == '') {
				first.html(title);
			}
			else if(first.val() != '') {
				$this.prepend('<option>'+$this.attr('title')+'</option>');
			}
			
			if ($this.children().eq(0).is(':selected')) {
				$this.addClass('default');
			}
			$this.change(function(){
				if ($this.children().eq(0).is(':selected')) {
					$this.addClass('default');
				}
			});
			
			$this.focus(function(){
				$this.removeClass('default');
			});	
		});
}

function clearLabelStr(str){
	str = jQuery.trim(str);
	return 	str.replace(/\n/g, ' ');
}

function toggleLabel(obj, type){
	var input = $(obj);
	var value = clearLabelStr(input.val());
	var label = clearLabelStr(input.attr('title'));

	if (type == 'remove' && value == label) {
		input.val('');
	}	
	if (type == 'add' && value == '') {
		input.val(label);
	}	
	
	if (input.val() == label) {
		input.addClass('default');
	}
	else {
		input.removeClass('default');
	}
}



function arcSelect(selector, callback) {
	
		$(selector).each(function() {

			var timeout;
			
			var elm       = $(this);
			var list      = elm.find("ul");					
			var items     = list.children();
			var current   = items.filter(".current"); 
			var active    = $('<li class="active"></li>').prependTo(list);
			var title     = elm.attr('title');
			var has_title = typeof title != 'undefined' && title.length > 0;
			var delay     = 3000;
			var bussy     = false;
			var ul_height = 43;
			
			items.each(function(){ ul_height += $(this).height()*1; });
			
			var openList = function() {
				if (bussy == true) return false;
				refreshTimeout();
				bussy = true;
				list.animate({height: ul_height + "px"}, 
							 ul_height/5, 
							 function(){ bussy = false; })
					.addClass("open");
			};
			
			var closeList = function() {
				if (bussy == true) return false;
				clearTimeout(timeout);
				bussy = true;
				list.animate({height: "31px", 
							  paddingBottom: 0}, 
							  ul_height/5, 
							  function(){ bussy = false; })
							 .removeClass("open");
			};
			
			var refreshTimeout = function() {
				clearTimeout(timeout);
				timeout = setTimeout(function(){ closeList(); }, delay);
			};
			
			var updateActive = function(text) {
				active.text(text);
				active.attr('title', text);
			};
			
			if (current.length == 0) {
				if (has_title) {
					updateActive(title);
					elm.addClass('default');
				}
				else { 
					current = items.eq(0);
					current.addClass('current');
					//callback.call(current);
					updateActive(current.text());
				}
			}
			else {
				updateActive(current.text());
			}
			
			items.click(function() {
				
				$this = $(this);
				closeList();
				setTimeout(function(){
					if ($this.is('.current') && has_title) {
						updateActive(title);
						elm.addClass('default');
						return false;
					}
					else {
						current.removeClass('current');
						current = $this;
						current.addClass('current');
						updateActive(current.text());
						elm.removeClass('default');
						if (typeof callback == 'function') {
							callback.call(current);
						}
					}
				},200);
				if (typeof callback == 'function') {
					return false;
				}
			});
			
			items.mousemove(function(){
				refreshTimeout();
			});
			
			$('body').click(function(){
				closeList();
			});
			
			active.click(function() {
				if (!list.is(".open")) {
					openList();
				} else {
					closeList();
				}
			});
			
			elm.addClass('init');
		});		
}

