/**
 * @author alexander.farkas
 */

/* Cufon Font Replacement */  /* plus: WEBSITE-310 */
Cufon.replace('html[dir=ltr] h5, html[dir=ltr] .text-box > h2, html[dir=ltr] .text-box-tabs > h2, html[dir=ltr] #home #teaser-group-4 h2, html[dir=ltr] #page-intro h1, html[dir=ltr] #search-results #main h1, html[dir=ltr] .new-search h2, html[dir=ltr] .text h1, html[dir=ltr] .text h2, html[dir=ltr] .text-col-box h2, html[dir=ltr] #faq h1, #main div.tw-switcher h3');


jQuery.noConflict();


(function($){
	var head;
	$.jsLoad = function(url){
		head = head ||
			document.getElementsByTagName('head')[0];
		if(head){
			var script = document.createElement('script');
			script.src = url;
			head.appendChild(script);
		}

	};
})(jQuery);


(function($){

	function callOnDomReady() {
		$('html').addClass('js-on'); // html class

		//createStyleSwitcher();

		//Zebra-Tables
		$('div.text tbody tr:nth-child(odd)').addClass('odd');

		//Twitter-Zebra
		$('#twitter_update_list li:nth-child(odd)').addClass('odd');

		addPrintLink();

		$('#reference-filter select')
			.bind('change', function() {
				$(this).parents('form')[0].submit();
				return false;
			});

		//wait for the swfobject DOM-Ready, so we can return a proper reference to flash object
		swfobject.addDomLoadEvent(function(){
			var s = $('div.flash')
				.embedSWF();
		});


		//initialize flowplayer
		window.contextPath = window.contextPath ||
			'';

		$("div.video a").flowplayer(
			contextPath + "/.resources/templating-kit/swf/flowplayer.swf", {
				// splash image
				clip:{
					autoPlay: false,
					autoBuffering: false
				}
			}
		);
		$("div.videoImage a").flowplayer(
				contextPath + "/.resources/templating-kit/swf/flowplayer.swf", {
					// splash image
					clip:{
						autoPlay: true,
						autoBuffering: false
					}
				}
			);

		//different tabs
		createTabs();
		faqToc();

		//Teaser-Switchers
		//$('div.teaser-wrapper:not(.tw-paging,.tw-slider)').scroller();
		$('div.teaser-wrapper:not(.tw-paging,.tw-slider)')
			.each(function(){
				$('div.pager', this)
					.append('<div class="prev"><span /></div><div class="next"><span /></div>');
				$(this).scroller();
			});

		pagingTeaserSwitcher();
		slidingTeaserSwitcher();

		$('body')
				.showbox({
					close: 'Close',
					prev: 'Previous',
					next: 'Next',
					posBox: '#showbox',
					dialogPosStyle: 'absolute',
					constrainToView: false,
					top: 10
				});

		slidingTabs();

		$.socialbookmark.init('li.social-b a');



		// Ausgangswert
		$("#searchbar").each(function(){
			var jElm = $(this),
				DEFAULT = "Search",
				val = jElm.val();

			// Bei Focus ändern
			function deleteVal(){
				jElm.removeClass('inactive');
				if(jElm.val() == DEFAULT){
					jElm.val("");
				}
			}
			// Bei blur/init ändern
			function restoreVal(){
				if(!jElm.val()){
					jElm.addClass('inactive').val(DEFAULT);
				}
			}

			jElm
				.bind('focus', deleteVal)
				.bind('blur', restoreVal);

			restoreVal();
		});




		/* FAQ */
        $('#faq-wrapper li h3 a')
			.inOut(function(){
	            $(this)
					.addClass('active', {
		                duration: 100,
		                easing: 'easeInExpo'
		            });
	        }, function(){
	            $(this)
					.removeClass('active', {
		                duration: 200,
		                easing: 'easeInExpo'
		            });
	        });




	} // callOnDomReady





	/* Twitter */
	window.twitterList = (function(){
		var itemTmpl = $.tmpl('<li><span class="date"><%=date%>:</span> <div class="tweet"><span><%=text%></span></div></li>'),
			listItems = '';
		function render(tweets){
			$.each(tweets, function(i, tweet){
				var t = {};
				t.text = tweet.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
				  return '<a href="'+url+'">'+url+'</a>';
				}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
				  return  reply.charAt(0)+'<a href="http://www.twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
				});
				t.date = relative_time(tweet.created_at);

				listItems += itemTmpl(t);
			});
			$('#twitter_update_list')
				.html(listItems);
		}
		function relative_time(time_value) {
			var values = time_value.split(" ");
			time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
			var parsed_date = Date.parse(time_value);
			var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
			var delta = parseInt((relative_to.getTime() - parsed_date) / 1000, 10);
			delta = delta + (relative_to.getTimezoneOffset() * 60);

			if (delta < 60) {
				return 'just now';
			} else if(delta < 120) {
				return 'a minute ago';
			} else if(delta < (60*60)) {
			return ('about '+ parseInt(delta / 60, 10)).toString() + ' minutes ago';
			} else if(delta < (120*60)) {
				return 'one hour ago';
			} else if(delta < (24*60*60)) {
				return 'about ' + (parseInt(delta / 3600, 10)).toString() + ' hours ago';
			} else if(delta < (48*60*60)) {
				return 'one day ago';
			} else {
				return ('about '+ parseInt(delta / 86400, 10)).toString() + ' days ago';
			}
		}
		return {
			render: render
		};
	})();
	/* Twitter END */




	function slidingTabs(){
		$.fn.mySlide = function(fn){
			fn = fn || function(){};
			return this.animate({
				height: 'toggle',
				opacity: 'toggle'
			}, {
				duration: 500,
				complete: fn,
				deque: true
			});
		};

		$('ol.superpromos-toc')
			.each(function(){
				$(this)
					.bind('tabtreecollapse', function(e, ui){
						ui.panel
							.stop(true, true)
							.animate({
								height: 'hide',
								opacity: 0
							}, {duration: 500});
					})
					.bind('tabtreeexpand', function(e, ui){
						ui.panel
							.stop(true, true)
							.animate({
								height: 'show',
								opacity: 1
							}, {duration: 500});
					})
					.tabtree(
						{activeButtonClass: 'on',
						selectEvents: 'mouseenter focus',
						handleDisplay: 'initial'
					})
					.find('a')
					.bind('click', function(e){

						if(e.pageX !== 0 && e.pageY !== 0){
							var url = $($(this).attr('href'))
								.find('a:first')
								.attr('href');
							if(url){
								location = url;
							}
						}
					});
			});


	}

	function pagingTeaserSwitcher(){
		function myPag(status){
				if(status == 'inactive'){
					$('a',this).animate({opacity: 0.5},{duration: 500});
				} else {
					$('a',this).animate({opacity: 1},{duration: 500});
				}
			}
			function myLink(status){
				if(status == 'show'){
					this.animate({opacity: 1},{duration: 500});
				} else {
					this.animate({opacity: 0},{duration: 500});
				}
			}
			$('div.teaser-wrapper.tw-paging').scroller({
				pagination: 'div.pagination',
				paginationFn: myPag,
				linkFn: myLink,
				paginationTitleFrom: 'h2',
				paginationAtoms: '<li class="pa-$number" title="$title"><a href="#">$number</a></li>'
			});
	}

	function slidingTeaserSwitcher(){

		$('div.teaser-wrapper.tw-slider')
			.each(function(){
				var jElm = $(this),
					slider = $('div.slider', this)
						.css({display: 'block'})
						.wrap('<div class="slider-bar" />');

				$('div.slider-bar', this)
					.append('<a href="#" class="prev">vor</a> <a href="#" class="next">zurück</a>');

				function slideSliderCall(e, o, ui){
					ui = ui ||
						o;
					var val = (ui && isFinite(ui.value))? ui.value : (o) ? o.value : false;
					jElm
						.scroller('moveTo', val + '%', false);
				}

				slider
					.slider({maxValue: 100})
					.bind('slide', slideSliderCall);

				jElm
					.scroller({
				        prevLink: 'div.slider-bar a.prev',
						nextLink: 'div.slider-bar a.next'
					})
					.bind('uiscrollerslide', function(e, d){
						slider
							.slider('value', d.percentPos);
					});

			});
	}


	function addPrintLink(){

		function print(){
			window.print();
			return false;
		}

		$('<li class="print"><a href="#">Print</a></li>')
			.prependTo('ul#text-features')
			.find('a')
			.click(print);
	}

	function faqToc() {
		var hash = location.hash;
			tabs = $('#faq-wrapper').find('h3 a');

		if(hash){
			tabs
				.filter('[href='+hash+']')
				.addClass('on');
		}

		$('#faq-wrapper')
			.bind('tabtreecollapse', function(e, ui){
				ui.panel.stop(true, true).slideUp(400);
			})
			.bind('tabtreeexpand', function(e, ui){
				ui.panel.stop(true, true).slideDown(400);
			})
			.tabtree(
				{
					buttonSel: 'h3 a',
					activeButtonClass: 'on',
					toggleButton: true,
					multiSelectable: true,
					handleDisplay: 'initial'
				}
			);
	}

	$.fn.tabChangeAddon = function(){
		this
			.bind('tabtreecollapse', function(e, ui){
				ui.button.parent().removeClass('on');
			})
			.bind('tabtreeexpand', function(e, ui){
				ui.button.parent().addClass('on');
			});

		$('a.on', this)
			.parent()
			.addClass('on');
		return this;
	};

	function createTabs(){

		$('ol.text-box-toc, ol.toc-box-toc')
			.each(function(){
				$(this)
					.tabtree(
						{activeButtonClass: 'on'}
					)
					.tabChangeAddon();
			});
	}

	function createStyleSwitcher(){
		if(location.pathname.indexOf('forms.html') != -1){
			var box = $('<div class="box" />');
			box
				.append('<h3>Styleswitcher</h3>');
			box
				.appendTo('#extras-1');

			$.CssSwitcher.createVisualSwitcher()
				.appendTo(box[0]);

			$('input', box[0]).checkBox();
		}
	}

	$('html').addClass('js-on'); // html class

	$.extend($.ui.scroller.defaults, {
        //Elements Classes
        atoms: 'div.rack-teaser',
        prevLink: 'div.prev span',
		nextLink: 'div.next span'
	});



	$(callOnDomReady);
})(jQuery);

// Suckerfish Dropdown Support

sfHover = function() {
  var sfEls = document.getElementById("dropdown").getElementsByTagName("LI");
  for (var i=0; i<sfEls.length; i++) {
    sfEls[i].onmouseover=function() {
      this.className+=" sfhover";
    }
    sfEls[i].onmouseout=function() {
      this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
    }
  }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);


