if(window.loadFirebugConsole) {
	window.loadFirebugConsole(); 
}

$(document).ready(function(){
	checkFrames();
	
	clearSearch.init();
	sidebar.init();
	initCategoryRadios();

	if( $('body').hasClass('start') ){
		setTimeout('carouselTimer()', 5000);
	}
	
	$.ie6CSSHover();
	
	if( $('body').hasClass('start') || $('body').hasClass('mag') ){
		
		if( $('body').hasClass('start') ){
			/* Playlist */
			var Programm = new Ccarousel();
			Programm.init('Programm', Programm, 'playlist-de');
		}
		
		/* Text-News */
		var news = new Ccarousel();
		news.init('news', news, 'hor_small'); 
		
		/* Videos */
		var videos = new Ccarousel();
		videos.init('videos', videos, 'hor_small'); 
	}
	
	jcHighlight.init();
	jcHighlight.run();
	
});

function checkFrames() {
	hasFrame = top.frames.length;
	myHost = window.location.host;
	myLocation = window.location.href;
	myTarget = 'http://www.bmw.de/de/de/insights/news/current/content.html?go2=';
	if(navigator.userAgent.toUpperCase().indexOf('IPAD')==-1 && myHost != 'localhost:8080' &&myHost != 'localhost:9090' && myHost != 'dwintegration.sevenload.com:8081' && myHost != 'dwintegration.sevenload.com:8080' && myHost != '78.35.17.149' ){
		if(hasFrame == 0)
			window.location.href = myTarget + myLocation;
	}
}

function ArchivRequest(conf) {
	var conf = conf;
	this.load = function (obj) {
		startAjaxLoading(conf.resultContainer);
		$(conf.form).hide();
		$.ajax({
			  url: (conf.url() ? conf.url() : obj.href),
			  type: "POST",
			  cache: true,
			  data: (conf.data() ? conf.data() : ''),
			  dataType: "html",
			  success: function(result){
				$(conf.form).show();
				if(conf.resultContainer) {
					 $(conf.resultContainer).html(result);
				 }
			  },
			  error:  function() {
				$(conf.form).show();
			  }
		});
		return false;
	}
}

function startAjaxLoading(container){
	var loaderHTML = '<div class="loader"><img src="/de/images/icon/loader.gif" alt="loading..." /></div>'
	
	$(container).empty().html(loaderHTML);
}

function completeAjaxLoading(container){
	alert('START LOADING...');
}

function toggleProgramsList () {

	if (  $('label[for=radio1_3]').hasClass('active') ) {
		$('#formSearchFilterArchive').find('.cElement').eq(1).hide();
	} else {
		$('#formSearchFilterArchive').find('.cElement').eq(1).show();
	}

}

function initCategoryRadios () {
	$('#cathegory label').bind("click", function(e){
		window.setTimeout(function () {
			if (  $('label[for=radio1_3]').hasClass('active') ) {
				$('#formSearchFilterArchive').find('.cElement').eq(1).hide();
			} else {
				$('#formSearchFilterArchive').find('.cElement').eq(1).show();
			}														
		}, 50)																				 
		if($(this).hasClass('active')) {
			return false;		
		}
	});
}
//----------------------------------------------------------------------------------
var clearSearch = {
	init: function () {
		var searchField = $('#Search'); 
	
		$(searchField).find('input').focus(function(){
		  $(this).val('');
		});

		$(searchField).find('input').blur(function(){
		  var val = $(this).val();
		  if(val === '')
			  $(this).val('Suche');
		});
	}
}


//----------------------------------------------------------------------------------
var sidebar = {
	init: function() {
	  $(".cElement").find("a.toggle").click(function () {
		
			if ( $(this).hasClass('active') ) {
				$(this).next().slideUp("slow");
				$(this).removeClass("active");
				return false;
			}else{
				$(this).next().slideDown("slow");
				$(this).addClass("active");
				return false;
			}
		});
	}
}


//----------------------------------------------------------------------------------
function picDisplay( inObj ) {
	var thumbControl = $('#ThumbControl');
	var picDisplayCaption = $('#PicDisplayCaption');
	var picDisplay = $('#PicDisplay');
	
	$(thumbControl).find('.active').removeClass('active');
	$(thumbControl).find('a').each( function() {
		if( inObj.href == this.href ) {
			$(this).addClass('active');
		}
	});																			
	$(picDisplayCaption).text( $(inObj).next().text() );	
	$(picDisplay).find('img')[0].src = inObj.href;
	return false;
}

//----------------------------------------------------------------------------------

function filterArchive() {
	var formSearchFilter = $('#formSearchFilterArchive');
	$(formSearchFilter).find('.checkbox').find('a').addClass('active');

	$(formSearchFilter).find('#cathegory').find('label').bind('click', function(e) {
		
		currentElementFor = $(e.target).attr('for');
		$(e.target).parent().find('label').each(function(i) {

			if(currentElementFor != $(this).attr('for')) {
				$(this).attr('class', 'inactive');	
			}
			else {
				$(this).attr('class', 'active');
			}
		});
	})

	$(formSearchFilter).find('.checkbox').bind('click', function() {
	
		if( $(this).find('label').hasClass('active') ){
			$(this).find('label').removeClass("active");
			
			$(formSearchFilter).find('.radio').find('label').removeClass('active');
		}else{
			$(this).find('label').addClass("active");
		}
	});
}

//----------------------------------------------------------------------------------
var firstLoad = 0;
var CarouselAutoScroll = true;
var CarouselSlideShowTimer = false;
var jcHighlight = {
	init: function () {
		//Slideshow
		var myHandler = $('.mycarousel li').find('.listener');
		
		$(myHandler).css({ background: 'red', 'opacity' : 0}).unbind("mouseover").bind("mouseover",function(e){
			$(this).each( function() {
				if(e.target.tagName == 'A'){
					CarouselSlideShow(e.target.parentNode);
				}				
			})
		});
		
		$(myHandler).unbind("mouseout").bind("mouseout",function(e){
			$(this).each( function() {
				if(e.target.tagName == 'A'){
					CarouselStopSlideShow();
				}
			})
		});
	},
	
	selectNew: function(videoId){

		$('.mycarousel').find('li').find('div').removeClass('active');
		$('.mycarousel li').find('.' + videoId).addClass('active');

		$('.videoCarousel').find('div').removeClass('active');
		$('.videoCarousel').find('.videoId_' + videoId).addClass('active');
		
		if( firstLoad ){
			if( CarouselAutoScroll ) {
				$('.jcarousel-next').trigger('click');
			}
		} else {			
			//$("#videos").load('action1.do?videoID=' + videoId );
			//$("#configurator").load('action2.do?videoID=' + videoId );			
		}
		/*
		if(firstLoad >= 1 && CarouselAutoScroll == true) {
			$('.jcarousel-next').trigger('click');
		}
		*/
		firstLoad++;

		lastSelectedCarouselTeaser = videoId;
	},

	run: function () {
		$('.jcarousel-next').unbind('mousedown').bind('mousedown', function() {
			CarouselAutoScroll = false;
		});
		
		$('.jcarousel-prev').unbind('mousedown').bind('mousedown', function() {
			CarouselAutoScroll = false;
		});
		
		$('.jcarousel-next').click(function(){
			jcHighlight.init();
		});

		$('.jcarousel-prev').click(function(){
			jcHighlight.init();
		});
	}
}


//----------------------------------------------------------------------------------


var scrollTextCarouselTimer = false;
var scrollVideoCarouselTimer = false;

function scrollCarousel(obj){
	scrollVideoCarouselTimer = setTimeout(function(){ scrollCarousel(obj) }, 7500);
	$('#news').find('.newsTeaserHeadline').text($('.mycarousel').find('#teaserHeadline').val());
	obj.next();
}

function carouselTimer(){
	setTimeout(function(){ scrollCarousel(carouselTimerObjects[0]) }, 5000);
	setTimeout(function(){ scrollCarousel(carouselTimerObjects[1]) }, 10000);
}


function CarouselSlideShow(obj){
	CarouselSlideShowTimer = setTimeout(function(){ CarouselSlideShow(obj) }, 1000);
	
	var firstImage = $(obj).find('img:first');
	var lastImage =  $(obj).find('img:last');
	
	$(lastImage).after(firstImage);
} 

function CarouselStopSlideShow(){
	clearTimeout(CarouselSlideShowTimer);
}

//----------------------------------------------------------------------------------------

function trackViews(id){
	 $('#trackVideo').load('increaseViewCount.do?articleID=' + id);
} 

function trackRating(id, rating){
	 $('#trackVideo').load('articleRating.do?articleID=' + id + '&rating');
} 

//----------------------------------------------------------------------------------

var carouselTimerObjects = new Array();
var globalJcarouselObj = false;
var startPos = false;
var carouselSize = false;

function Ccarousel() {
	this.init = function( obj_id, obj, type ){
		startPos = 1;
		
		if(type != 'hor_thmbs'){
			$('#' + obj_id).find('.teaserList .teaser').each( function () {
				myHTML = $(this).html();
				if( $(myHTML).hasClass('active') ){
					startPos = $(myHTML).attr('class');
					startPos = startPos.split(" ");
					startPos = parseInt(startPos[0].substr(14));
				}
			})
		}
		this.startCarousel(obj_id, startPos);
 	},
 	
 	this.startCarousel = function(obj_id, startPos){
 		carouselSize = $('#' + obj_id).find('.teaserList').find('.teaser').length;
 		
 		if( obj_id == 'Programm'){
 			wrap = null;
 			vertical = true;
 			foobar = '{onAfterAnimation: lastItem}';
 		}
 		else{
 			wrap = 'circular';
 			vertical = false;
 			foobar = '';
 		}
 		if( obj_id == 'ThumbControl') {
 			wrap = null;
 		}
 		
 		$('#' + obj_id).find('.mycarousel').jcarousel({
				start: startPos,
				scroll: 1,
				size: carouselSize,
				animation: 700,
				vertical: vertical,
				wrap: wrap,
				itemVisibleInCallback: {onBeforeAnimation: itemVisibleInCallback},
				itemVisibleOutCallback: {onAfterAnimation: itemVisibleOutCallback},
				itemLastInCallback: eval(foobar)
		}, obj_id);
 	}
}

lastItem = function(carousel, item, i, state) {
	var programm = $('#Programm');
	
	tempSize = $(programm).find('.teaserList').find('.teaser').length;
	activeItem = $(item).find('div.active').hasClass('active');
	
	if(carousel.obj_id == 'Programm'){
		if(i == tempSize){
			if(activeItem) {
				$(programm).find('.jcarousel-next').trigger('click');
			}
		}
		else{
			$(programm).find('.jcarousel-next').show();
		}
	}

}


itemVisibleInCallback = function(carousel, item, i, state, evt){
	var idx = carousel.index(i, $('#' + carousel.obj_id).find('.teaserList').find('.teaser').length );
	carousel.add(i, getItemHTML(idx, carousel.obj_id, carousel) );

 	if( carousel.obj_id == 'Playlist'){
 		jcHighlight.init();
		checkItems(carousel);
	}
 	if( carousel.obj_id == 'ThumbControl'){
		checkItems(carousel);
	}
 	
	if( $('body').hasClass('start') ){
		if( carousel.obj_id == 'news'){
	 		carouselTimerObjects[0] = carousel;
		}
	 	
	 	if( carousel.obj_id == 'videos'){
	 		carouselTimerObjects[1] = carousel;
		}
	}
 	return;
}

itemVisibleOutCallback = function(carousel, item, i, state, evt){
  carousel.remove(i);
}

getItemHTML = function(item, obj_id){
	if(obj_id != 'Programm'){
		var total = $('#' + obj_id).find('.teaserList').find('.teaser').length;		    
		var pageCounter = "<span>" + item + " / " + total + "</span>";
		$('#' + obj_id).find('.pageCounter').html(pageCounter);
	}
	
	teaser = $('#' + obj_id).find('.teaserList').find('.teaser').get(item-1);

	return $(teaser).html();
}

checkItems = function(carousel) {
	var myItems = $('#' + carousel.obj_id).find('.teaserList').find('.teaser').length;

	if(myItems < 5){
		var i = 1;

		$('.mycarousel .jcarousel-item').each( function() {
			if(i > myItems) {
				$(this).remove();
			}
			i++;
		})

		$('.jcarousel-prev').hide();
		$('.jcarousel-next').hide();
	}
}


function bookmarkItem(inUrl, inTitle, inDescription , inBookmarkService) {

	inUrl = encodeURIComponent(inUrl);

	switch(inBookmarkService) {
		case 'digg':
			window.open('http://digg.com/remote-submit?phase=2&url='+inUrl+'&title='+inTitle+'&bodytext='+inDescription);
			break;
		case 'delicious':
			window.open('http://del.icio.us/post?&url='+inUrl+'&title='+inTitle+'&notes='+inDescription);
			break;
		case 'facebook':
			window.open('http://www.facebook.com/sharer.php?u='+inUrl+'&t='+inTitle);
			break;
		case 'mrwong':
			window.open('http://www.mister-wong.com/index.php?action=addurl&bm_url='+inUrl+'&bm_description='+inTitle);
			break;
		case 'twitter':
			window.open('http://twitter.com/home?status='+inUrl);
			break;
		case 'webnews':
			window.open('http://www.webnews.de/einstellen?url='+inUrl+'&title='+inTitle);
			break;
        case 'web_news':
			window.open('http://www.webnews.de/einstellen?url='+inUrl+'&title='+inTitle);
			break;
	}
	return false;
}


//----------------------------------------------------------------------------------------

function openLayer(targetLayer) {
	$('.fadeOut').show();
	$(targetLayer).css('display', 'block')
}