/**
 * ContextTeasers
 * Author: Matthias Orgler <matthias@orgler.de>
 * 
 * The namespace ContextTeasers contains methods to display context teasers in
 * the other rollos. 
 * 
 * Mark / unmark the active / inactive rollo by using markRolloAsActive() 
 * and markRolloAsInactive. The active rollo is the one from which the teaser
 * context is taken.
 * 
 * Call init() after each (navigating) click of the user to fade in and out 
 * the appropriate teasers in the rollos. 
 */

var ContextTeasers = {
	
	/* public methods 
	---------------------------------------------------------------------- */

	/** Show context teasers in other rollos */
	init: function() {
		//author: Andreas Pfau
		//logger.info("theaser initialization"); 
		//-------------
		
		
		ContextTeasers.logger("ContextTeasers.init()");
		activeRolloIndex = this.getActiveRolloIndex();
		
		// Return if no teasers are defined 
		// or if displaying teasers is suppressed 
		if ((activeRolloIndex == 0) || (this.getQueryVariable('show-teasers') == 'false')) {
			this.removeAllTeasers();
			log('show NO teasers');
			return;
		}
		
		// Get teaser content
		teaserTop = $('.rollo' + activeRolloIndex + ' .content-teaser-top');
		teaserBottom = $('.rollo' + activeRolloIndex + ' .content-teaser-bottom');
		
		// Links from within a teaser should not trigger any other teasers
		this.preventTeasersForLinksIn(teaserTop);
		this.preventTeasersForLinksIn(teaserBottom);
	
		// Get timing params for teasers
		fadin_top = parseInt(teaserTop.children().attr('fadin'));
		duration_top = parseInt(teaserTop.children().attr('duration'));
		fadin_bottom = parseInt(teaserBottom.children().attr('fadin'));
		duration_bottom = parseInt(teaserBottom.children().attr('duration'));
		
		// Move image before headlines
        if (!teaserTop.find(".fragment0 > .width-66px").size()) {
            teaserTop.find(".width-66px").insertBefore(".rollo" + activeRolloIndex + " .content-teaser-top .teaserHeadlines");
        }
        if (!teaserBottom.find(".fragment0 > .width-66px").size()) {
            teaserBottom.find(".width-66px").insertBefore(".rollo" + activeRolloIndex + " .content-teaser-bottom .teaserHeadlines");
		}
		
		// Add teasers to rollos
		switch(activeRolloIndex) {
			case 1:
				this.removeTeaserFromRollo(1);
				this.setTeaserForRollo(2, teaserTop, fadin_top, duration_top);
				this.setTeaserForRollo(3, teaserBottom, fadin_bottom, duration_bottom);
				break;
			case 2:
				this.setTeaserForRollo(1, teaserTop, fadin_top, duration_top);
				this.removeTeaserFromRollo(2);
				this.setTeaserForRollo(3, teaserBottom, fadin_bottom, duration_bottom);
				break;
			case 3:
				this.setTeaserForRollo(1, teaserTop, fadin_top, duration_top);
				this.setTeaserForRollo(2, teaserBottom, fadin_bottom, duration_bottom);
				this.removeTeaserFromRollo(3);
				break;
		}
		
		// Put section title on top of teaser
		$('.rollo-home > p').css('position', 'absolute');
		History.initContextTeaser();
	},

	/**
	 * Marks the rollo with rolloIndex as active
	 * @param rolloIndex
	 * @param rolloSizeAct rollo is only marked active, if this size is greater than 130px
	 * @return
	 */
	markRolloAsActive: function(rolloIndex, rolloSizeAct) {
		ContextTeasers.logger("ContextTeasers.markRolloAsActive("+rolloIndex+","+rolloSizeAct+")");
		if (rolloSizeAct > 130) {
			$(".rollo" + rolloIndex).addClass('active');
		}
	},
	
	/**
	 * Marks the rollo with rolloIndex as inactive (removes active flag)
	 * @param rolloIndex
	 * @return
	 */
	markRolloAsInactive: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.markRolloAsInactive("+rolloIndex+")");
		$(".rollo" + rolloIndex).removeClass('active');
	},
	
	
	/**
	 * Method to call from any place in the interaktiv flash to display a
	 * specified context teaser
	 * @param rolloIndex (1-3)
	 * @param ttContentId
	 * @return
	 **/
	showTeaserByContentId: function(rolloIndex,ttContentId) {
        ContextTeasers.logger("ContextTeasers.showTeaserByContentId("+rolloIndex+","+ttContentId+")");
        activeRolloIndex = this.getActiveRolloIndex();

        $(".rollo"+activeRolloIndex+" .content-teaser-top div[class*=content-element]").remove();
        $("#ce"+ttContentId).clone().appendTo(".rollo"+activeRolloIndex+" .content-teaser-top");
        
        teaserTop = $(".rollo"+activeRolloIndex+" .content-teaser-top");

        if (!teaserTop.find(".fragment0 > .width-66px").size()) {
            teaserTop.find(".width-66px").insertBefore(".rollo" + activeRolloIndex + " .content-teaser-top .teaserHeadlines");
        }
        fadin_top = parseInt(teaserTop.children().attr('fadin'));
		duration_top = parseInt(teaserTop.children().attr('duration'));
        this.setTeaserForRollo(rolloIndex, teaserTop, fadin_top, duration_top);
    },
	
	
	
	/* private methods
	---------------------------------------------------------------------- */
	
	timerShowTeaserInRollo: new Array(),
	timerHideTeaserInRollo: new Array(),
	
	/** 
	 * @return the index of the active rollo. 
	 */
	getActiveRolloIndex: function() {
		ContextTeasers.logger("ContextTeasers.getActiveRolloIndex()");
		MAX_ROLLOS = 4;
		for(i=1; i <=MAX_ROLLOS; i++) {
			active_rollos = $('.active.rollo' + i);
			if (active_rollos.size() > 0) return i;
		}
		return 0;
	},
	
	/**
	 * Show the teaser in the given rollo
	 * @param rolloIndex 1..4
	 * @param teaserElement a DIV element containing the teaser
	 * @param fadin seconds to wait before showing the teaser
	 * @param duration seconds until the teaser will be hidden
	 * @return
	 */
	setTeaserForRollo: function(rolloIndex, teaserElement, fadin, duration) {
		ContextTeasers.logger("ContextTeasers.setTeaserForRollo("+rolloIndex+","+teaserElement+","+fadin+","+duration+")");
		
		// Remove any old teasers
		this.removeTeaserFromRollo(rolloIndex);

		if (teaserElement.html()) {

			// Add new teaser (still hidden)
			wrapBegin = '<div class="context-teaser-rollo' + rolloIndex + '">';
			wrapEnd = '</div>';
			$('.rollo' + rolloIndex + ' .rollo-home').append( wrapBegin + teaserElement.html() + wrapEnd);
			$('.rollo' + rolloIndex + ' .subcontent').after(wrapBegin + teaserElement.html() + wrapEnd);
			
			$('.rollo' + rolloIndex + ' .closeTeaser').click(function() {
                ContextTeasers.hideTeaser(rolloIndex);
                return false;
            });


            // Set teaser click href
            url = teaserElement.find(".csc-textpic-text a").attr("href");
            target = teaserElement.find(".csc-textpic-text a").attr("target");
            
            //url = $('.rollo' + rolloIndex + ' div[class*=individualcontent_pi4] .csc-textpic-text a').attr("href");
            url = addPreSlash(addPostSlash(removeDomain(url)));

            // ShowSpecial für Interaktiv Flash
            if (target.length) { url += "showSpecial/"+target+"/"; showSpecial = target; }

            $('.rollo' + rolloIndex + ' div[class*=individualcontent_pi4]').attr("rel",url);

            $('.rollo' + rolloIndex + " div[class*=individualcontent_pi4]").click(function() {
                anchor = "";
                url = addPreSlash(addPostSlash($('.rollo' + rolloIndex + " div[class*=individualcontent_pi4]").attr("rel")));
                Google.track(url);
                $.historyLoad(url);
                return false;
            });

			// Schedule fade-in and fade-out
			this.clearTimers(rolloIndex);
			if(this.teasersAllowedInRollo(rolloIndex)) {
				this.timerShowTeaserInRollo[rolloIndex] = setTimeout('ContextTeasers.showTeaser(' + rolloIndex +  ')', fadin * 1000);
				if (duration > 0) this.timerHideTeaserInRollo[rolloIndex] = setTimeout('ContextTeasers.hideTeaser(' + rolloIndex + ')', (fadin * 1000) + (duration * 1000));
			}
			
		}
	},
	
	/**
	 * Stops all running timers for the rollo with rolloIndex
	 * @param rolloIndex
	 */
	clearTimers: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.clearTimers()");
		if (this.timerShowTeaserInRollo[rolloIndex]) clearTimeout(this.timerShowTeaserInRollo[rolloIndex]);
		if (this.timerHideTeaserInRollo[rolloIndex]) clearTimeout(this.timerHideTeaserInRollo[rolloIndex]);
	},
	
	/**
	 * Deletes any teasers from the rollo with the given rolloIndex
	 * @param rolloIndex
	 * @return
	 */
	removeTeaserFromRollo: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.removeTeaserFromRollo("+rolloIndex+")");
		this.teaserInRolloWithHome(rolloIndex).remove();
		this.teaserInRolloWithSubcontent(rolloIndex).remove();
	},
	
	/**
	 * Show the hidden teaser in rollo with index rolloIndex
	 * @param rolloIndex
	 * @param timeCode a timecode or other UID to identify this teaser instance
	 * @return
	 */
	showTeaser: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.showTeaser("+rolloIndex+")");
		this.teaserInRolloWithHome(rolloIndex).fadeIn(500);
		this.teaserInRolloWithSubcontent(rolloIndex).fadeIn(500);
	},
	
	/**
	 * Hide the teaser in rollo with index rolloIndex
	 * @param rolloIndex
	 * @param timeCode a timecode or other UID to identify this teaser instance 
	 * @return
	 */
	hideTeaser: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.hideTeaser("+rolloIndex+")");
		this.teaserInRolloWithHome(rolloIndex).fadeOut(500);
		this.teaserInRolloWithSubcontent(rolloIndex).fadeOut(500);
	},
	
	/**
	 * 
	 * @param rolloIndex
	 * @return the DIV of the rollo with rolloIndex, if the DIV has a .rollo-home inside (i.e. DIV has no content)
	 */
	teaserInRolloWithHome: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.teaserInRolloWithHome("+rolloIndex+")");
		return $('.rollo' + rolloIndex + ' .context-teaser-rollo' + rolloIndex);
	},
	
	/**
	 * 
	 * @param rolloIndex
	 * @return the DIV of the rollo with rolloIndex, if the DIV has a .subcontent inside (i.e. DIV has content already)
	 */
	teaserInRolloWithSubcontent: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.teaserInRolloWithSubcontent("+rolloIndex+")");
		return $('.rollo' + rolloIndex + ' .context-teaser-rollo' + rolloIndex);
	},
	
	removeAllTeasers: function() {
		ContextTeasers.logger("ContextTeasers.removeAllTeasers()");
		MAX_ROLLOS = 4;
		for(i=1; i <=MAX_ROLLOS; i++) {
			this.removeTeaserFromRollo(i);
		}	
	},
	
	/**
	 * Get the value of the param variable from the current window.location url
	 */
	getQueryVariable: function(variable) {
	  ContextTeasers.logger("ContextTeasers.getQueryVariable("+variable+")");
	  var query = window.location.href.substr(window.location.href.indexOf('?') + 1);
	  var vars = query.split("&");
	  for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == variable) {
	      return pair[1];
	    }
	  } 
	},
	
	/**
	 * Append the param definition to the URL (if it's not already there)
	 */
	addParam: function(url, param) {
		ContextTeasers.logger("ContextTeasers.addParam("+url+","+param+")");
		if (url.href.search(param) < 0) {
			url.href += '?' + param;
		}
	},
	
	/**
	 * Adds a param to each link in teaserElement to prevent it from triggering
	 * consequent teasers.
	 */
	preventTeasersForLinksIn: function(teaserElement) {
		ContextTeasers.logger("ContextTeasers.preventTeasersForLinksIn("+teaserElement+")");
/**
		links = teaserElement.find('a');
		for(i=0; i < links.length; i++) {
			this.addParam(links[i], 'show-teasers=false');
		}
*/

        var cturl = teaserElement.find("a").attr("href");
        if ((cturl) && (cturl.indexOf("show-teasers/false/") == -1)) {
    		teaserElement.find("a").attr("href",teaserElement.find("a").attr("href")+"show-teasers/false/");
        }
	},
	
	/**
	 * @return true, if displaying teasers is currently allowed for the rollo 
	 * with rolloIndex
	 */
	teasersAllowedInRollo: function(rolloIndex) {
		ContextTeasers.logger("ContextTeasers.teasersAllowedInRollo("+rolloIndex+")");
		return ($('.rollo' + rolloIndex + ' .no-teaser').size() == 0);
	},
	
	logger: function(logstring) {
		//log(logstring);
	}
	
};
