//Set document.domain to the main domain (without subdomains) of this host.
//This is needed to allow communication with iframes hosted on different subdomains, e.g. stylingtester.brigitte.de
if (!window.jfPD || !jfPD.controller.isNativeApp) { //can't set document.domain in native portable device apps
  var domainParts = window.location.host.split('.');
  document.domain = domainParts[domainParts.length-2]+'.'+domainParts[domainParts.length-1];
}

try {
  document.execCommand("BackgroundImageCache", false, true); //IE hover flickering images fix
} catch(err) {}

var common = (function($) {

  var that = (typeof common !== 'undefined') ? common : {},
      ns = that;

  /**
   * Functions for hash-params parsing/getting/adding
   */
  that._hashParams = {};

  that._initHashParams = function()
  {
    var pos = [], kv  = [],
        loc = (document.location+'');
    if ((pos = loc.indexOf('#')) == -1) return;

    var pairs = loc.substring(pos+1, loc.length).split('&');
    for (var i=0; i<pairs.length; i++) {
      if ((kv=pairs[i].split('=')).length == 2) {
        that._hashParams[kv[0]] = kv[1];
      }
    }
  }();
  that.getHashParam = function(key)
  {
    var default_value = arguments.length > 1 ? arguments[1] : null;
    return that._hashParams[key] || default_value;
  }
  that.addHashParamsFromHash = function(element, params)
  {
    var value, hash_params = {};
    for (var i=0; i<params.length; i++) {
      if ((value = that.getHashParam(params[i])) == null) continue;
      hash_params[params[i]] = value;
    }
    return that.addHashParams(element, hash_params);
  }
  that.addHashParams = function(element, params)
  {
    params = $.param(params);

    element.href+= ((element.href.indexOf('#') == -1) ? '#' : '&')+params;

    return true;
  }

  /**
   * Functions for back to article links
   */
  that.backToArticleId = null;
  that.backToArticlePage = null;
  that.setBackToArticle= function(id, page)
  {
    that.backToArticleId   = id;
    that.backToArticlePage = page;
  }
  that.addBackToArticleHash = function(element)
  {
    var backToArticleId;
    if (that.backToArticleId != null && that.backToArticlePage != null){
      that.addHashParams(element, $H({ 'backToArticle': that.backToArticleId, 'backToArticlePage': that.backToArticlePage }));
    }
    else if ((backToArticleId = that.getHashParam('backToArticle')) != null) {
      that.addHashParams(element, $H({ 'backToArticle': backToArticleId, 'backToArticlePage': that.getHashParam('backToArticlePage', 1) }));
    }

    return true;
  }
  that.renderBackToArticleLink = function(element, url, html)
  {
    var id = null;
    if (typeof (id = that.getHashParam('backToArticle')) != 'string' || !$(element)) return;
    var page = that.getHashParam('backToArticlePage', 1);

    $(element).replace(
      html.replace('%link%',
        url.replace('_id', id).replace('_page', page)
      )
    );
  }
  
  that.initStandardToolTips = function() {
    that.initToolTips('.autotooltip');
  };

  /**
   * Creates a new prototip for every element with 'class=toolTip' and a rel-attribute
   *
   * @author Daniel Kuhnke
   * @enhanced by Andreas Weste
   *
   * @param  string styleRule      classes or ids of elements to be toolTips (e.g. '#lightbox .content .toolTip') [optional]
   * @return void
   */
  that.initToolTips = function (styleRule) {
    styleRule = (typeof styleRule == 'undefined') ? '.toolTip' : styleRule;
    $(styleRule).each(function(idx, element) {
      that.initToolTip(element);
    });
  }

  /**
   * Init tooltips
   *
   * @param DOM-element element The element to add tooltip
   * @param string|Prototype extended DOM-Element mit toHTML or toElement method
   *
   * @return void
   */
  that.initToolTip = function(element)
  {
    /**
     * Prototip and Prototype are deprecated (in this project)!
     * Use jQuery Tools instead -> jquery.tools.min.js
     * Documentation: http://flowplayer.org/tools/tooltip/index.html
     * you can customize the tooltips in the following line and css/jquerytools.css.php
     */
    $(element).tooltip({position: "bottom right", effect: "fade", delay: 2000});
  }


  that.centerElement = function(elem, options)
  {
    options = options || {};
    var $elem = $(elem),
        $window = $(window);
    
    var left = options.fixedLeft || ((($window.width() - $elem.outerWidth()) / 2) + $window.scrollLeft());
    
    var scrollTop = $(document).scrollTop();
    var top = options.fixedTop ? scrollTop + options.fixedTop : scrollTop + Math.max(5, (($window.height()-$elem.outerHeight()) / 2));

    $elem.css({
      "top": top+"px",
      "left": + left+'px'
    });
  }


  that.fontresizer = function($element) {
    this._current_zoom_level = 0;

    this._destination = $element;

    var options = $.extend({
      maximize_button: null,
      minimize_button: null,
      zoom_level: ['', 'zoomLevel1', 'zoomLevel2']
    }, ((arguments.length > 1) ? arguments[1] : {}) || {});

    this._zoom_level = options.zoom_level

    this._btnMaximize = $(options.maximize_button);
    this._btnMinimize = $(options.minimize_button);

    this._btnMaximize.bind('click', this._maximizeCallback.bind(this));
    this._btnMinimize.bind('click', this._minimizeCallback.bind(this));
  };
  
  that.fontresizer.prototype = {
    incZoomLevel: function()
    {
      if (this._isMaxZoomed()) {
        return; 
      }

      this._toggleButton(this._btnMinimize, true);
      this._updateZoomLevel(this._current_zoom_level + 1);

      if (this._isMaxZoomed()) {
        this._btnMaximize.hide();
        this._btnMinimize.show();
      }
    },

    decZoomLevel: function()
    {
      if (this._isMinZoomed()) {
        return; 
      }

      this._toggleButton(this._btnMaximize, true);
      this._updateZoomLevel(this._current_zoom_level - 1);

      if (this._isMinZoomed()) {
        this._btnMaximize.show();
        this._btnMinimize.hide();
      }
    },

    _updateZoomLevel: function(zoom_level, direction)
    {
      if (this._zoom_level[this._current_zoom_level].length > 0) {
        this._destination.removeClass(this._zoom_level[this._current_zoom_level]);
      }

      this._current_zoom_level = zoom_level;

      if (this._zoom_level[this._current_zoom_level].length > 0) {
        this._destination.addClass(this._zoom_level[this._current_zoom_level]);
      }
    },

    _isMaxZoomed: function()
    {
      return this._current_zoom_level >= (this._zoom_level.length - 1);
    },

    _isMinZoomed: function()
    {
      return this._current_zoom_level <= 0;
    },

    _maximizeCallback: function(e)
    {
      e.stopPropagation();
      e.preventDefault();
      if (window.briTracker) {
        briTracker.track({additional_tracking_info: 'fontSizeIncrease'});
      }
      this.incZoomLevel();
    },

    _minimizeCallback: function(e)
    {
      e.stopPropagation();
      e.preventDefault();
      if (window.briTracker) {
        briTracker.track({additional_tracking_info: 'fontSizeDecrease'});
      }
      this.decZoomLevel();
    },

    _toggleButton: function(element, active)
    {
      var button_image = element.find('img');
      var button_image_src = button_image.attr('src');

      if (active) {
        button_image.attr('src', button_image_src.replace(/_inaktiv\.gif$/, '.gif'));
      }
      else {
        button_image.attr('src', button_image_src.replace(/ern\.gif$/, 'ern_inaktiv.gif'));
      }
    }
  };
  
  that.csspopup = function(url, width, height, options) {
  
    if (width) {
      width += 80;
    }
    if (height) {
      height += 45;
    }
  
    if (!url.match(/layout_csspopup=1/)) {
      url += (-1 === url.indexOf('?') ? '?' : '&')+'layout_csspopup=1';
    }
    
    // If url is a picture it should be displayed centered. So the iframe option is set to false.
    var iframe = true;
    if (url.match(/\.jpg/)) {
      iframe = false;
    }

    options = options || {};
    options = jQuery.extend({
      href: url, 
      width: width, 
      height: height,
      iframe: iframe,
    }, options);
    
    jQuery.colorbox(options);
    
    return false; //prevent events from bubbling if this function's return value is passed to event handler
  };
  
  that.csspopup.close = function() {
    jQuery.colorbox.close();
  }


  that.init = function() {
    that.initStandardToolTips();
  };


  $(function() {
    $(document).trigger('common:init');
  });
  
  $(document).bind('common:init', that.init);
  
  return that;
  
})(jQuery);


