/**
 * AUDI JavaScript library: Teaser related stuff
 * 
 * @projectDescription	Teaser rotation
 * @namespace			teaser
 *
 * @author 				$Author: jbambauer $
 * @version				$Revision: 1 $
 * @copyright			NEUE DIGITALE GmbH, Berlin
 * 
 * @jslint: 2008-10-31
 * 
 * @file:				audi_ngw.dom.teaser.js
 */

/* create namespace */
audi_ngw.namespace(audi_ngw,'dom.teaser');

audi_ngw.dom.teaser.personalized = false;


audi_ngw.dom.teaser.deleteNetminingTeaser = function (aValidTeaser) {
	var notPersonalTeaser = [];

	for( i = 0; i < aValidTeaser.length; i++ ) {
		
		// if the teaser is a personalized one, we don't return it
		if( !jQuery(aValidTeaser[i]).hasClass('audi_teaser_personalization') ) {
			notPersonalTeaser.push(aValidTeaser[i]);
		}
		
	}
	
	return notPersonalTeaser;
	
};

audi_ngw.dom.teaser.netmining = function (aValidTeaser, $teaserContainer) {
	
	var teaserMetadata,
		i,
		j,
		//personalTeaser = jQuery(aValidTeaser).find('.audi_teaser_personalization').get(),
		frequency = audi_ngw.config.nmFrequency || 0.5,
		tmpFrequency = Math.random()
		personalTeaser = [];
		
	jQuery(aValidTeaser).each(function(){
		
		var $this = jQuery(this);
		if( $this.hasClass('audi_teaser_personalization') ) {
			personalTeaser.push($this.get());
		}				
		
	});
	//personalTeaser = personalTeaser[0];

		
	if( true === audi_ngw.dom.teaser.personalized || 0 == jQuery(personalTeaser).length ) {
		return audi_ngw.dom.teaser.deleteNetminingTeaser(aValidTeaser);
	}
	
	if( tmpFrequency > frequency ) {
		return audi_ngw.dom.teaser.deleteNetminingTeaser(aValidTeaser);
	}
	
	if( typeof(audi_ngw.config.nmCookieName) != 'undefined' && $teaserContainer.hasClass('audi_personalization') ) {
		
		var personalCookie = jQuery.cookie(audi_ngw.config.nmCookieName),
			cookieData = [],
			tmpCookieData;
		
		if( !personalCookie ) {
			return audi_ngw.dom.teaser.deleteNetminingTeaser(aValidTeaser);
		}
		
		personalCookie = personalCookie.split('|');
		
		for( i = 0; i < personalCookie.length; i++ ) {
			tmpCookieData = personalCookie[i].split('=');
			cookieData[i] = {};

			if( !tmpCookieData[0].search('carlinegroup') ) {
				cookieData[i].key = 'carlinegroup';
			} else {
				cookieData[i].key = 'carline';
			}
						
			tmpCookieData = tmpCookieData[1].split(',');
			cookieData[i].val = tmpCookieData[0];
			cookieData[i].interest = tmpCookieData[1];
		}

		for( i = 0; i < personalTeaser.length; i++ ) {
						
			teaserMetadata = jQuery(personalTeaser[i]).metadata();
		
			if( teaserMetadata.personalization ) {
				
				for( j = 0; j < cookieData.length; j++ ) {
									
					if( cookieData[j].key == 'carline' && teaserMetadata.personalization.carline == cookieData[j].val && cookieData[j].interest >= teaserMetadata.personalization.interest ) {
						
						audi_ngw.dom.teaser.personalized = true;
						return aValidTeaser[i];

					} else if( cookieData[j].key == 'carlinegroup' && teaserMetadata.personalization.carlinegroup == cookieData[j].val && cookieData[j].interest >= teaserMetadata.personalization.interest ) {
						
						audi_ngw.dom.teaser.personalized = true;
						return aValidTeaser[i];
						
					} 
					
				}	

			}
						
		}
		
	}

	return audi_ngw.dom.teaser.deleteNetminingTeaser(aValidTeaser);
	
};



audi_ngw.dom.teaser.showToday = function (weekDayFrom, weekDayTo, dayTimeFrom, dayTimeTo) {
	
	var dateNow = new Date(),
		weekdayNow = dateNow.getDay(),
		result = false;


	
	// first let's find out, if the weekday is ok
	if( weekDayFrom < weekDayTo ) {
		if( weekDayFrom <= weekdayNow && weekDayTo >= weekdayNow ) {
			result = true;
		}
	} else if( weekDayFrom == weekDayTo ) {
		if( weekDayFrom == weekdayNow ) {
			result = true;
		}
	} else {
		if( weekDayFrom <= weekdayNow || weekDayTo >= weekdayNow ) {
			result = true;
		}
	}

	// now let's look for the time of the day
	if( true === result ) {
		
		var timeFrom = dayTimeFrom.split(':'),
			timeTo = dayTimeTo.split(':'),
			syntaxOk = false;
			
		if( 3 === timeFrom.length && 3 === timeTo.length ) {

			syntaxOk = true;
			
			var tmpDateFrom = new Date();
			var tmpDateTo = new Date();

			tmpDateFrom.setHours(parseInt(timeFrom[0], 10));
			tmpDateFrom.setMinutes(parseInt(timeFrom[1], 10));
			tmpDateFrom.setSeconds(parseInt(timeFrom[2], 10));				
			
			tmpDateTo.setHours(parseInt(timeTo[0], 10));
			tmpDateTo.setMinutes(parseInt(timeTo[1], 10));
			tmpDateTo.setSeconds(parseInt(timeTo[2], 10));	
						
		}

		if( true === syntaxOk && tmpDateFrom <= dateNow && tmpDateTo >= dateNow ) {
				result = true
		}
		
		
		
		
	}
	
	return result;
};


audi_ngw.dom.teaser.control_home = function($teaserContainer) {
	var aValidTeaser = [];
	var aShowTeaser = [];
	
	var dateNow = (audi_ngw.dom.teaser.sDate ? new Date(audi_ngw.dom.teaser.sDate.replace(/_/g," ")) : null) || new Date();
	var weekdayNow = dateNow.getDay();
	
	// erstmal alle validen Teaser raussuchen
	jQuery('li.teaser', $teaserContainer).each(function() {
		var teaser = jQuery(this);
		var teaserMeta = teaser.metadata();
		var isValid = false;

		if (
			'undefined' !== typeof(teaserMeta.validFromDay) &&
			'undefined' !== typeof(teaserMeta.validToDay) &&
			'undefined' !== typeof(teaserMeta.validFrom) &&
			'undefined' !== typeof(teaserMeta.validTo)
		) {
			
			isValid = audi_ngw.dom.teaser.showToday(teaserMeta.validFromDay, teaserMeta.validToDay, teaserMeta.validFrom, teaserMeta.validTo); 
/*			
			var timeFrom = teaserMeta.validFrom.split(':');
			var timeTo = teaserMeta.validTo.split(':');
			if( 3 === timeFrom.length && 3 === timeTo.length ) {
				var tmpDateFrom = new Date();
				var tmpDateTo = new Date();
				tmpDateFrom.setHours(parseInt(timeFrom[0], 10));
				tmpDateFrom.setMinutes(parseInt(timeFrom[1], 10));
				tmpDateFrom.setSeconds(parseInt(timeFrom[2], 10));				
				tmpDateTo.setHours(parseInt(timeTo[0], 10));
				tmpDateTo.setMinutes(parseInt(timeTo[1], 10));
				tmpDateTo.setSeconds(parseInt(timeTo[2], 10));

				

				if (teaserMeta.validFromDay <= weekdayNow && teaserMeta.validToDay >= weekdayNow && tmpDateFrom <= dateNow && tmpDateTo >= dateNow) {
					isValid = true;
				}

			}
*/
		} else if (
			'undefined' === typeof(teaserMeta.validFromDay) &&
			'undefined' === typeof(teaserMeta.validToDay) &&
			'undefined' !== typeof(teaserMeta.validFrom) &&
			'undefined' !== typeof(teaserMeta.validTo)
		) {
			if( new Date(teaserMeta.validFrom) <= dateNow && new Date(teaserMeta.validTo) >= dateNow ) {
				isValid = true;
			}
		} else if (
			'undefined' === typeof(teaserMeta.validFromDay) &&
			'undefined' === typeof(teaserMeta.validToDay) &&
			'undefined' === typeof(teaserMeta.validFrom) &&
			'undefined' === typeof(teaserMeta.validTo)
		) {
			isValid = true;
		}
		
		if (isValid === true) {
			if (teaserMeta.exclusive === 'true') {
				aValidTeaser = [];
				aValidTeaser.push(teaser);
				return false;
			} else {
				aValidTeaser.push(teaser);
			}
		}
	});

	// check for netmining cookie for personalization

	aValidTeaser = audi_ngw.dom.teaser.netmining(aValidTeaser, $teaserContainer);


	// get metadata from the flash-container
	var flashVars = {};
	var $teaserContainerMeta = $teaserContainer.metadata();
	flashVars.xmldata = $teaserContainerMeta.xml;
	var flashVersion = ( 'undefined' == typeof($teaserContainerMeta.version) ) ? audi_ngw.flash.sNeededFlashVersion : $teaserContainerMeta.version;
	
	// in aValidTeaser sind jetzt die sortierten Teaser, die IDs und Links der ersten vier mÃ¼ssen ans Flash Ã¼bergeben werden
	// wenn kein flash
	// => zufÃ¤lligen teaser anzeigen
	if( audi_ngw.flash.hasFlash !== true || !swfobject.hasFlashPlayerVersion(flashVersion) ){

		var numberOfTeaserToShow = Math.ceil(Math.random() * 1000) % aValidTeaser.length;	
		jQuery(aValidTeaser).eq(numberOfTeaserToShow)[0].addClass('active').parent().show();

		return false;

	// wenn IE6 und Option im CMS gesetzt (class=audi_no_flash_ie6)
	// => immer den ersten Teaser anzeigen
	} else if( jQuery.browser.msie === true && parseFloat(jQuery.browser.version) < 6.5 && $teaserContainer.hasClass('audi_no_flash_ie6') ) {
		
		$teaserContainer.find('li:first').addClass('active').parent().show();
		return false;
		
	}


	
	// ansonsten per flash einblenden
	
	jQuery(aValidTeaser).each(function(index, domElement) {
		if (index < 4) {
			var flash = jQuery(this);
			var ctaLink = jQuery('a', flash);
			var flashMeta = flash.metadata();
			flashVars['teaserId'+index] = flashMeta.teaser_id;	
			flashVars['ctaLink'+index] = escape('<a href="'+ctaLink.attr('href')+'" rel="'+ctaLink.attr('rel')+'"></a>');
		} else {
			return false;
		}
	});
	
	
	
	
	var oParams = {};
	oParams.wmode = 'transparent';
	oParams.allowScriptAccess = 'always';
	
	var id = audi_ngw.dom.identify(jQuery('#audi_teaser_control_home').html('<div />').find('div'));
	flashVars.parent_id = id;
	
	

	audi_ngw.flash.embed($teaserContainerMeta.swf, id, '100%', '100%', flashVersion, "", flashVars, oParams);
	if (typeof audi_ngw.flash.objects === 'undefined') {
		audi_ngw.flash.objects = [];
	}
	audi_ngw.flash.objects.push(id);
};

audi_ngw.dom.teaser.control = function($teaserContainer){
	var aValidTeaser = [];
	var aInvalidTeaser = [];

	// Date format: 2 Jan 2000 00:00:00 GMT
	// if audi_ngw.dom.teaser.sDate is already set (preview), it comes in as get parameter spaces escaped by _
	// we replace them and create a new date from the string
	// if audi_ngw.dom.teaser.sDate we just create a new date
	var dateNow = (audi_ngw.dom.teaser.sDate ? new Date(audi_ngw.dom.teaser.sDate.replace(/_/g," ")) : null) || new Date();
	var weekdayNow = dateNow.getDay();


	
	// check vor valid dates
	$teaserContainer.children().each(function() {
		
		var $item = jQuery(this);
		var data = $item.metadata();
		
		$item.removeClass('current');

		//case 2: this teaser is valid from a time on a weekday to another time on a weekday
		if( 'undefined' !== typeof(data.validFromDay) && 'undefined' !== typeof(data.validToDay) && 'undefined' !== typeof(data.validFrom) && 'undefined' !== typeof(data.validTo) ) {
			
			if( true === audi_ngw.dom.teaser.showToday(data.validFromDay, data.validToDay, data.validFrom, data.validTo) ) {
				aValidTeaser.push($item);
			}
/*			
			var timeFrom = data.validFrom.split(':');
			var timeTo = data.validTo.split(':');
			var syntaxOk = false;
			if( 3 === timeFrom.length && 3 === timeTo.length ) {

				syntaxOk = true;
				
				var tmpDateFrom = new Date();
				var tmpDateTo = new Date();

				tmpDateFrom.setHours(parseInt(timeFrom[0], 10));
				tmpDateFrom.setMinutes(parseInt(timeFrom[1], 10));
				tmpDateFrom.setSeconds(parseInt(timeFrom[2], 10));				
				
				tmpDateTo.setHours(parseInt(timeTo[0], 10));
				tmpDateTo.setMinutes(parseInt(timeTo[1], 10));
				tmpDateTo.setSeconds(parseInt(timeTo[2], 10));	
							
			}

			if( true === syntaxOk && data.validFromDay <= weekdayNow && data.validToDay >= weekdayNow && tmpDateFrom <= dateNow && tmpDateTo >= dateNow ) {
				
					aValidTeaser.push($item);
				
			} 
*/				
			
			
		// case 1: this teaser is valid from a specific date to another specific date
		} else if( 'undefined' === typeof(data.validFromDay) && 'undefined' === typeof(data.validToDay) && 'undefined' !== typeof(data.validFrom) && 'undefined' !== typeof(data.validTo) ) {

			if( new Date(data.validFrom) <= dateNow && new Date(data.validTo) >= dateNow ) {
				aValidTeaser.push($item);
			} 
		
		// case 0: this teaser is always valid if no options are specified
		} else if( 'undefined' === typeof(data.validFromDay) && 'undefined' === typeof(data.validToDay) && 'undefined' === typeof(data.validFrom) && 'undefined' === typeof(data.validTo) ) {
			
			aValidTeaser.push($item);
			
		} 
		
	});
	

	if( $teaserContainer.hasClass('con_teaser_distributor_2') ) {
		jQuery(aValidTeaser).each(function(){
			jQuery(this).addClass('valid');
		});
		if( 3 < aValidTeaser.length ) {
			$teaserContainer.addClass('con_teaser_distributor_2_large');
		}
	}
	
	// check for netmining cookie for personalization
	aValidTeaser = audi_ngw.dom.teaser.netmining(aValidTeaser, $teaserContainer);

	// class current marks the valid teaser, it is randomly chosen from the valid teaser array
	jQuery(aValidTeaser[audi_ngw.getRandomNumber(aValidTeaser.length)]).addClass("current");
	
};

/**
 * Starts rotation inside $elContainer by setting an interval calling audi_ngw.dom.teaser.rotate($elContainer).
 * Relies on HTML-structure:
 * <CONTAINER>
 *  <ul>
 *   <li><a>
 *  </ul>
 *  <a>
 * </CONTAINER>
 * @see audi_ngw.dom.teaser.rotate($e lContainer)
 * @param {Element} jQuery extendes element $elContainer
 * @return {Void}
 */
audi_ngw.dom.teaser.startRotation = function($elContainer) {

	if( 0 !== $elContainer.find('.GCQTinyNewBar').size() ) {
		return false;
	}

	// set interval
	audi_ngw.dom.teaser._timerRotation = window.setInterval(
		function () {
			audi_ngw.dom.teaser.rotate($elContainer);
		},
		audi_ngw.dom.teaser.iRotationMs);
};

/***
 * Stops rotation by clearing the interval 
 * @return {Void}
 */
audi_ngw.dom.teaser.stopRotation = function() {
	audi_ngw.dom.teaser._timerRotation = audi_ngw.clearTimer(audi_ngw.dom.teaser._timerRotation);
};

/**
 * Rotates directly to a teaser inside $elContainer.
 * Brigde to audi_ngw.dom.teaser._doRotate
 * Relies on HTML-structure:
 * <CONTAINER>
 *  <ul>
 *   <li><a>
 *  </ul>
 *  <a>
 * </CONTAINER>
 * Copies anchors inside the unordered list, rotates them outside the list due to sliding effect ()
 * @see audi_ngw.dom.teaser._doRotate($elContainer)
 * @param {String} Container id 
 * @param {Number} Index, starting at zero
 * @return {Void}
 */
audi_ngw.dom.teaser.rotateTo = function(_sId, _iIndex) {
	// call rotation method
	audi_ngw.dom.teaser._doRotate(jQuery("#"+_sId),_iIndex);
};

/**
 * Rotates teaser inside $elContainer.
 * Brigde to audi_ngw.dom.teaser._doRotate
 * Relies on HTML-structure:
 * <CONTAINER>
 *  <ul>
 *   <li><a>
 *  </ul>
 *  <a>
 * </CONTAINER>
 * Copies anchors inside the unordered list, rotates them outside the list due to sliding effect ()
 * @see audi_ngw.dom.teaser._doRotate($elContainer)
 * @param {Element} jQuery extendes element $elContainer
 * @return {Void}
 */
audi_ngw.dom.teaser.rotate = function($elContainer) {
	// force jQuery extensions
	$elContainer = jQuery($elContainer);
	// force and store id 
	var _sId = audi_ngw.dom.identify($elContainer);
	// call rotation method
	audi_ngw.dom.teaser._doRotate($elContainer,null);
};

/**
 * Sets rotation options by using the container id as identifier
 * @param {String} _sId
 * @return {Object} Rotation options 
 */
audi_ngw.dom.teaser._setRotationOptionsbyId = function(_sId) {
	// get container
	var $elContainer = jQuery('#'+_sId);
	// set options if necessary 
	if (!audi_ngw.dom.teaser._aRotation[_sId]) {
		audi_ngw.dom.teaser._aRotation[_sId] = {
			sId: _sId, // id
			iCurrent: 0, // current teaser's index 
			iMax: ($elContainer.find('ul li a').size() - 1) // max index 
		};
	}
	return audi_ngw.dom.teaser._aRotation[_sId];
};

/**
 * Rotation method.
 * Relies on HTML-structure:
 * <CONTAINER>
 *  <ul>
 *   <li><a>
 *  </ul>
 *  <a>
 * </CONTAINER>
 * Copies anchors inside the unordered list, rotates them outside the list due to sliding effect ()
 * @private
 * @param {Object} $elContainer
 * @param {Object} _iIndex
 * @return {Void}
 */
audi_ngw.dom.teaser._doRotate = function($elContainer, _iIndex) {
	// get link next to ul
	var _sId = $elContainer.attr('id');
	// set options
	audi_ngw.dom.teaser._setRotationOptionsbyId(_sId);
 	// get current teaser 
	var _$elCurrentTeaser = $elContainer.find('ul + a');
	// remove all links except the "slide button", remove the current teaser element
	_$elCurrentTeaser
		.not('.slide_button')
		.remove()
		.end()
		.remove();
	// get the next teaser's index, use supplied (-1,because it'll be increased)  or stored
	_iIndex = (_iIndex || _iIndex === 0 ) ? _iIndex - 1 : audi_ngw.dom.teaser._aRotation[_sId].iCurrent;
	audi_ngw.dom.teaser._aRotation[_sId].iCurrent = _iIndex = (_iIndex >= 0 && _iIndex < audi_ngw.dom.teaser._aRotation[_sId].iMax) ? ++_iIndex : 0;
	// set index at options 
	//	audi_ngw.dom.teaser._aRotation[_sId].iCurrent = ( _iIndex === 0 ) ? 0 : _iIndex;
	// find next teaser inside the dom 
	$elContainer
		.find('ul li a')
		.eq(_iIndex)
		// clone and set css 
		.clone(true)
		.css({
			display: 'none'
//			,
//			position: 'absolute',
//			bottom: '10px'
		})
		// fade in 
		.appendTo($elContainer)
		.fadeIn(650);
};

 
 /**
 * Custom Event: wil be fired as soon as we filled the ajax-content into the modal layer, just before "xhrReallocate"
 * @param {Object} event
 * @param {Object} xhr
 */
audi_ngw.dom.teaser.onAjaxModalContentReady = function(event,xhr){
	// check if this xhr-response contains valid content
	if (!audi_ngw.url.hasXHRContent(xhr,event.timeStamp)) {return false;}
	//audi_ngw.log("-> "+audi_ngw.event.ajaxModalContentReadyCount+" EVENT - ajaxModalContentReady:audi_ngw.dom.teaser.onAjaxModalContentReady",arguments);
	// execute funtions on new content
 	
	var $scope = jQuery('#'+audi_ngw.url.getContentId());

	// start rotation
	if (jQuery('.more_teaser_news').size()) {
		audi_ngw.dom.teaser.startRotation(jQuery('.more_teaser_news'));
	}
	
	
	$scope.find('.audi_teaser_control').each(function() {
		audi_ngw.dom.teaser.control(jQuery(this));
	});
	
	$scope.find('#audi_teaser_control_home > ul').each(function() {
		audi_ngw.dom.teaser.control_home(jQuery(this));
	});
	
 	// trigger event 
	audi_ngw.event.trigger('ajaxModalContentPrepared');
};


 
/**
 * Constructor
 * @param {Object} options
 * @return {Void}
 */	
audi_ngw.dom.teaser.initialize = function(options){

	this.__className =  'audi_ngw.dom.teaser';
	this.__classVersion= '1.0';

	// initialize rotation timer
	audi_ngw.dom.teaser._timerRotation = null;
	// set rotation timeout 
	audi_ngw.dom.teaser.iRotationMs = 5000;
	
	// PREVIEW sets this.sDate to value of the get parameter preview_date
	// if parameter is not set this.sDate = null
	this.sDate = audi_ngw.edit ? audi_ngw.url.getParam('preview_date') : null;
	audi_ngw.dom.teaser._aRotation = [];

	// all elements in containers with class .audi_teaser_control will be contolled	
	jQuery('.audi_teaser_control').each(function() {
		audi_ngw.dom.teaser.control(jQuery(this));
	});
	
	jQuery('#audi_teaser_control_home > ul').each(function() {
		audi_ngw.dom.teaser.control_home(jQuery(this));
	});

	// register ajaxModalContentReady event
	audi_ngw.event.bind('ajaxModalContentReady.domTeaser',audi_ngw.dom.teaser.onAjaxModalContentReady);
	
	// start rotation
	if (jQuery('.more_teaser_news').size()) {
		audi_ngw.dom.teaser.startRotation(jQuery('.more_teaser_news'));
	}
	
};


