var	isiPad = navigator.userAgent.match(/iPad/i) != null,
		speed = 500,
		$wall = null,
		$overlay = null,
		lastY = 0,
		running = false,
		html5history = (history && history.pushState) ? true : false,
		memory = new Array();
		addedElementsLength = 1,
		isotopeOptions = {
			layoutMode : 'masonry',
			itemSelector: '.box',
			animationOptions: {
				duration: speed,
				easing: 'linear',
				queue: false
			},
			getSortData : {
		    rel : function ( $elem ) {
		      var r = $elem.attr('rel');
					if(r != undefined){
						//log(parseInt(r.erase('e'))+' || '+$('.title', $elem).text());
						return parseInt(r.erase('e'));
					}
		    }
			},
			sortBy : 'rel',
			sortAscending : false
		};
		
$(document).ready(function(){
	if (navigator.userAgent.match(/Opera/i) != null)     
	{
		$('body').addClass('opera');
	}
	
	if(html5history && false){
		window.onpopstate = function(event){
			if(event.state){
				if(!$wall.is(':visible')){
					closeOverlay();
				}
				$('a[href="'+event.state.path+'"]:not(.latest)').click();
			}
		};
	}
	sublimevideo.load();
  initDirectorSlider();
	$('#radiofilternavigation').attr('rel','e9999999999999');
	$wall = $('#main');
	$overlay = $('#overlay');
	if($('.box', $wall).length && $('#radiofilternavigation ul a').length){
		$('#main div:not(.mod_navigation)').remove();
		$('#main').addClass('loaded');

		$wall.isotope(isotopeOptions);
		$('#radiofilternavigation ul a').click(function(){
			if(!running){
				running = true;
				$('#radiofilternavigation ul a.latest').removeClass('latest');
				var $li = $($(this).parent());
				if(!$li.hasClass('active')){
					if($('ul li a', $li).length){
						$('#radiofilternavigation ul li ul:visible').slideUp(speed);
						$('ul',$li).slideDown(speed, function(){
							$('a:first, ul li a:first', $li).prependTeasersByHash();
							$('ul li:first', $li).addClass('active');						
						});
					} else {
						if(!$(this).parent().parent().hasClass('level_2')){
							$('#radiofilternavigation ul li ul:visible').slideUp(speed);
						}
						$(this).prependTeasersByHash();
					}
					$li.toggleClass('active');
				} else {
					if($('ul li', $li).length){
						$('.latest', $li).removeClass('latest');
						if($('ul:hidden li', $li).length) {
							$('#radiofilternavigation ul li ul:visible').slideUp(speed);
							$('ul',$li).slideDown(speed);
							$('li.active:first a', $li).killTeasersByHash();
						} else {
							$('ul',$li).slideUp(speed,function(){
								$('a',$li).killTeasersByHash();
							});
						}
					} else {
						$('#radiofilternavigation ul li ul:visible').slideUp(speed);
						$(this).killTeasersByHash();
					}
				}
			}
			return false;
		});
		
		var $aopt = $('#radiofilternavigation ul > li.trail.submenu > a');
		var $aop = $('#radiofilternavigation ul > li.active > a');
		if($aopt.length){
			$aopt.parent().addClass('active');
			$('ul', $aopt.parent()).slideDown(speed);
		}
		if($aop.length){
			$aop.parent().removeClass('active');
			$aop.click();
		}
		
	}else if($('.smallmedia').length){
		sublimevideo.ready(function(){
			initMediaGallery();
		});
	}
	
	if($('#footercontactnavigation a').length){
		$('#footercontactnavigation li a').click(function(){
			var $this = $(this);
			
			if($('#main .'+$this.attr('id')).length){
				$wall.isotope('remove', $('#main .'+$this.attr('id')));
				$wall.isotope('reLayout');
			}
			
			if($('#article').is(':visible')){
				closeOverlay();
				window.setTimeout(function(){
					$.scrollTo(0, speed);
					$this.prependTeasersByHash();
				}, 2*speed);
			} else {
				$.scrollTo(0, speed);
				$this.prependTeasersByHash();
			}
			return false;
		});
	}
	
	$('#footer ul li a').click(function(){
		var hash = $(this).attr('href');
		if($('#radiofilternavigation ul li a[href="'+hash+'"]').length){
			if($('#article').is(':visible')){
				closeOverlay();
				window.setTimeout(function(){
					$.scrollTo(0, speed);
					$('#radiofilternavigation ul li a[href="'+hash+'"]').click();
				}, 2*speed);
			} else {
				$.scrollTo(0, speed);
				$('#radiofilternavigation ul li a[href="'+hash+'"]').click();
			}
			return false;
		}
	});
});

function initDirectorSlider(){
	if($('.slidercanvas:not(.initialized)').length){
		$('.slidercanvas').addClass('initialized');
		$('.slidercanvas').jCarouselLite({
			btnNext: '.next',
			btnPrev: '.prev'
		});
	}
};

function mediaGalleryVideoToggle(aim){
	var $this = $(aim).parent();
	if($('#mediaslot1 .sublime').length){
		sublimevideo.stop();
		sublimevideo.unprepare($('#mediaslot1 .sublime').attr('id'));
	}
	if($('video', $this).length){
		sublimevideo.prepare($('.sublime', $this).attr('id'));
	}
	var msOld = $('#mediaslot1 .mediaslotcontent').remove();
	var msNew = $('.mediaslotcontent', $this).remove();
	$('#mediaslot1').css({opacity:0}).append(msNew).animate({opacity:1},speed);
	$this.css({opacity:0}).append(msOld).delay(speed/3).animate({opacity:1},speed);
	$('.mediaslotcontent', $this).click(function(){
		mediaGalleryVideoToggle(this);
	});
	return false;
};

function initMediaGallery(){
	if($('#mediaslot1 .sublime').length > 0){
		sublimevideo.prepare($('#mediaslot1 .sublime').attr('id'));
	}
	$('.smallmedia .mediaslotcontent').click(function(){
		mediaGalleryVideoToggle(this);
	});
	//replacing media with mediaslot to prohibit the page to scroll to the item with the id
	if(mediaslot && $('#mediaslot'+mediaslot).hasClass('smallmedia')){
		window.setTimeout(function(){ $('#mediaslot'+mediaslot+' .mediaslotcontent').click(); }, 500);
	}
};

String.prototype.erase = function(k){return this.replace(k,'');};

jQuery.fn.toTop = function(){
	var	$data = this,
			newElementsLength = $data.length,
			countdown = addedElementsLength;
	addedElementsLength += newElementsLength;
	$('#radiofilternavigation').attr('rel','e'+(addedElementsLength*100));	
	return $data.each(function(){
		$(this).attr('rel','e'+(newElementsLength+countdown));
		countdown--;
	});
};

jQuery.fn.killTeasersByHash = function(){
	var fc = '';
	if(this.length == 1){
		var $hash = $('.'+this.attr('id'), $wall);
		if($hash.css('opacity') == 1){
			this.parent().toggleClass('active');
			$wall.isotope('remove', $hash);
			$wall.isotope('reLayout');
			memory.pop();
		} else {
			this.prependTeasersByHash();
		}
	} else {
		this.parent().parent().parent().toggleClass('active');
		this.each(function(){
			var hash = $(this).attr('id');
			$wall.isotope('remove', $('.'+hash, $wall));
			if(jQuery.inArray(hash, memory) != -1){
				memory.splice(jQuery.inArray(hash, memory), 1);
			}
		});
		$wall.isotope('reLayout');
	}	
	fc = memory.pop();
	memory.push(fc);
	html5history && history.pushState({ path: $('#radiofilternavigation ul a[id='+fc+']').attr('href') }, '', $('#radiofilternavigation ul a[id='+fc+']').attr('href'));
	
	if($('.'+fc).length > 0){
		//alte Sachen wieder aktiv machen.
		
		//hide 2. navigation dimension
		var $latest = $('#radiofilternavigation ul li ul li a.latest');
		var $newest = $('#radiofilternavigation ul li ul li a[id='+fc+']');
		if($latest.length && !$newest.length)
			$latest.parent().parent().slideUp(speed);
		
		$('#radiofilternavigation ul a[id='+fc+']').addClass('latest');
		if($('#radiofilternavigation ul li ul li a[id='+fc+']').length){
			$('#radiofilternavigation ul li ul li a[id='+fc+']').parent().parent().slideDown(speed);
		}
		
		
		stopPromoteaser();
		$('.box:not(.nosort)', $wall).css({opacity:0.25}).addClass('ishistory');
		$('.'+fc).css({opacity:1}).toTop().removeClass('ishistory');
		
		//regisseurbox spezialfall
		if($('.box.regisseure').length){
			if($('ul li a.latest', $('a#id-5').parent()).length){
				$('.box.regisseure').css({opacity:1}).attr('rel',(addedElementsLength+1)*5);
			} else {
				var rel = $('.box.regisseure').attr('rel');
				$('.box.regisseure').attr('rel',rel/5);
			}
			$wall.isotope('updateSortData', $('.box', $wall));
			$wall.isotope({ sortBy : 'rel' });
			$wall.isotope('reLayout');
		}
		
		
		$wall.isotope('updateSortData', $('.box', $wall));
		$wall.isotope({ sortBy : 'rel' });
		$wall.isotope('reLayout');
		startPromoteaser();
		html5history = (history && history.pushState) ? true : false;
	}
	running = false;
	return this;
};

jQuery.fn.prependTeasersByHash = function(){
	var ids = new Array();
	var hrefs = new Array();
	var results = new Array();
	$this = $(this);
	$this.each(function(){
		ids.push($(this).attr('id'));
		hrefs.push($(this).attr('href'));
	});
	var $elements = $('.'+ids.join(', .'), $wall);
	if($elements.length === 0){
		if($this.length > 1){
			$this.parent().parent().parent().addClass('loading');
		} else {
			$this.parent().addClass('loading');
		}
		hrefs.reverse();
		countdown = hrefs.length;
		for(i=0; i < hrefs.length; i++){
			results[i] = null;
			//log(hrefs[i]+'?requestOrder='+i);
			$.ajax({
			  url: hrefs[i]+'?requestOrder='+i,
			  success: function(data){
					if($('#teasers .box', $(data)).length > 0){
						var requestOrder = parseInt(data.substr(0,1));
						results[requestOrder] = $('#teasers .box', $(data));
						data = null;
					}
				},
				complete: function(){
					running = false;
					countdown--;
				}
			});
		}
		
		//bis alle requests fertig sind
		var checkAjax = window.setInterval(function(){
			if(countdown == 0){
				ids.reverse();
				for(n=0; n < results.length; n++){
					if(results[n] != null){
						$('#cache').append(results[n].toTop());
						results[n] = null;
						if(!$('#'+ids[n]).hasClass('submenu')){
							memory = memory.concat(ids[n]);
						}
					}
				}
				window.setTimeout('cache2wall()', 500);
				window.clearInterval(checkAjax);
			}
		}, 100);
		
	} else {
		//nur nach oben schieben
		var key = memory.indexOf($this.attr('id'));
		if(key != -1){
			var sliced = memory.splice(key, 1);
		}
		memory.push($this.attr('id'));
		$('#radiofilternavigation ul li.loading').removeClass('loading');
	}
};

jQuery.fn.addTeaserEvents = function(){
 this.each(function(){
		$('.awards-hover', this)
			.mouseenter(function(){
				$('.awards-flyout', this).stop(true, true).fadeIn(speed);
			})
			.mouseleave(function(){
				$('.awards-flyout', this).stop(true, true).fadeOut(speed);
			});
	
		if($(this).hasClass('horizontal')){
			$('a', $(this)).hover(function(){
				$('.teasercontent', $(this)).stop(true, true).animate({top:0}, 100);
			},
			function(){
				$('.teasercontent', $(this)).stop(true, true).animate({top:-20}, 100);
			});
		} else if($(this).hasClass('vertical')){
			$('a', $(this)).hover(function(){
				$('.teasercontent', $(this)).stop(true, true).animate({right:20}, 100);
			},
			function(){
				$('.teasercontent', $(this)).stop(true, true).animate({right:0}, 100);
			});
		}
		
		$('a.showarticle', this).click(function(){ //add clickevent to teasers
			if(!running){
				running = true;
				var $this = $(this);
				lastY = $(window).scrollTop();
				$.scrollTo(0, speed, {onAfter:function(){
					showOverlay($($this).attr('href'));
				}});
			}	
			return false;
		});
	});
	return this;
};

function showOverlay(loadUrl){
	var loadUrl = loadUrl;
	if ( $.browser.msie && parseInt($.browser.version, 10) < 9 ) {
		if(loadUrl.search('http://') != -1 ){
			this.location.href(loadUrl);
		}else{
	  	this.location.href('/'+loadUrl);
		}
	} else {
		$overlay.hide(0);
		$('#footer').fadeOut(speed);
		$wall.fadeOut(speed, function(){
			$.ajax({
			  url: loadUrl,
			  success: function(data){
					if($(data).length){
						$overlay.append(data);
						if(html5history){
							$('#article .backbutton a', $overlay).attr('href',history.state);
							history.pushState({ path: loadUrl }, '', loadUrl);
						}
						$('#article .backbutton a', $overlay).click(function(){
							html5history && history.pushState({ path: $($this).attr('href') }, '', $($this).attr('href'));
							closeOverlay();
							return false;
						});
						$overlay.fadeIn(speed, function(){
							window.setTimeout('initMediaGallery()', 500);
							html5history = (history && history.pushState) ? true : false;
						});
						$('#footer').fadeIn(speed);
					}
					return false;
				},
				error: function(){
					//log('fatal error: forced page refresh');
					this.location.href('/'+loadUrl);
					return false;
				}
			});
		});
	}
};

function closeOverlay(){
	$('#footer').fadeOut(speed);
	$overlay.fadeOut(speed, function(){
		$overlay.html('');
		$wall.fadeIn(speed);
		$wall.isotope('updateSortData', $('.box', $wall));
		$wall.isotope({ sortBy : 'rel' });
		$wall.isotope('reLayout');
		$('#footer').fadeIn(speed);
		$.scrollTo(lastY, speed);
		running = false;
		html5history = (history && history.pushState) ? true : false;
	});
};

function startPromoteaser(){
	var $promo = $('.promoimages:first', $wall);
	if($promo.length && !$promo.parent().hasClass('ishistory'))
		$promo.data('nivoslider').start();
};

function stopPromoteaser(){
	var $promo = $('.promoimages:first', $wall);
	if($promo.length)
		$promo.data('nivoslider').stop();
};

function initPromoteaser(){
	var $promo = $('.promoteasers:not(.ishistory) .promoimages', $wall);
	if($promo.length){
		var $backup = $('img', $promo);
		$promo
			.html('')
			.append($backup)
			.nivoSlider({
				effect: 'boxRandom',
				boxCols:5,
				boxRows:4,
				directionNav: false,
				keyboardNav: false,
				captionOpacity: 1,
				afterLoad: function(){
					var $imgs = $('img', $promo);
					$imgs.each(function(i, img){
						$('a.nivo-control[rel="'+i+'"]', $promo).addClass($(img).attr('class'));
					});
				}
			});
		}
};

function cache2wall(){
	var fc = memory.pop();
	memory.push(fc);		
	//hide 2. navigation dimension
	var $latest = $('#radiofilternavigation ul li ul li a.latest');
	var $newest = $('#radiofilternavigation ul li ul li a[id='+fc+']');
	if($latest.length && !$newest.length)
		$latest.parent().parent().slideUp(speed);
	
	html5history && history.pushState({ path: $('#radiofilternavigation ul a[id='+fc+']').attr('href') }, '', $('#radiofilternavigation ul a[id='+fc+']').attr('href'));
	
	$('#radiofilternavigation ul a.latest').removeClass('latest');
	$('#radiofilternavigation ul a[id='+fc+']').addClass('latest');
	
	stopPromoteaser();
	$('#radiofilternavigation ul li.loading').removeClass('loading');
	var $bs = $('#cache .box').remove();
	$wall.isotope('insert', $bs.addTeaserEvents(), function(){
		$bs = null;
		$('.box:not(.nosort)', $wall).css({opacity:0.25}).addClass('ishistory');
		$('.'+fc).css({opacity:1}).removeClass('ishistory');
		
		//regisseurbox spezialfall
		if($('.box.regisseure').length){
			if($('ul li a.latest', $('a#id-5').parent()).length){
				$('.box.regisseure').css({opacity:1}).attr('rel',(addedElementsLength+1)*5);
			} else {
				var rel = $('.box.regisseure').attr('rel');
				$('.box.regisseure').attr('rel',rel/5);
			}
			$wall.isotope('updateSortData', $('.box', $wall));
			$wall.isotope({ sortBy : 'rel' });
			$wall.isotope('reLayout');
		}
		
		initDirectorSlider();
		initPromoteaser();
		html5history = (history && history.pushState) ? true : false;
	});	
};

$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length;
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
     if (this.complete || this.complete === undefined){
        var src = this.src;
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src+'?'+Math.random();
     }  
  });
  return this;
};

jQuery.fn.fadeToggle = function(speed, easing, callback) {
	if(isiPad){
		return this.toggle(0);
	}else{
    	return this.animate({opacity: 'toggle'}, speed, easing, callback);
	}
};

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

function log(t){try{console.log(t);}catch(e){ /*if($.browser.msie){alert(t);}*/ }};
