
/**
 * Teaser class
 * Manages configuration and 
 * displaying of the top teaser
 * including the match center
 */
function Teaser() {
	// to shorten call for gallery
	/*
	if(params != null && params.shop){
	    params = {
		   autocycle    : true,
		   navigation   : true,
		   
		   clazz        : "shopImg",
		   template     : "shop",
             subtemplate  : "shopEl",
		   tooltip      : null,
		   imageSlider  : false,
		   dotSlider    : true
        };
	}
	if(params != null && params.gallery){
	    params = {
		   autocycle    : false,
		   navigation   : true,
		   
		   clazz        : "galleryImg",
		   template     : "gallery",
           subtemplate  : "galleryEl",
		   tooltip      : null,
		   imageSlider  : true,
		   dotSlider    : false
        };
	}
	*/
    //this.construct(params);    
//}

/**
 * Class itself. The teaser converts
 * images of a defined class into a sliding
 * teaser.
 * The parameter Object may contain
 * following items:
 *
 * {
 *    clazz        : "teaserImg" -> the image class to observe
 *    attributes   :             -> which attributes of the image
 *                                  should match which element in
 *                                  the teaser
 *    {
 *         "title" : "title",    -> the title attribute shall match
 *                                  the title class in the teaser
 *         "ref"   : "subtitle",
 *         ....
 *    }
 *    template     : "teaser"    -> the teaser class when building it
 *    subtemplate  : "teaserEl"  -> the single element wrapper
 *    tooltip      : {           -> a tool tip, may be ommitted
 *         clazz   : "teaserTip" -> the class for the tooltip (css)
 *         preview : "img"       -> if and which element should be
 *                                  shown. can be used for preview images
 *         position: "relative"  -> tooltip position in respect to the number
 *                                  "relative" - moves with number
 *                                  "fixed" - takes just the css
 *         corrX   : -10         -> horizontal position fix for relative tips
 *         corrY   : -150        -> vertical position fix
 *    },
 *                                  it in the tooltip. recursive searching
 *    meta         : "meta"      -> the containing div class for meta
 *                                  information (see attributes)
 *    easing       : "fade"      -> the animation when switching items
 *                                  "fade", "slide" currently
 *    switcher     : "switcher"  -> the div containing the numbers to
 *                                  switch between images
 *    number       : {           -> a single number in the switcher
 *         clazz   : "number .ff"-> the class for the number     
 *         id      : "number"    -> a reference
 *    }
 *    hover        : "active"    -> the class to add in hover state
 *    active       : "active"    -> the class to add when active
 *    duration     : 4           -> the easing-duration in seconds
 *    fadeDuration : 1           -> duration of the switch
 * }
 */
//Teaser.prototype = {

    this._params = { 
				autocycle    : true,
				navigation   : false,
				imageSlider  : false,
				dotSlider    : false,
        clazz        : "teaserImg",
        attributes   : {
            "title"  : "title",
            "ref"    : "subtitle",
            "type"   : "type"
        },
        template     : "head_teaser_teaser",
        subtemplate  : "teaserEl",
//        tooltip      : {
//            clazz    : "teaserTip",
//            preview  : "img",
//            position : "relative",
//            corrX    : 6,
//            corrY    : 165
//        },
        meta         : "meta",
        switcher     : "switcher",
        number       : {
            clazz    : "number",
            id       : "number"
        },
		slider       : "slider",
		navNextClass    : "nextBtn",
		navPrevClass    : "prevBtn",
		slideNextClass  : "nextBtnSlide",
		slidePrevClass  : "prevBtnSlide",
		fullscreen   : {
			  active	 : false,
		    clazz    : "fullscreenLink White font12",
			  text     : "Vollbild",
			  image    : "/pics/buttons/btn_vollbild.png"
		},
        hover        : "active",
        active       : "active",
        easing       : "fade",
        duration     : 5,
        fadeDuration : 0.5,
		sliderImages : 5
    };
    
    this._images = null;
    this._actPosition= -1;
	this._actSliderArea=0;
	this._areasCount = 0;
    this._timer = null;
	this._fade  = true;
	

    /**
     * Constructor.
     * Instantiates the teaser
     *
     * @param params String
     */
    this.construct = function(params) {
        //overwrite params, if given		
        if (params != null) this._params = jQuery.extend(true, this._params, params);
        this._init();
    };
    
    /**
     * Private initialization
     */
    this._init = function() {
        //remember the images
        this._images = $("." + this._params.clazz);
        //wrap all
        this._images.wrapAll('<div class="' + this._params.template + '" />');



        //add the numbers to the wrapper
        var switcher = $('<div class="' + this._params.switcher + '" />');
        $('.' + this._params.template).append(switcher)
        this._fillNumbers(switcher);
        //wrap'em
        var el      = null;
        var meta    = null;
		var fs		= null;
		
		if(this._params.dotSlider){
			var dots = $('.' + this._params.template + ' .' + this._params.switcher).children();
			var padding = (310 - (7 * dots.length)) / 2;
			$('.' + this._params.template + ' .' + this._params.switcher).css({'padding':'0px ' + padding +'px'});
		}
		
        //cycle
        for (var i = 0; i < this._images.length; i++) {
            $(this._images[i]).wrap('<div class="' + this._params.subtemplate + '" />');
            el = $(this._images[i]).parent();

                    //
        this._addBorder(el);

            //add meta
            meta = $('<div class="' + this._params.meta + '" />');		
            //append it
            el.append(meta);
			
			if(!this._params.autocycle){				
				//add fullscreen
			    fs = $('<div class="' + this._params.fullscreen.clazz + '" >'
									+ this._params.fullscreen.text 
									+ ' <img src="'
									+ this._params.fullscreen.image 
									+ '" /></div>');
					if(this._params.fullscreen.active){
			    	el.append(fs);
			  	}
			  	else{
			  		$('.' + this._params.template + ' .' + this._params.subtemplate + ' .' + this._params.meta).css({'width':'100%'});	
			  	}
			}

             


            //make meta clickable, if a link is wrapped
            if ($(this._images[i]).attr('href') != "" && this._params.autocycle) {
                var tmpTarget = "_self";

                if ($(this._images[i]).attr('target') != "") {
                    tmpTarget = $(this._images[i]).attr('target');
                }
                if (typeof(tmpTarget) != 'undefined'){
                    meta.wrap('<a href="' + $(this._images[i]).attr('href') + '" target="' + tmpTarget + '" />');
                }else{
                     meta.wrap('<a href="javascript:;" onclick="pressPlay($(this).parent().find(\'.videoPlayButton\'))" />');
                }
            }
			if(!this._params.autocycle){
                                // wrap fullscreen area
				fs.wrap('<a href="' + $(this._images[i]).attr('href') + '" target="' + tmpTarget + '" />');
			}




            //inside of meta, add the attributes given in the configuration
            for (var key in this._params.attributes) {
                //key is attribute of the core element
                meta.append($('<div class="' + this._params.attributes[key] + '" />').html($(this._images[i]).attr(key)));
            }
			// add count to meta
			if(!this._params.autocycle){
			  el.children('.' + this._params.meta).append('<div class="imageCount">' + (i + 1) + ' / ' + this._images.length +'</div>');	
			}
			
            //hide
            el.hide();
        }
		
		if(this._params.imageSlider){		    
			this._addNavButtons(true);
			this._handleSlideButtons();
		}
		// handle navigation
		if(this._params.navigation){
			this._addNavButtons(false);			
		}
		
		//show first element
        this._cycle();
        
		if(this._params.autocycle && this._images.length > 1){
		    //add timer
            this._addTimer();
		}
        
    };	
	/**
         *
         */
        this._addBorder = function(el){
            var border = $('<div class="border"></div>');
//            $('.' + this._params.template).append(border);

           // for(var i=0; i < this._images.length; i++){
                el.append(border);
            //}
        }



	/**
	 * write out buttons and
	 * add functionality
	 */
	this._addNavButtons = function(slider){
		var prev = this._params.navPrevClass;
		var next = this._params.navNextClass;
		if(slider){
			prev = this._params.slidePrevClass;
			next = this._params.slideNextClass;
		}
		//add navigation buttons
		var spanAppend = '<a href="javascript:void(0);"></a></span>';
		jQuery('.' + this._params.template).append('<span class="'+ prev +'" id="0">' + spanAppend
												   + '<span class="'+ next +'" id="2">' + spanAppend);
			
		this._addButtonFunction('.' + prev, slider);
		this._addButtonFunction('.' + next, slider);
	};	
	/**
         *
         */

        this.pause = function(){
            clearInterval(this._timer);
        }



	/**
	 *
	 */
	this._addTimer = function(){
		this._timer = setInterval(jQuery.proxy(this._cycle, this), this._params.duration * 1000);
	};	
	
	/**
	 *
	 */
	this._slideArea = function(ev){
	    if(this._params.imageSlider){			
		    this._setActSliderArea($(ev.target).parent().attr('id') - 1);
			this._showArea();
		    this._handleSlideButtons();
		}	
	};
	
	/**
	 *
	 */
	this._slideImage = function(ev){
	    if(this._fade){			
			this._switchTo(this._getSwitchTo($(ev.target).parent().attr('id') - 1));
			//set fade to false to avoid "fast click effects"
			this._fade = false;
			
			if(this._params.autocycle){
		        //add timer
                this._addTimer();		    
		    }
					
			if(this._params.imageSlider){
			    // get number of slider area
			    var area = $('.' + this._params.template + ' #' + this._params.number.id + this._actPosition).parent().attr('id').replace(this._params.slider, "");
			    // set slider area
			    this._actSliderArea = area;
			    // show the area
			    this._showArea();
			    // show or hide slider buttons
			    this._handleSlideButtons();
		    }
		}	
	};	

     /**
     * add click funtionality to next
     * and previous buttons
     */
	this._addButtonFunction = function(element, slider){
		var obj = jQuery('.' + this._params.template + ' ' + element);
		var fct = slider ? this._slideArea : this._slideImage;
		// add click function
		obj.click(jQuery.proxy(fct, this));
	};

     /**
     * show actual slider area
     * hide the other ones
     */
	 
	 // TODO: merge with _activateNumber function
	this._showArea = function(){
	//deactivate them all
        $('.' + this._params.template + ' .' + this._params.switcher).children().hide();
        //activate current
        $('.' + this._params.template + ' #'+ this._params.slider + this._actSliderArea.toString()).show();
	};
	
	/**     
        * set slider to actual area
	* but only to available areas
        */
	this._setActSliderArea = function(step){
		this._actSliderArea = parseInt(this._actSliderArea);
		var tmp = this._actSliderArea + step;
		if(tmp < 0) this._actSliderArea = 0;
		else if(tmp > this.areasCount) this._actSliderArea = this.areasCount;
		else this._actSliderArea = tmp;
		
	};
	
	/**     
        * hide slider navigation on ends
        */
	this._handleSlideButtons = function(){
		var prev = $('.' + this._params.slidePrevClass);
		var next = $('.' + this._params.slideNextClass);
		this._actSliderArea == 0 ? prev.hide() : prev.show();
		this._actSliderArea + 1 == this._areasCount ? next.hide() : next.show();		
	};
	
	/**
        * returns the postion of
        * image to display
	* 
	* used if cycle is disabled
        *
        * @param int val
        */
	this._getSwitchTo = function(val){
		var $this    = this;
		var actPos   = parseInt(this._actPosition);
		var switchTo = actPos + val;		
		var elOut    = jQuery(this._images[actPos]).parent();
		
		// fade out and set _fade to true after finishing effect	
		elOut.fadeOut(this._params.fadeDuration * 1000, function(){
		    $this._fade = true;
		});
		// if bigger than image count
		// start with first image
		if(switchTo >= this._images.length){
		    return 0;
		}
		// switch to last image
		else if(switchTo < 0){
			return this._images.length - 1;
		}
		return switchTo;	
	};
	
    
    /**
     * Fills the given element with the numbers
     * and activates the first one
     *
     * @param el a jquery object
     */
    this._fillNumbers = function(el) {
        var number = null;
		var wrapCount = -1;
		
		if(this._params.imageSlider){
			// how many slider areas do we need?
			// append them to switcher
			this._areasCount = Math.ceil(this._images.length / this._params.sliderImages);
		    for (var z = 0; z <= this._areasCount; z++){				 
				$(el).append('<div class="'+this._params.slider+'" id="'+ this._params.slider + z +'" />');
			}
		}
        for (var i = 0; i < this._images.length; i++) {
			// html is number
			var html = i + 1;			
			if(this._params.imageSlider){
				// html is image
				html = jQuery(this._images[i]).html();
				// count slider areas
				if(i % this._params.sliderImages == 0){
				    wrapCount++;
				}
			}
			if(this._params.dotSlider){
				html = '';
			}
			
            var num = $('<div class="' + this._params.number.clazz + '" id="' + this._params.number.id + i.toString() + '" />');
            num.html(html).click(jQuery.proxy(this._numClicked, this));
			if(this._params.imageSlider){
				// append slider divs
				number = $('#' + this._params.slider + wrapCount).append(num);				
			}
			else{
			    number = $(el).append(num);
			}
            //add tooltip, if given
            if (this._params.tooltip != null) {

                num.mouseenter(jQuery.proxy(this._numOver, this));
                num.mouseleave(jQuery.proxy(this._numOut, this));
            }
        }
    };
	
    /**
     * Switches to the next image
     */
    this._cycle = function() {
        var elOut = null;
        //get element to fade out
        if (this._actPosition >= 0) elOut = $(this._images[this._actPosition]).parent(); 
        this._actPosition++;
        var elIn = null;
        if (this._actPosition >= this._images.length) {
            this._actPosition = 0;
            elIn = $(this._images[this._actPosition]).parent();
            //fade out the last image, so the first is shown 
            //automatically
            elIn.show();
            if (elOut != null) elOut.fadeOut(this._params.fadeDuration * 1000);
        } else {
            elIn = $(this._images[this._actPosition]).parent();
            //show the next image
            elIn.fadeIn(this._params.fadeDuration * 1000, function() {
                if (elOut != null) elOut.hide();
            });
        }
        //activate the number
        this._activateNumber();
    };
    
    /**
     * Switches the teaser to the specified element
     *
     * @param num int the teaser number
     */
    this._switchTo = function(num) {
		
        var elOut = $(this._images[this._actPosition]).parent();
        var elIn = $(this._images[num]).parent();
        //depth
		
		if (this._actPosition != num) {
			elIn.fadeIn(this._params.fadeDuration * 1000);
			elOut.fadeOut(this._params.fadeDuration * 1000);
		}
		/*
        if (this._actPosition > num) {
            elIn.show();
            elOut.fadeOut(this._params.fadeDuration * 1000);
        } else if (this._actPosition < num) {
            elIn.fadeIn(this._params.fadeDuration * 1000);
        }
		*/
        this._actPosition = num;
		if(!this._params.dotSlider){
            clearInterval(this._timer);
		}
        this._activateNumber();
    };
    
    /**
     * Activates the currently selected snippet
     */
    this._activateNumber = function() {
		var switcherClass = this._params.switcher;
		if(this._params.imageSlider){
		    switcherClass = switcherClass + ' .' + this._params.slider;
		}
        //deactivate them all
        $('.' + this._params.template + ' .' + switcherClass).children().removeClass(this._params.active);
        //activate current
        $('.' + this._params.template + ' #' + this._params.number.id + this._actPosition.toString()).addClass(this._params.active);
    };
    
    /**
     * Switcher number clicked, switch
     * to the element
     *
     * @param ev mouse event
     */
    this._numClicked = function(ev) {
        //strip off the number from the id		
        var number = $(ev.target).attr('id').replace(this._params.number.id, "");
		
		if(number == null || number == ''){
		    number = $(ev.target).parent().attr('id').replace(this._params.number.id, "");
		}
        //switch to that number
        this._switchTo(number);
    };
    
    /**
     * Number was hovered, add tooltip
     *
     * @param ev mouse event
     */
    this._numOver = function(ev) {
        //strip off the number from the id
        var number = $(ev.target).attr('id').replace(this._params.number.id, "");
        //clone the meta
        var tt = $(this._images[number]).parent().find("." + this._params.meta).clone();
        tt.removeClass(this._params.meta);
        tt.addClass(this._params.tooltip.clazz);
        $('.' + this._params.template).append(tt);
        //add a preview, if given
        if (this._params.tooltip.preview != null) {
            //search for the first element recursively, matching the parameter
            var preview = $(this._images[number]).find(this._params.tooltip.preview).first().clone();
            tt.append(preview);
        }
        //reposition, if necessary
        if (this._params.tooltip.position == "relative") {
            var pos = $('.' + this._params.template + ' #' + this._params.number.id + number).position();
            tt.css({
                top  : (pos.top + this._params.tooltip.corrY) + "px",
                left : (pos.left + this._params.tooltip.corrX) + "px"
            });
        }
    };
    
    /**
     * Roll down from number, remove the tooltip
     *
     * @param ev Mouse event
     */
    this._numOut = function(ev) {
        //remove the tooltip
        $('.' + this._params.template + ' .' + this._params.tooltip.clazz).remove();
    };
}
