
/**
 * Teaser class
 * Manages configuration and
 * displaying of the top teaser
 * including the match center
 */
function Teaser() {

    /**
     * Default Parameter
     */
    this._params = {
        thumbPath    : false,
        autocycle    : true,
        navigation   : false,
        imageSlider  : false,
        dotSlider    : false,
        clazz        : "teaserImg",
        attributes   : {
            "title"  : "title font22b",
            "ref"    : "subtitle font14"
        },
        template     : "teaser",
        subtemplate  : "teaserEl",
        tooltip      : {
            clazz    : "teaserTip",
            preview  : "img",
            position : "relative",
            corrX    : 60,
            corrY    : 165
        },
        meta         : "meta",
        switcher     : "switcher",
        number       : {
            clazz    : "number font12b",
            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,
    uniqueID : null
    };

    this._images = null;
    this._actPosition= -1;
    this._actSliderArea=0;
    this._areasCount = 0;
    this._timer = null;
    this._fade  = true;
    this._metas = [];
    this.stopped = false;
    this.actualVideo = null;

    /**
     * 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
        if(this._params.uniqueID != null){
            this._images = $("." + this._params.clazz + this._params.uniqueID);
            //wrap all
            var tmpl = this._params.template + this._params.uniqueID;
            this._images.wrapAll('<div class="'+ tmpl + ' ' + this._params.template + '" />');
            this._params.template = tmpl;

            var switcher = $('<div class="' + this._params.switcher + ' ' + this._params.switcher + this._params.uniqueID + '" />');
            this._params.switcher = this._params.switcher + this._params.uniqueID;
        }
        else{
            this._images = $("." + this._params.clazz);
            //wrap all
            this._images.wrapAll('<div class="' + this._params.template + '" />');
            var switcher = $('<div class="' + this._params.switcher + '" />');
        }
        //add the numbers to the wrapper
        $('.' + 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();

            //add extra class for identifying TV teaser
            if($(this._images[i]).attr('type') && $(this._images[i]).attr('type').length>0){
                this._params.meta='meta_tv';
            }

            //add meta
            meta = $('<div class="' + this._params.meta + '" />');
            //add video type for video previews (TV)
            if($(this._images[i]).attr('type') && $(this._images[i]).attr('type').length>0){
                meta.append('<div class="detailsType_'+$(this._images[i]).attr('type')+'"></div>');
            }
            //append it
            el.append(meta);
            //save meta
            this._metas.push(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{
            //console.log($('.' + this._params.template + ' .' + this._params.subtemplate + ' .' + this._params.meta));
            $('.' + this._params.template + ' .' + this._params.subtemplate + ' .' + this._params.meta).css({'width':'100%'});
          }
      }
            //make meta clickable, if a link is wrapped
            if (typeof($(this._images[i]).attr('href')) != "undefined" && $(this._images[i]).attr('href') != "" && this._params.autocycle) {
                var tmpTarget = "_self";
                if ($(this._images[i]).attr('target') != "") {
                    tmpTarget = $(this._images[i]).attr('target');
                }
                meta.wrap('<a href="' + $(this._images[i]).attr('href') + '" target="' + tmpTarget + '" />');
            }
      if(!this._params.autocycle){
        // wrap fullscreen area
        fs.wrap('<a href="' + $(this._images[i]).attr('href') + '" />');
      }
            //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();
    }

    };

  /**
   * write out buttons and
   * add functionality
   */
  this._addNavButtons = function(slider){
    var prev = this._params.navPrevClass;
    var next = this._params.navNextClass;
    var prev2 = '';
    var next2 = '';
    var id = '';
    if(slider){
        prev = this._params.slidePrevClass;
        next = this._params.slideNextClass;
        if(this._params.uniqueID != null){
            id = this._params.uniqueID;
            this._params.slidePrevClass = this._params.slidePrevClass + this._params.uniqueID;
            this._params.slideNextClass = this._params.slideNextClass + this._params.uniqueID;
            prev2 = prev + this._params.uniqueID;
            next2 = next + this._params.uniqueID;
        }
    }
    //add navigation buttons
    var spanAppend = '<a href="javascript:void(0);"></a></span>';
    jQuery('.' + this._params.template).append('<span class="'+ prev2 +' '+ prev +'" id="0">' + spanAppend
                           + '<span class="'+ next2 +' '+ next +'" id="2">' + spanAppend);

    this._addButtonFunction('.' + prev + id, slider);
    this._addButtonFunction('.' + next + id, slider);
  };

  /**
   *
   */
  this._addTimer = function(){
    this._timer = setInterval(jQuery.proxy(this._cycle, this), this._params.duration * 1000);
    //console.log(
  };

  this._removeTimer = function() {
    clearInterval(this._timer);
  };

  /**
   * Hides all meta information windows
   */
  this.hideMeta = function() {
    for(var i = 0; i < this._metas.length; i++) {
        $(this._metas[i]).fadeOut(0);
    }
  };

  /**
   * Displays all meta information
   */
  this.showMeta = function() {
    for(var i = 0; i < this._metas.length; i++) {
        $(this._metas[i]).show();
    }
  };

  /**
   *
   */
  this._slideArea = function(ev){
      if(this._params.imageSlider){
        this._setActSliderArea($(ev.target).parent().attr('id') - 1);
        this._showArea();
        this._handleSlideButtons();
    }
  };

  /**
   *
   */
  this._slideImage = function(ev){
      //this._removeTimer();
      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.switcher + ' #' + 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.switcher + ' #' + 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);
    parseInt(this._actSliderArea) == 0 ? prev.hide() : prev.show();
    parseInt(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);
      /*CHANGE: "z<" instead of "z<=" to prevent empty div*/
        for (var z = 0; z < this._areasCount; z++){
            //var additional = this._params.uniqueID != null ? this._params.slider + this._params.uniqueID : '';
            $(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();
        // if thumbPath is set, replace the path of the thumbnails
        if (this._params.thumbPath) {
            html = html.replace(this._params.thumbPath.search, this._params.thumbPath.replace);
        }
        // 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.switcher + ' #' + 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);
                /*elOut.find("object").remove();
                console.log("weg auto");*/
            }
        } else {
            elIn = $(this._images[this._actPosition]).parent();
            //show the next image
            elIn.fadeIn(this._params.fadeDuration * 1000, function() {
                if (elOut != null) {
                    elOut.hide();
                    /*elOut.find("object").remove();
                    console.log("weg auto");*/
                }
            });
        }
        //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, function() {
        /*if (elOut.find('object').length > 0) {
            var id = elOut.find('object').attr('id');
            var swf = document.getElementById(id);
            swf.stopFromJavascript();
        }
        elOut.find('object').remove();
        console.log("weg");
        //elOut.append('<div id="' + id + '">');*/
      });
    }
    /*
        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);
    }
        clearInterval(this._timer);
        //if (this._params.dotSlider) this._timer = setInterval(jQuery.proxy(this._cycle, this), 1000);
        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) {
        //remove video player, if any
        if (this.actualVideo != null) {
            var parent = $('#' + this.actualVideo).parent();
            $('#' + this.actualVideo).remove();
            parent.append($('<div id="' + this.actualVideo + '">'));
            this.actualVideo = null;
            this.showMeta();
        }
        this.stopped = true;
        //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 video infos to "tt"

        if ($(this._images[number]).find('.description').length > 0) {
            tt.addClass('vid');
            tt.append('<div class="logoTv"></div>');
        }

        //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();
    };

    /**
     * Displays a flash video instead of some images in the teaser
     *
     * @param id the video id
     * @param type the type of video
     */
    this.showVideo = function(id, type, width) {
        this.hideMeta();
        var height = 342;
        var position = "teaser";
        //pause teaser
        this._removeTimer();
        //load video
        var flashvars = {
            skin   : '/flash/vplayer/skinWerder.swf',
            config : '/playlistXML.php%3Fid=' + id + '%26type=' + type + '%26position=' + position + '%26autoplay=true'
        };
        var params = {
            menu              : "false",
            scale             : "noScale",
            allowFullscreen   : "true",
            allowScriptAccess : "always",
            wmode             : "opaque",
            bgcolor           : "#000000"
        };
        var attributes = {
            id:"altContent" + position + id
        };
        swfobject.embedSWF("/flash/vplayer/vplayer.swf", "altContent" + position + id, width, height, "9.0.0", "/flash/vplayer/expressInstall.swf", flashvars, params, attributes);
        $(document).ready(function() {var player = new Player('altContent' + position + id, '/playlistJSON.php?id=' + id + '&type=' + type, "606px", "342px")});
        this.actualVideo = "altContent" + position + id;
    };
}
