if (typeof common == 'undefined') common = {};


/**
 * Replaces the src attribute value with filename on the current
 * object.
 *
 * @var string filename The filename
 *
 * @return void
 *
 * @author Lars Hess <hess@twt.de>
 */
common.initHoverButtonChangeImage = function(filename)
{
  this.writeAttribute('src', filename);
}

/**
 * Init an hover button with the hover effect
 *
 * @var DOM-element element The button to animate
 *
 * @return void
 *
 * @author Lars Hess <hess@twt.de>
 */
common.initHoverButton = function(element)
{
  var src = common.xtractFileNameFromSrc(element.readAttribute('src'));
  var filename = src.file.split('.');

  element.onmouseover = common.initHoverButtonChangeImage.curry(src.path + '/' + filename[0]+'_hover.'+filename[1]);
  element.onmouseout  = common.initHoverButtonChangeImage.curry(src.path + '/' + filename[0]+'.'+filename[1]);

  if (element.hasAttribute('disabled')) {
    element.setAttribute('src', src.path + '/' + filename[0]+'_hover.'+filename[1]);
  }
}

/**
 * Extract a path and filename from a given location in the form
 *
 * /path/to/file/filename.ext
 * or
 * http://path/to/file/filename.ext
 *
 * @param string A location string as described above
 *
 * @return object
 *   {path: /path/to/file, file: filename.ext}
 *
 * @author Jan Schumann <schumann.jan@guj.de>
 */
common.xtractFileNameFromSrc = function(src)
{
    var parts = src.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
	if (parts == null) {
		var ret = {path: '', file: src};
	}
	else {
		var ret = {path: parts[1], file: parts[2]};
	}

    return ret;
}

common.initUgcModules = function()
{
  $$('div.boxen-wrapper').each(function(wrapper) {
    wrapper.list = new Array();

    wrapper.select('div.ugc-boxen').each(function(box) {
      this.list.push(box);

      box.hide();

      var previous  = box.select('a.previous').first();
      previous.setStyle({visibility:'visible'});
      previous.observe('click', function(e) {
        e.stop();
        wrapper.list.each(function(sbox) {
          if (sbox == this) {
            if (sbox.previous()) {
              sbox.previous().show();
            }
            else {
              wrapper.list.last().show();
            }

            sbox.hide();
          }
        }.bind(this));
      }.bind(box));

      var next = box.select('a.next').first();
      next.setStyle({visibility:'visible'});
      next.observe('click', function(e) {
        e.stop();
        wrapper.list.each(function(sbox) {
          if (sbox == this) {
            if (sbox.next()) {
              sbox.next().show();
            }
            else {
              wrapper.list.first().show();
            }

            sbox.hide();
          }
        }.bind(this));
      }.bind(box));
    }.bind(wrapper));

    if (wrapper.list.length == 1) {
      wrapper.list.last().select('a.next').first().style['visibility'] = 'hidden';
      wrapper.list.first().select('a.previous').first().style['visibility'] = 'hidden';
    }

    if (wrapper.list.length > 0) {
      wrapper.list.first().show();
    }
  });
}


/**
 * Inits sidebar elements
 *
 * @return void
 */
common.initSidebar = function()
{
  this.initMediaTeaser();

  $$('div.shopbox ul.shopbox-reiternavi').each(function(element) {
    new common.aboBox(element);
  });
}


/**
 * Class to init aboBox containers in sidebars
 */
common.aboBox = new Class.create({
  _tabs: new Array(),
  _pages: new Array(),

  initialize: function(tab_container)
  {
    this._tabs = tab_container.select('li');
    this._pages = tab_container.up('div').select('div.aktuelles-heft');

    this._tabs.each(function(element, tab_num) {
      element.down('a').observe('click', this._tabClickEvent.bindAsEventListener(this, tab_num));
    }.bind(this));
  },

  _tabClickEvent: function(e, tab_num) {
    e.stop();

    Event.element(e).up('ul').className ="shopbox-reiternavi "+(Event.element(e).up('li').className)+"-active clearfix";
    this._pages.invoke('hide');

    this._pages[tab_num].show();
  }
});


/**
 * Inits Media Teaser
 *
 * @return void
 *
 * @author Carsten Eilers <eilers@twt.de>
 */
common.initMediaTeaser = function()
{
  $$('div.media-box').each(function(el){
    var counter= el.select('li.counter').first();
    var teaser = el.select('div.media-box-teaser');
    var pos    = 0;
    var size   = teaser.length;

    if(teaser.length <= 1) {
      return false;
    }

    teaser.each(function(sub){
      sub.hide();
    });

    el.select('div.media-box-teaser').first().show();

    el.select('a.previous').first().observe('click', function(e){
      e.stop();

      if (pos == 0) {
        this[pos].hide();
        pos = size;
      }

      if (pos > 0) {
        if (this[pos]) {
        this[pos].hide();
        }

        pos--;
        this[pos].show();

        counter.innerHTML = (pos+1)+'/'+size;
      }

    }.bind(teaser));

    el.select('a.next').first().observe('click', function(e){
      e.stop();

      if ((pos+1) == size) {
          this[pos].hide();
        pos = -1;
      }

      if((pos+1) < size) {
      if (this[pos]) {
          this[pos].hide();
      }

        pos++;
        this[pos].show();

        counter.innerHTML = (pos+1)+'/'+size;
      }
    }.bind(teaser));
  });
}

/**
 * Init Video Preview Boxes
 *
 * @return void
 *
 * @author Carsten Eilers <eilers@twt.de>
 */
common.initVideoBoxes = function()
{
  if ($$('div.videobox').length == 0) {
    return false;
  }

  $$('div.videobox').each(function(e){
    with(e.select('div.scroll-video-box').first()) {
      style['width'] = (select('div.scroll-video-tab').length * parseInt(select('div.scroll-video-tab').first().offsetWidth))+'px';
    }

    var video_border = e.select('div.scroll-video-border').first();

    Object.extend(video_border, {
      scrollEast : function()
      {
        if (((-1) * parseInt(this.style['left'])) >= (((this.select('div.scroll-video-tab').length)-1) *
          this.select('div.scroll-video-tab').first().offsetWidth)) {
          this.style['left'] = 0;
        }
        else {
          common.scrollVideoBox(this, -200);
        }
      },

      scrollWest : function()
      {
        if (((-1) * parseInt(this.style['left'])) == 0) {
          this.style['left'] = ((-1)*((this.select('div.scroll-video-box').first().select('div.scroll-video-tab').length)-1) *
            this.select('div.scroll-video-tab').first().offsetWidth)+'px';
        }
        else {
            common.scrollVideoBox(this, 200);
        }
      }
    });

    e.select('div ul li a.next').first().observe('click', function(e){
      e.stop();

      this.scrollWest();
      this.wait = 1;

    }.bind(video_border));

    e.select('div ul li a.previous').first().observe('click', function(e){
      e.stop();

      this.scrollEast();
      this.wait = 1;

    }.bind(video_border));
  });

  new PeriodicalExecuter(function(pe) {
    $$('div.scroll-video-border').each(function(el){
      if(el.wait != 1) {
        el.scrollEast();
      }
      el.wait = 0;
    });
  }, 6);
}

/**
 * Lock Variable to lock Scrolling while actions
 *
 * @author Carsten Eilers <eilers@twt.de>
 */
common.scrollLock = null;

/**
 * Sliding in video boxes
 *
 * @param box sliding box
 * @param move the way to move
 *
 * @return void
 *
 * @author Carsten Eilers <eilers@twt.de>
 */
common.scrollVideoBox = function(box, move)
{
  if(this.scrollLock == null) {
    this.scrollLock = true;
    new Effect.MoveBy(box, 0, move,
    {
      duration: 0.4,
      fps: 25,
      transition: Effect.Transitions.sinoidal,
      queue: 'end',
      afterFinish : function() {
        this.scrollLock = null;
      }.bind(this)
    });
  }
}

common.initMainNavigation = function()
{
  var Navigation = $('hauptnavigation');
  Object.extend(Navigation,{
    def: null,
    _static:  false,

    initialize: function()
    {
      this._static = this.hasClassName('statisch');

      if (this.select('ul > li.aktiv').length > 0){
        this.setDefaultValue(this.select('ul > li.aktiv').first());
      }
    },

    setDefaultValue: function(value)
    {
      this.def = (Object.isElement(value) ? value : null);
      this.setDefault();
    },

    setStatic: function(value)
    {
      if (value != null) {
        this._static = value;
      }

      if (this._static == true) {
        this.addClassName('statisch');
      }
      else {
        this.removeClassName('statisch');
      }
    },

    isStatic:  function()
    {
      return this.hasClassName('statisch');
    },

    setInactive: function()
    {
      this.removeClassName('ebene2-2')
        .removeClassName('ebene2')
        .removeClassName('ebene2_bfr')
        .removeClassName('ebene2_bfr-2')
        .addClassName('ebene1');

      this.select('ul.clearfix > li')
        .invoke('removeClassName', 'aktiv')
        .invoke('removeClassName', 'erster-aktiv');
    },

    setActive: function(element)
    {
      this.setInactive();

      if (element == null) return;

      if(element.id != '' && element.id == 'bfr_li') {
        this.addClassName((element.select('ul > li.clearleft').length > 0) ? 'ebene2_bfr-2' : 'ebene2_bfr');
      }
      else {
        this.addClassName((element.select('ul > li.clearleft').length > 0) ? 'ebene2-2': 'ebene2');
      }

      this.setStatic();
      element.addClassName('aktiv');

      if (element.hasClassName('erster')) {
        element.addClassName('erster-aktiv');
      }
    },

    hasDefault: function()
    {
      return Object.isElement(this.def);
    },

    getDefault: function()
    {
      return (this.hasDefault() ? this.def : null);
    },

    setDefault: function()
    {
      if (this.hasDefault()) {
        if(this.def.id != '' && this.def.id == 'bfr_li') {
          this.addClassName((this.def.select('ul > li.clearleft').length > 0) ?
            ((this.isStatic()) ? ' ebene2_bfr-2-statisch' : '') :
            ((this.isStatic()) ? ' ebene2_bfr-statisch' : ''));
        }
        else {
          this.addClassName((this.def.select('ul > li.clearleft').length > 0) ?
            ((this.isStatic()) ? ' ebene2-2-statisch' : '') :
            ((this.isStatic()) ? ' ebene2-statisch' : ''));
        }

        this.setActive(this.getDefault());
      }
      else {
        this.setInactive();
      }
    }
  });

  Navigation.initialize();

  $$('#hauptnavigation > ul > li').each(function(el) {
    if (el.select('ul > li').length > 0) {
      Event.observe(el, 'mouseover', function() {
        window.clearTimeout($('hauptnavigation').timer);
        $('hauptnavigation').setActive(this);
      });

      Event.observe(el, 'mouseout', function(){
        $('hauptnavigation').timer = window.setTimeout(function(evt) {
          $('hauptnavigation').setActive($('hauptnavigation').getDefault());
        }, 3000);
      });

      el.select('ul > li').each(function(sub){
        if (sub.select('ul > li').length > 0) {
          Event.observe(sub, 'mouseover', function() {
            window.clearTimeout(Navigation.timer_sub);

            for (var pos in this.parentNode.childNodes) {
              if (this.parentNode.childNodes[pos].nodeType == 1) {
              this.parentNode.childNodes[pos].removeClassName('aktiv');
              }
            }

            this.addClassName('aktiv');
          });

          Event.observe(sub, 'mouseout', function(){
            Navigation.timer_sub = window.setTimeout(function() {
              for (var pos in this.parentNode.childNodes) {
                if (this.parentNode.childNodes[pos].nodeType == 1) {
                  this.parentNode.childNodes[pos].removeClassName('aktiv');
                }
              }
            }.bind(this), 150);
          });
        }
      });
    }
  });
}

/**
 * Init Rating
 */
common.initRatingScore = function() {
  if (score = $('rating_score')) {
  score.onclick = function() {
      var list = score.select('> a');

      if (list.length > 0) {
        if (document.all) {
          list.first().click();
        }
        else {
          var evObj = document.createEvent('MouseEvents');
          evObj.initEvent( 'click', true, true );
          list.first().dispatchEvent(evObj);
        }
      }
    }
  }
}

Event.observe(window, 'load', function() {
  // Initialize Js Components in Sidebar
  // we cannot do this in dom:loaded, because there are timing issues in IE
  // because of a badly implemented event in Prototype
  common.initSidebar();
});

document.observe('dom:loaded', function() {
  // Initialize ugc modules
  common.initUgcModules();

  // Initialize video boxes
  common.initVideoBoxes();

  // Initialize hoverbuttons
  $$('.hoverbutton').each(common.initHoverButton);


  initBfriendsToolTips('.bfriendsToolTip');

  $('login_login', 'login_password').each(function(element) {
    if (element && element.value != '') {
    $(element.id+'_labelspan').hide();
  }
  });

  common.initRatingScore();
});

/**
 * Opens an link always in top-frame
 *
 * @param  dom-objekt element An anchor dom element
 *
 * @return bool
 */
common.openInTopFrame = function (element) {
  if (element.windows != top) {
    top.location = element.href;
    return false;
  }

  return true;
}

/**
 * Open a lightbox for iframes
 *
 * Additionaly it add the layout_csspopup request parameter
 *
 * @param string url    Url top open
 * @param int    width  Windows-width
 * @param int    height Window-height
 */
common.csspopup = function(url, width, height)
{
  if (csspopup.getCurrentInstance() != null) {
    return;
  }

  Tips.hideAll()
  url += (/\?/.test(url) ? '&' : '?') + 'layout_csspopup=1';

  try {
    new csspopup(height, width, {
      type: 'iframe',
      options: Object.extend({
        src: url,
        offsetHeight: -30
      }, ((arguments.length > 3) ? arguments[3] : {}) || {})
    });
  }
  catch(e) {}

  return false;
}

/**
 * Opens a lightbox for images
 *
 * @param string url    Url top open
 * @param int    width  Windows-width
 * @param int    height Window-height
 *
 * @return bool
 */
common.imagepopup = function(url, width, height)
{
  if (csspopup.getCurrentInstance() != null) {
    return;
  }

  Tips.hideAll()
  try {
    new csspopup(height, width, {
      type: 'image',
      options: {
        src: url
      }
    });
  }
  catch(e) {}

  return false;
}

/**
 * Opens a lightbox with topicexplorer in it
 *
 * @return bool
 */
common.topicexplorer = function()
{
  if (csspopup.getCurrentInstance() != null) {
    return;
  }

  Tips.hideAll()

  if (!$('topicExplorerFlashContent')) {
    var options = Object.extend({
      contentHeadline: '', infoHeadline: '', infoContent: '', query: ''
    }, ((arguments.length > 0) ? arguments[0] : {}) || {});
  }

  try {
    new csspopup(
      576, // Flash-Size: 576    + Border 40 616
      726, // Flash-Size: 726    + Border 24 750
      {
        type: 'flash',
        showCloseButton: false,
        options: {
          wmode: 'transparent',
          src:   '/flash/themenfinder/themenfinder.swf'
            +'?contentHeadline='+options.contentHeadline
            +'&infoHeadline='+options.infoHeadline
            +'&infoContent='+options.infoContent
            +'&query='+escape(options.query)
        }
      }
    );
  }
  catch(e) {}

  return false;
}

/**
 * submit action for paging on search
 */
function submitSearchByReturnKey(event, formName)
{
 if (!event) event = window.event;
  var key = event.keyCode || event.which;
  if(key == Event.KEY_RETURN){
        document.forms[formName].submit();
  }
}


common.myOpinionBubble = function(obj, url, content) {
  var id = (obj.id.split('_').length > 1) ? obj.id.split('_')[1] : obj.id;

  Event.observe(obj, 'click', function(e) {
    e.stop();
  });

  Event.observe(obj, 'prototip:shown', function() {
    $('layer_'+obj.id).innerHTML = content;

    new Ajax.Request(url, {
       parameters: { id: id },
       method: 'post',
       onSuccess: function(transport) {
      $('layer_'+obj.id).innerHTML = transport.responseText;
       }
    });
    trackingManager.count('showOpinionBubble');
  });

  this.initToolTip(obj, new Element('div', { id : 'layer_'+obj.id}), {
    closeButton: true,
    showOn: 'click',
    hideOthers: true,
    hideOn: {
      element: 'closeButton',
      event: 'click'
    },
    hook: { tip: 'topLeft', mouse: true },
    offset: { x: 14, y: 14 },
    hideAfter: 5
  });
}

/**
 *  common function to update element content via ajax
 *  - get new Content via ajax-request from sfAction 'source'
 *  - and update the passedd 'targetArea' with the ajax.responce
 *
 * @param targetArea  id of container to update with response
 * @param addParams   prams to set to request (response?)
 * @param origin
 * @param elId
 * i.E.
 * loadAreaContent('viewContainerId','bf_friends/myFriends ','page=2&ajax=&filter=&status=friends..');
 */
loadAreaContent = function (targetArea, source, addParams, origin, elId) {

  //alert("loadAreaContent(targetArea='"+targetArea+"', source='"+source+"', addParams='"+addParams+"', origin='"+origin+"', elId)");
  if(!$(targetArea)) { return; }

  // scriptRoot
  if (typeof scriptRoot == 'undefined') {
    scriptRoot = '';
  }

  new Ajax.Request(scriptRoot + source, {
    method: 'post',
    postBody: addParams,
    onSuccess: function(transport){

      if(origin) {
        var liElements = $('tabNavigation').getElementsByTagName('li');
        for (i=0; i < liElements.length; i++) {
          $(liElements[i]).removeClassName('on');
          $(liElements[i]).down().removeClassName('active');
        }
        origin.up().addClassName('on');
        origin.addClassName('active');
      }
      if (elId) {
        elements = $$('.linkActive');
        for (i = 0; i < elements.length; i++) {
          $(elements[i]).className = 'linkPassive';
        }
        $(elId).className = 'linkActive';
      }

      var response = transport.responseText;
      //window.scrollTo(0,0);
      $(targetArea).innerHTML = response;
      $(targetArea).innerHTML.evalScripts();

      // Init tooltips reloaded by ajax
      if (typeof initToolTips != 'undefined') {
        initToolTips('#'+targetArea+' .toolTip');
      }
    }
  });
}



/**
 * Creates a new gujTooltip for every element with 'class=toolTip' and a rel-attribute
 *
 * @author Daniel Kuhnke
 * @enhanced by Andreas Weste
 * @changed by Kay Schewe
 * @param  string styleRule      classes or ids of elements to be toolTips (e.g. '#lightbox .content .toolTip') [optional]
 * @return void
 */
initBfriendsToolTips = function (styleRule) {

  styleRule = (typeof styleRule == 'undefined') ? '.toolTip' : styleRule;

  $$(styleRule).each(function(element) {

    textTitle = (element.hasAttribute('title')) ? element.readAttribute('title') : '';

    textTitle = textTitle.replace(/\(online\)$/, '<span class="colorOnline">(online)</span>');
    textTitle = textTitle.replace(/\(offline\)$/, '<span class="colorOffline">(offline)</span>');

    textBody  = '';

    if (element.hasAttribute('rel')) {
      textBody = element.readAttribute('rel');
    }
    else if (element.hasAttribute('onmouseover')) {
      textBody = element.onmouseover();
    }

  new gujTooltip(element, textBody+textTitle, {className: 'bfriendsUserAvatarToolTip'});

    element.setAttribute('title', '');
    var tmpHref = (element.hasAttribute('href')) ? element.getAttribute('href') : '';
    if (tmpHref.match(/#$/) && !element.hasAttribute('onclick')) {
      element.onclick = function () {
        return false;
      }
    }
  });
}



