//firebug xs
try{
 if (!window.console || !console.firebug)
  {
      var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
      "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
  
      window.console = {};
      for (var i = 0; i < names.length; ++i){
        window.console[names[i]] = function() {};        
      }
  }
}
catch(e){}

/**
 *
 * @param {String} key the translation key
 * @param {String} culture target language
 * @param {String} labelVar the variable that contians the tranlations
 * @deprecated use @see i18n instead
 */
function __(key, culture, labelVar){
  return i18n(key, culture, labelVar);
}

/**
 *
 * @param {String} key the translation key
 * @param {String} culture target language
 * @param {String} labelVar the variable that contians the tranlations
 */
function i18n(key, culture, labelVar){  
  try{
    return labelVar[key][culture];
  } 
  catch(e){
    return key;
  }  
}

var sgText ={
    logoutLink: {
     'de_DE': 'Sie wurden ausgeloggt. <a href="/login/">Bitte melden Sie sich neu an</a>.',
     'en_US': 'Your session has expired. <a href="/login/">Please log in again</a>.'
    },
    editLinkText: {
      'de_DE': 'ändern',
      'en_US': 'change'
    },
    confirmLinkText: {
      'de_DE': 'ok',
      'en_US': 'ok'
    },
    loadError:{
      'de_DE': 'Leider konnte die angeforderte Seite nicht geladen werden.',
      'en_US': 'Unfortunately we could not complete the request.'
    },
    processing:{
      'de_DE': 'Daten werden geladen',
      'en_US': 'loading' 
    }
};

var sixGroups = {
  initFuncs: [],//this will hold all init funcs from all scripts that are included  --> not so cool i think now 
  culture: 'de_DE',  
  initialized: false,
  
  /**
   * stores all pending updates via ajax, if there are active posts, delay all polling requests till after finish
   */
  pendingUpdates: [],
  
  
  barRefreshInterval : 30000,
  barRefreshTask : null,
  
  /**
   * indicates, whether the bar is currently refreshing or not
   */
  updatingBar : false,
  
  
  /**
   * no of times the super navigation refresh was requested
   */
  updateCount : 0,  
  pId : 0,
  lastModified : "Thu, 01 Jan 1970 00:00:00 GMT",
  
  
  /**
   * global settings, can be overwritten with params object in init function
   * @see init()
   */
  settings : {
    culture: 'de_DE',    
    pId: null, //the partnercodeId
    isWidget: null,
    loggedIn: false,
    sgDomain: 'sixgroups.com',
    userId: null,
    tracking: false,    
    urchinId: "UA-2124570-1",
    fbApiKey: '',
    autoRefresh: true,
    partnercodeId: null //TODO: move from sgBar to here
  },
  

  /**
   * adds functions that are supposed to init once this system is ready
   * @param {Object} func
   * @param {num} pos
   */
  addLoadFunc: function(func){
    if(this.initalized === false){
      sixGroups.initFuncs.push(func);      
    }
    else{
      try{
        func();
      }
      catch(e){
        console.warn('could not execute ', e);
      }
    }
  },

  executeInitFuncs: function(){
    $.each(sixGroups.initFuncs, function(num, func){
      func();
      sixGroups.initFuncs[num] = null;
    });
  },
  
  //loads XFBML and FB API if needed
  initFb: function(apiKey, params){
    var settings = {
      redirectUrl: '/auth/fbLogin/',
      logout: false         
    };
    
    var fbParams = {
      /*"reloadIfSessionStateChanged": false,*/
      "ifUserConnected" : function(){
        if(settings.logout === false){
          console.log('we have connected to FB! redirecting!', settings.redirectUrl);
          document.location.href=settings.redirectUrl;          
        }     
      }      
    };
    
    settings = $.extend(settings, params);
    
    //load fb connect
    FB_RequireFeatures(
      ["XFBML"], 
      function(){
        FB.init(
          apiKey, 
          "/xd_receiver.htm",
          fbParams
        );
      }
    );
  },  
  
  
  /**
   * 
   * @param {String} url
   * @param {String} title
   * @param {Object} options
   * @param {Boolean} centered
   * @return the window instance
   */
  popup:function (url, title, options, centered) {
         var title = title || 'Popup';
         var settings = {
             width: 400,
             height: 400,
             top: null,
             left: null,
             resizable: 'no',
             scrollbars: 'no',
             toolbar : 'no',
             menubar: 'no',
             directories: 'no',
             status: 'yes'
         };

         //merge config
         if(options){
           settings = jQuery.extend(settings, options);
         }

         //centers the window if top/left are null or smaller than zero
         if(!settings.top > -1 && settings.left > -1){
           settings.top = screen.height/2 - settings.height;
           settings.left = screen.width/2 - settings.width/2;
         }

         //create popup
         var params = [];
         var paramStr = '';
         var propCount = 0;
         jQuery.each(settings, function(prop){
           propCount++;
           params.push(prop+'='+this);
         });
         //console.info(params);

         paramStr = params.join(',');
         //console.log(paramStr);
         var win = window.open(url, title, paramStr);
         win.focus();
         return win;
       },

  
  
/**
 * 
 * @param {Object} customSettings
 */
  init:function(customSettings){
    this.settings = $.extend(this.settings, customSettings); 
    console.log('init sixgroups', this.settings);
    
    this.culture = this.settings.culture;    
    this.executeInitFuncs();
    this.initBlockUiDefaults();
	  this.initCluetip();    
    
    if (this.settings.userId !== null) {
      this.settings.loggedIn = true;
    }   
        
    this.registerEventHandlers();
    this.initThickboxes();
    
    try{
      //normal page
      
      //replaces sgBar  
      if(this.settings.isWidget == null && this.settings.autoRefresh != false){ 
        clearInterval(this.barRefreshTask);    
        this.barRefreshTask = setInterval(
          function(){          
            sixGroups.refresh();
          }, 
          this.barRefreshInterval
        );     
      }
    }
    catch(e){
      console.error(e);
    }
    this.initialized = true;
  },  
  
  
  debug: function(message, _level){
    level = _level | 'debug';
    $('#sgDebug').append('<p>Log: '+message+'</p>').show();
  },
  
  
  getPageSize: function(){
      var de = document.documentElement;      
      var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
      var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
      return {height: h, width: w};      
  },
  
  cleanup: function(){
    //console.log('cleanup');
    clearInterval(barRefreshTask);
  },
  
  /**
   * 
   * @param {String} url
   * @param {Boolean} [complete] optional, if true, the url is removed from the pendingUpdates list 
   */
  setAjaxPendingState: function(url, complete) {
    
    if(!complete){
      if(!this.pendingUpdates.inArray(url)){
        this.pendingUpdates.push(url);
      }  
    }
    //remove the url
    else{
      var indexToRemove = null;
      $.each(this.pendingUpdates, function(num){        
        if(this == url){
          indexToRemove = num;          
        }
      });
      this.pendingUpdates.splice(indexToRemove, 1);      
    }
  },
  
  
  /**
   * @param {String} url
   * @return boolean, true if the call is taking place at the moment, false, if there is no such a call
   */
  isPending: function(url){
    if(!this.pendingUpdates.inArray(url)){
      return false;
    }
    else {
      return true;
    }
  },


  initBlockUiDefaults: function(){    
    // override these in your code to change the default messages and styles 
    $.blockUI.defaults = { 
      // the message displayed when blocking the entire page 
      pageMessage:    '<div id="uiBlock">'+__('processing', this.culture, sgText)+'<div>', 
      // the message displayed when blocking an element 
      elementMessage: '<div id="uiBlock">'+__('processing', this.culture, sgText)+'<div>', // none 
      // styles for the overlay iframe 
      overlayCSS:  { backgroundColor: '#f6f6f6', opacity: '0.5' }, 
      // styles for the message when blocking the entire page 
      pageMessageCSS:    { width:'250px', margin:'-50px 0 0 -125px', top:'50%', left:'50%', textAlign:'center', color:'#000', backgroundColor:'#fff', border:'0px solid #aaa' }, 
      // styles for the message when blocking an element 
      elementMessageCSS: { width:'250px', padding:'10px', textAlign:'center', backgroundColor:'#fff'}, 
      // styles for the displayBox 
      displayBoxCSS: { width: '400px', height: '400px', top:'50%', left:'50%' }, 
      // allow body element to be stetched in ie6 
      ie6Stretch: 1, 
      // supress tab nav from leaving blocking content? 
      allowTabToLeave: 0, 
      // Title attribute for overlay when using displayBox 
      closeMessage: 'Click to close', 
      // use fadeIn effect 
      fadeIn:  1, 
      // fadeIn transition time in millis 
      fadeInTime: 500, 
      // use fadeOut effect when unblocking (can be overridden on unblock call) 
      fadeOut:  1, 
      // fadeOut transition time in millis 
      fadeOutTime: 500 
    };
  },
  
  /*
   * tooltip
   * usage: <a [<label <li] class="clueTip [sticky showTitle]"
   */
  initCluetip: function() {
    $('a.clueTip').cluetip({
      sticky: $(this).hasClass('sticky'),
      showTitle: $(this).hasClass('showTitle'),
      closePosition: 'title',
      closeText: '<small>Close</small><img class="vMiddle" src="/images/icons/cross_sm.gif" alt="close" />'
    });
		
	$('li.clueTip').cluetip({
       splitTitle: '|', 
       cursor:'help',
       showTitle: $(this).hasClass('showTitle')
    });
	$('label.clueTip').cluetip({
       splitTitle: '|', 
       cursor:'pointer',
       showTitle: $(this).hasClass('showTitle')
    });
		
  },
  
  /*
   * inits favicons for external links
   */
  initFaviconize: function() {   
	$("a.faviconize").faviconize({
		position: "before",
		defaultImage: "/images/icon_external.gif",
		className: "favicon",
		linkable: true,
		afterFaviconize: function(elem){
	      $(elem).removeClass('faviconize');
		}
	});
  },
  
  
  
	
  checkCookieCapabilities : function(){
    var cookie =  $.cookie('sixgroups');
    if(cookie == null){//no cookie capabilities :(
      $('#safariDebug').show();      
      return false;
    }
    else{      
      return true;
    }
  },
  
  
  /**
   * adds a displayMode = "partial" to all pager links
   * @param {Sting} targetContainerSelector
   * @param {Function} callbackFunc(responseText, textStatus, XMLHttpRequest)
   */
  ajaxifyPager: function(targetContainerSelector, params){
    //console.log('ajaxify pager');
    var settings = {
      onBeforeSubmit:null,
      onSuccess:null     
    };
    
    settings = $.extend(settings, params);    
   
    /**
     * event handler for links inside a pager
     */
    var onPagerLinkClicked = function(){
      this.href = sixGroups.attachUrlParam(this.href, {'name':'displayMode', 'value':'partial'});
      if(settings.onBeforeSubmit != null){
        settings.onBeforeSubmit();
      }

      $(targetContainerSelector).block();
      $(targetContainerSelector).load(this.href,
        function(responseText, textStatus, XMLHttpRequest){
          if(settings.onSuccess != null){            
            settings.onSuccess(responseText, textStatus, XMLHttpRequest);            
          }
          setTimeout(sixGroups.Tracking.track, 100);
          $(targetContainerSelector).unblock();
        }
      );
      return false;
    };
    
    $('ul.pagination li a').click(onPagerLinkClicked);
  },




  /**
   * attaches a url parameter to a url
   * @param {String} url the url to add the parameter to
   * @param {Object} param a parameter object cotaining name, and value
   * @return {String} url the formatted url
   * @deprecated use @see sixGroups.addUrlParams instead
   */
  attachUrlParam: function (url, param){
    console.warn('attachUrlParam is deprecated');
    if(url){
      if(url.indexOf('?')>=0 && url.indexOf(param.name+'='+param.value)==-1){
        url+='&'+param.name+'='+param.value;
      }
      else if(url.indexOf(param.name+'='+param.value)==-1){
        url+='?'+param.name+'='+param.value;
      }
      return url;
    }
  },
  
  /**
   * attaches url parameters to a url
   * @param {String} url the url to add the parameter to
   * @param {Object} params a parameter object cotaining key/val pairs
   * @return {String} url the formatted url
   */
  addUrlParams: function (url, params){
    try{
      if(url){
        console.log(url);      
        $.each(params, function(key){
          if(url.indexOf('?')>=0 && url.indexOf(key+'='+this)==-1){
            url+='&'+key+'='+this;
          }
          else if(url.indexOf(key+'='+this)==-1){
            url+='?'+key+'='+this;
          }
        });
        console.log(url);      
      }      
    }
    catch(e){
      console.warn('could not add url param', url, params);  
    }
    return url;
  },
  
  /**
   * strip HTML tags from a String
   * @param {String} str
   * @return {String} the cleaned string
   */
  stripTags: function(str){
    var re= /<\S[^><]*>/g;
    return(str.replace(re, ''));  
  },

  
  /**
   * init all thickbox links
   */
  initThickboxes: function(){
    //on page load call tb_init
    //console.log("tbinit")
    $('a.thickbox', 'area.thickbox', 'input.thickbox').unbind('click');
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
    imgLoader = new Image();// preload image
    //imgLoader.src = "/images/loading_dark.gif";
    imgLoader.src = "/images/loadingAnimation/arrows_white.gif";
  },


  /**
   * used to store tracking data vor google analytics
   */
  Tracking: {
    next : '',
    last: '',
    pageTracker: null,
    gwoTracker: null,
    
        
    /**
     * initializes the tracking
     */
    init: function(){
      if(typeof _gat != 'undefined'){
        this.pageTracker = _gat._getTracker(sixGroups.settings.urchinId);
        this.pageTracker._setDomainName(sixGroups.settings.sgDomain);
        this.pageTracker._setAllowHash(false); 
        
        this.gwoTracker = _gat._getTracker("UA-2124570-5");
      }
      else{
        console.warn('google analytics not installed');
      }
    },
    
    
    
    /**
     * call a gwo test url
     * @param url
     */
    gwoTest: function(url){
      try{
        var trackingUrl = '';
        if(this.gwoTracker === null){
          this.init();
        }
        console.log('testing gwo: ', url);
        this.gwoTracker._trackPageview(url);
      }
      catch(e){
        console.warn('could not use gwo', e);
      }  
    },
    
    
    /**
     * tracks something with google analytics, 
     * @param {Object} param if set, the passed parameter wil be used as the trackingUrl in ganalytics, 
     * otherwise,the lastAction stored in the session is used as tracking url  
     * 
     */
    track: function(url){
      var trackingUrl = url || '';
      try{
        if(sixGroups.settings.tracking){          
          
          if(this.pageTracker === null){
            this.init();
          }
          
          //an action that was set by the tracking filter, overwrites everything else -deprecated?
          if(sixGroups.Tracking.next != ''){          
            trackingUrl = sixGroups.Tracking.next;
            sixGroups.Tracking.next = '';
          }
        
          if(sixGroups.pId >0){
            sixGroups.addUrlParams(trackingUrl, {'partnercodeId': sixGroups.pId } );            
          }
          
          if(trackingUrl.length > 0){
            this.pageTracker._trackPageview(trackingUrl);
          }
          else{
            this.pageTracker._trackPageview();
            console.info('standard tracking ', trackingUrl);
          }
          
          //not good, as this will stay the same for the whole time
          if(sixGroups.pId >0){      
            console.log('set external var for tracking');     
            this.pageTracker._setVar('externalPi-'+sixGroups.pId);            
          }
          else{
             this.pageTracker._setVar('');
          }
        }
        else{
          if(trackingUrl === ''){
            trackingUrl = 'default url';
          }
          console.info('tracking is off, url to track: ', trackingUrl);
        }
      }
      
      catch(e){
        console.warn('could not track', trackingUrl, e);
      }      
    }
  }, 
  


  /**
   * registers event handlers on main content
   */
  registerEventHandlers : function(){    
    
    try {
      $('a').live('click',
        function(){
          if(
            (this.className.indexOf('externalIfInCommunityBar') > -1 && sixGroups.settings.isWidget !== null) 
            || $(this).attr('rel') == 'external'
          ){
            this.target = '_blank';
            //alert('open', this.href, this.target)
            //var newWindow = window.open(this.href, '_blank');
            //newWindow.focus();
            //return false;         
          }
     });      
      
      //ie6 button fix
      $('button[class=alternateSubmit]').live('click', 
          function(){
            $('button[class=alternateSubmit]').attr('disabled', 'disabled');
            $(this).removeAttr('disabled');        
      });      
    }
    catch(e) {
      console.error('cold not init event listeners', e);
    }
  },

  /**
   * create a valid url from any string
   * @param {String} str
   */
  createValidUrl: function(str){
    str = $.trim(str);
    str = str.toLowerCase();
    
    //replace whitespace with _
    var myRe = /\s/gi;
    str = str.replace(myRe, "_");
    
    //replace umlauts
    str = str.replace(/ü/g, "ue");
    str = str.replace(/ö/g, "oe");
    str = str.replace(/ä/g, "ae");
    str = str.replace(/ß/g, "ss");

    //remove non word characters (as - is considered a non word character, we must replace it with _ before doing this
    str = str.replace(/-/gi, "_");
    myRe = /\W/gi;
    str = str.replace(myRe, "");

    //replace _ with - and remove duplicate -- 
    str = str.replace(/_/gi, "-");    
    str = str.replace(/-{2,}/g, "-");
    
    //remove non word cahracters (-) at start and end
    str = str.replace(/\W$/, "");
    str = str.replace(/^\W/, "");
    
    return str;
  },

  /**
   * @param cssSelector the cssSelector for the element containing the checkboxes that should be marked
   */
  registerCheckAllCheckbox : function(cssSelector){
    $(cssSelector).find('input[type=checkbox]:first').unbind('click').click(
      function(){
        if(this.checked){
          $(this).parents('form').find('fieldset :checkbox').each(
            function(num, elem){
              elem.checked = true;
            }
          );
        }
        else{
          $(this).parents('form').find('fieldset :checkbox').each(
            function(num, elem){
              elem.checked = false;
            }
          );
        }
      }
    );
    sixGroups.Tracking.track('/ajax/checkAllCheckboxes');
  },
  
  /**
   * inserts the cursor at a certain point inside a textarea
   * @param {Object} obj
   * @param {String} text
   */
  insertAtCaret : function(obj, text) {
    if(document.selection) {
      obj.focus();
      var orig = obj.value.replace(/\r\n/g, "\n");
      var range = document.selection.createRange();

      if(range.parentElement() != obj) {
        return false;
      }

      range.text = text;

      var actual = obj.value.replace(/\r\n/g, "\n");
      var tmp = actual;

      for(var diff = 0; diff < orig.length; diff++) {
        if (orig.charAt(diff) != actual.charAt(diff)) {
          break;
        }
      }

      for(var index = 0, start = 0;
        tmp.match(text)
          && (tmp = tmp.replace(text, ""))
          && index <= diff;
        index = start + text.length
      ) {
        start = actual.indexOf(text, index);
      }
    } else if(obj.selectionStart) {
      var start = obj.selectionStart;
      var end   = obj.selectionEnd;

      obj.value = obj.value.substr(0, start)
        + text
        + obj.value.substr(end, obj.value.length);
    }

    if(start != null) {
      setCaretTo(obj, start + text.length);
    } else {
      obj.value += text;
    }
  },

  setCaretTo : function(obj, pos) {
    if(obj.createTextRange) {
      var range = obj.createTextRange();
      range.move('character', pos);
      range.select();
    } else if(obj.selectionStart) {
      obj.focus();
      obj.setSelectionRange(pos, pos);
    }
  },
    
  
   

  /**
   * initializes a star rating
   *
   * @param {String} selector the css selector of the form
   * @param {String} targetSelector the css selector of the rating container
   * @param {Boolean} ratingAllowed submit possible?
   * @param {String} hoverMessage message to display on hover over stars
   */
  initRatingForm : function(ratingAllowed, hoverMessage, options){
    var settings = {
      formSelector : '#ratingForm',
      containerSelector: '#ratingContainer',
      listSelector: 'ul#rating'
    };
    settings = $.extend(settings, options);

    var starList = $(settings.listSelector);
    var formObject = $(settings.formSelector);
    var rateLinks = $(settings.listSelector).find('li a');
    var currentScore = $(settings.listSelector).find('li.filled').length;
    var currentMessage = $('#ratingInfo').html();
    var container = $(settings.containerSelector);


    /**
     * fill all stars up to score
     * @param {Integer} score
     */
    function hover(score){
      $(rateLinks).each(
        function(num){
          if($(this).text()<=score){
            $(this).css('background-position', '0 0');
          }
          else{
            $(this).css('background-position', '0 -25px');
          }
        }
      );
    }


    /**
     * if rating isn clicked, restore old val on mouseout
     */
    function restore(){
      $(rateLinks).each(
        function(num){
          if($(this).text()<=currentScore){
            $(rateLinks).css('background-position', '0 0');
          }
          else{
            $(this).css('background-position', '0 -25px');
          }
        }
      );
    }


    if (ratingAllowed){
      var formSettings = {
        target: settings.containerSelector, // target element(s) to be updated with server response
        beforeSubmit: function(){
          $(settings.containerSelector).prepend(
            '<small style="position:absolute;background:#fff;padding:5px;">'
            + __('loading', sixGroups.culture, sgRating.labels)
            +'</small>'
          );
        },
        success: function(data){
          $(container).animate(
            {'backgroundColor': '#E20177'},
            500,
            function(){
              $(container).animate(
                {'backgroundColor': '#f6f6f6'},
                500
              );
            }
          );
          try{            
            setTimeout(sixGroups.Tracking.track, 100);
          }
          catch(e){
            console.warn(e);
          }
        }
      };

      //submit form
      $(rateLinks).unbind('click').click(function(){
        $('#ratingScore').val($(this).text());
        $(formObject).ajaxSubmit(formSettings);
        this.blur();
        return false;
      });
    }

    //user is not logged in, dont allow form submit
    else {
      $(rateLinks).unbind('click').click(
        function(){
          this.blur();
          return false;
        }
      );
    }

    //hover actions for stars
    $(rateLinks).unbind('mouseover').mouseover(
      function(){
        if (ratingAllowed) {
          hover($(this).text());
          $('#ratingInfo').html(
              sgRating.getRatingInfo($(this).text())
          );
        }
        else{
          $('#ratingInfo').html(hoverMessage);
        }
      }
    );

    $(starList).mouseout(
      function(){
        if (ratingAllowed) {
          restore();
        }
        $('#ratingInfo').html(currentMessage);
      }
    );
  },

  /**
     * adds a new script tag to the head of the page
     * @param {String} url
     * @param {String} url
     */
    addScript: function(url, addRnd){
      if(addRnd != null){
        scriptObj.setAttribute('id', 'script_'+random);
        var random = (new Date()).getTime();//to prevent ie caching
        url = sixGroups.attachUrlParam(url, {'name':'rand', 'value':random});
      }
      //console.log('appending '+url);
      var scriptObjStr = '<script type="text/javascript" src="'+url+'" charset="utf-8"></script>';
      $('head').append(scriptObjStr);
    },
    
    /**
     * 
     * periodic refresh of page (bar)
     * @param {Boolean} logout
     * @param {Boolean} forceUpdate
     */
    refresh: function(logout, forceUpdate){
      if (this.settings.isWidget == null && this.settings.autoRefresh != false) {
      
        //only update if not currentyl updating
        if (sixGroups.updatingBar != true) {
          var barUrl = '/navigation/superNavigation/';
          var ifModified = true;
          
          if (typeof logout != 'undefined' && logout != null) {
            barUrl += '?logout=true';
          }
          
          //ie6 doesnt understand the if-modified header properly so we have to use a different url each time
          if ($.browser.msie) {
            ifModified: false;
          }
          
          $.ajax({
            url: barUrl,
            ifModified: ifModified,
            beforeSend: function(xhr){
              sixGroups.updatingBar = true;
              //if bar hasnt updated yet,set the if-modified since header to the current rcf date         
              if (sixGroups.updateCount == 0) {
                xhr.setRequestHeader("If-Modified-Since", sixGroups.lastModified);
              }
            },
            
            success: function(data){
              if (data.length > 0) {
                $('#sgBar').html(data);
                var newText = $('#lastShoutMessage').text();
                if (newText !== "") {
                  document.title = $('#lastShoutMessage').text();
                }
                sixGroups.updateCount++;
              }
            },
            
            complete: function(){
              sixGroups.updatingBar = false;
            }
          });
        }
      }
  },  
  
  setPid: function(pid){   
   this.pId = pid;
  },

  
  /**
   * return the current valid rfc 822 date for headers
   */
  getCurrentRfcDate: function(){
    var newDate = new Date();
    var utcDate = newDate .toUTCString();
    var sDate = newDate .toString();
    var time = sDate.substring(16, 24);
    var rfcDate = utcDate.substring(0, utcDate.length-12)+' '+time+' '+sDate.substring(sDate.length-5);
    return rfcDate;
  }
};


var sgRating = {
  getRatingInfo : function (starID) {
    return __('rating_'+starID, sixGroups.settings.culture, sgRating.labels);
  },

  labels : {
    'rating_1' : {
      'de_DE': 'Laaangweilig',
      'en_US': 'Poor'
    },
    'rating_2' : {
      'de_DE': 'Nichts besonderes',
      'en_US': 'Nothing special'
    },
    'rating_3' : {
      'de_DE': 'Cool',
      'en_US': 'Nice'
    },
    'rating_4' : {
      'de_DE': 'Echt cool',
      'en_US': 'Pretty cool'
    },
    'rating_5' : {
      'de_DE': 'Hammer!',
      'en_US': 'Awesome!'
    },
    'loading' : {
      'de_DE' : 'Bewertung wird gespeichert...',
      'en_US' : 'Saving rating...'
    }
  }
};

/**
 * Six Groups help system for small question marks, only used in old compontens. TODO: replace with clueTip
 */
sixGroups.helpSystem = function (){
  var settings = {};

  /**
  * a list of help DOM elements, each of them can have several triggers (click on a link, focus of a form)
  */
  var helpItems = [];

  var helpTriggers = [];

  /**
  * A named object of help DOM elements using the elem ids as property names
  */
  var helpObjects = {};
  
  var activeHelpId = null;

  function init(params){
    //move all help elements to the top of the DOM, so they can be positioned absolutely
    helpItems = $('.helpTooptip');
    //console.log('helpItems::', $(helpItems));
    helpTriggers = $('.triggerHelp');

    $.each(
      helpItems,
      function(num){
        //store help items in an object, that uses the helpItems Ids as properties
        helpObjects[this.id] = this;
        $(this).appendTo('body');
      }
    );
    registerEventListeners();
  }



  function registerEventListeners(){
     $(helpTriggers).each(function(num){
        var targetId = '';
        //console.info(this.tagName);
        if(this.tagName == 'A'){
            targetId = this.rel; //this is the small bubble element
            $(this).mouseover( 
              function(){            
                position(targetId, true);
              }
            );
            
            //hm this should only happen if the mouse is not over the bubble now
            $(this).mouseout(
              function(){             
                hide(targetId);
              }
            ); 
        }
        else{
          targetId = this.id; //this is an input field, selct, or texarea
        }     
        
      }
    );
    
    $('.closeHelp').click(
      function(){
        //console.log('clicked close',$(this).parents('div.helpTooptip'));
        $(this).parents('div.helpTooptip').hide();
        return false;
      }
    );
  }


  /**
  * @param helpElem
  *
  **/
  function position(inputElemId, show){
      var triggerBubbleElem = $('#triggerHelp_'+inputElemId);
      //console.info('triggerBubbleElem', triggerBubbleElem);
      var helpElem = $('#dynamicHelp_'+inputElemId);
      var dims = $(triggerBubbleElem).offset();
      
      try{
        var pageSize = sixGroups.getPageSize();
        var bodyWidth = $('#sixgroups').width();
        var left = dims.left - 144+$(triggerBubbleElem).width()/2;//($(helpElem).width()/2)+$(triggerBubbleElem).width()/2;
        var top = dims.top - $(helpElem).height()+15;
        
        //console.info(left, dims.left, ($(helpElem).width())+$(triggerBubbleElem).width()/2 );
        $(helpElem).css({
          'position' : 'absolute',
          'top': top,
          'left' : left
        });
        if(show === true){          
          $(helpElem).show();
          activeHelpId = inputElemId; 
          hideOthers(inputElemId);         
        }
      }
      catch(e){
        console.warn(e);
      }
      return false;
  }
  
  function hide(inputElemId){
    //only hide the element if the mous is not within the bubble 
    
    $('#dynamicHelp_'+inputElemId).unbind('mouseout').mouseout(
      function(){
        $('#dynamicHelp_'+inputElemId).hide();
      }
    );
        
  }
  
  function hideAll(){
    $(helpItems).hide();
  }
  
  function reposition(){
    //console.log('reposition '+activeHelpId);
    position(activeHelpId, false);
  }
  
  function hideOthers(inputElemId){
    $(helpItems).each(      
      function(num){
        if(this.id != 'dynamicHelp_'+inputElemId){
          $(this).hide();
        }
      }
    );
    
    return false;
  }

  return {
    init: init,
    hideAll: hideAll,
    position: position,
    reposition: reposition
  };
}();

//sg jquery plugins
/**
 * @param settings Object an object with config options
 * @option cookieName String the name of the cookie
 * @option hideSelector selector string for the close handlers
 * @option domain the cookie Domain
 */
jQuery.fn.sgCookieBox = function(settings) {
  var box = null;

  var config = {
      cookieName : 'sgJustFounded',
      hideSelector : '.sgCloseBox',
      domain: ''
  };

  if(settings){
    config = $.extend(config, settings);
  }

  var init = function(container){
    box = container;
    jQuery(config.hideSelector, box).click(function(){
      jQuery(box).hide();
      
      //delete the cookie
      try{
        var cookie =  jQuery.cookie(config.cookieName);
        //if(cookie != null){//no cookie capabilities :(
          jQuery.cookie(config.cookieName, 'false', {expires: -1, path: '/', domain: config.domain});
        //}        
      }
      catch(e){
        console.wanr('could no get cookie');
      }
      return false;
    });
  };

  return this.each(function(){
    init(this);
  });
};


 /**
* 
* @version 0.1
* @author Andreas Stephan 
* @param {Object} options an object to overwrite the default settings
* 
* @classDescription
*  enables like funcitonality on same domain pages for sigroups verticals
*  for more documentation on the callback see function http://docs.jquery.com/Ajax/jQuery.ajax#options 
*  
*  useage: init on Dom load on a link with a selector of your choice:
*  
*  jQuery(function(){
*    jQuery('.likeLink').sgInlineLike({
*      communityUrl: 'http://www.schoener-essen.de',
*      partnercodeId: 4
*    });
*  });
* 
* 
*
*/

jQuery.fn.sgInlineLike = function(options){
  return this.each(function(){
   
    var likeLink = this;
   

    /*
     * @param settings - default configuration
     * 
     */
    var settings = jQuery.extend({
      partnercodeId: '',
      communityUrl : 'http:://stage.schoenerEssen.de',
      
      /**
       * @param beforeSend Function overwrites the standard method that is called before the ajax call is fired
       */
      beforeSend: null, //overwrides the standard BeforeSend Method
      
      /**
       * @param success Function overwrites the standard success method, 
       *    recieves two arguments:
       *    - a json encoded data block containing
       *      - likeCount the new like count
       *   - a reference to the clicked element 
       *   
       */
      success: null,
      
       
      /**
       * param error Function overwrites the standard error method (alert)
       * 
       */
      error: null,
      
      /**
       * if set to false, the href attribute of the link will be used
       */
      rewriteUrl: true            
    }, options); 
    
    
    /**
     * stores currently pending calls to prevent they are fired twice
     */
    var callsInProgess = {
      
    } ;

    jQuery(likeLink).unbind('click').click(function (event) { //for some reason doenst work with "live" :(
      var likeUrl = '';
      
      if(settings.rewriteUrl === false){
        likeUrl = this.href;//external like widget already has the shout id and a proper url
      }
      else if( $(this).hasClass('unlike')){          
        likeUrl =   settings.communityUrl+'/like/unlikeByUrl?url='+encodeURIComponent(likeLink.href)+'&partnercodeId='+settings.partnercodeId;        
      }
      else{
        likeUrl = settings.communityUrl+'/like/LikeByUrl/?url='+encodeURIComponent(likeLink.href)+'&partnercodeId='+settings.partnercodeId;
      }      

      console.log('init inline like', settings, likeUrl);       
     
      //TODO: set a local cookie, so we know can store the liked iems of this user event if we dont have a server store available
                
      
      jQuery.ajax({
        url: likeUrl,
        dataType: "json",
        
        /**
         * executed before the ajax request, useful to show a loading animation or similar
         */
        beforeSend: function(XMLHttpRequest){    
          if(callsInProgess[this.url]){
            return false;
          }
          else{
            callsInProgess[this.url] = true;
            if(typeof settings.beforeSend == 'function'){
              settings.beforeSend(XMLHttpRequest);
            }
            else{
              jQuery(likeLink).removeClass('smallHeartGray').addClass('loading');
            }                
          }
        },
        
        success: function(data){
          if(typeof settings.success == 'function'){
            console.log('call custom func');
            settings.success.apply(this, [data, likeLink]);
            //this.apply(settings.success, [data);
          }
          //default behaviour
          else{
            var previousContent = jQuery(likeLink).html(); 
            jQuery(likeLink).html('<span>Danke!</span>');
            setTimeout(function(){
                jQuery(likeLink).find('span').fadeOut('fast', function(){
                  jQuery(likeLink).html(previousContent);
                });
              },
              2000);                                                
          }              
        },
        
        complete: function(XMLHttpRequest, textStatus){
          console.log('sg inline like call complete!');
          callsInProgess[this.url] = true;
          $('.sgLike').sgInlineLike(settings);//call like class again          
        },
        
        error: function(XMLHttpRequest, textStatus, errorThrown){
          if(typeof settings.error == 'function'){
            settings.error(XMLHttpRequest, textStatus, errorThrown);
          }
          alert('Sorry, an error occurred');              
        } 
      });
       return false;     
    });
  });
};