//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){}


function outputDebug(){
  if($('#superDebug3000').length < 1){
    $('body').append('<div id="superDebug3000">'+messages.join('<br/>')+'</div>');    
  }
  else{
    $('#superDebug3000').empty().html(messages.join('<br/>'));
  }
}

/**
 *
 * @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,
  //blockUiMessage : '',
  /**
   * stores all pending updates via ajax, if there are active posts, delay all polling requests till after finish
   */
  pendingUpdates: [],
  
  /**
   * global settings, can be overwritten with params object in init function
   * @see init()
   */
  settings : {
    culture: 'de_DE',
    outputType: 'html',
    pId: 0,//the partnercodeId
    isWidget: null,
    loggedIn: false,
    sgDomain: 'sixgroups.com',
    userId: null,
    tracking: 'off',
    barUpdates: 'on'
    //,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;
    });
  },
  

  
  
/**
 * 
 * @param {Object} customSettings
 */
  init:function(customSettings){
    this.settings = $.extend(this.settings, customSettings);    
    this.culture = this.settings.culture;    
    this.executeInitFuncs();
    this.initBlockUiDefaults();
	this.initCluetip();
    this.initLogoutLink();
    this.initFaviconize();
    
    if (this.settings.userId !== null) {
      this.settings.loggedIn = true;
    }
        
    try{
      //widget
      if(this.settings.isWidget !== null){                
        this.registerEventHandlers($('#livecommunity'));       
      }

      //nomal page
      else{        
        this.registerEventHandlers('#sixgroups');        
        sgBar.init();       
      }      
      this.initThickboxes();      
      
    }
    catch(e){
      console.warn(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);      
    }
    //console.info('pending updates after setAjaxPendingState call', this.pendingUpdates);
    
  },


  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');
		}
	});
  },
  
  /**
   * logout animation
   */
  initLogoutLink: function(){
    $('#logoutLink').click(
      function() {
        $('#logoutLink').html('<img src="/images/loadingAnimation/arrows_pink.gif"/>');
      }
    );
  },
	
  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){
            sixGroups.registerEventHandlers();            
          }
          else{
            settings.onSuccess(responseText, textStatus, XMLHttpRequest);            
          }
          setTimeout(sixGroups.Tracking.track, 100);
          $(targetContainerSelector).unblock();
        }
      );
      return false;
    };
    
    $('ul.pagination li a').click(onPagerLinkClicked);
  },

  //attach outputType=iframe to all Links and forms
  /**
   * @deprecated? the iFrame parameter should be eliminated
   */
  initWidgetLinks: function(){
    $('a').each(
      function(i) {
        this.href = sixGroups.addOutputTypeToUrl(this.href, 'iFrame');
      }
    );
    $('form').each(
      function(i) {
        this.action = sixGroups.addOutputTypeToUrl(this.action, 'iFrame');
      }
    );
  },
	
	
  /**
   * attach an output type param to a url
   * @param {String} url
   * @param {String} outputType
   * @return {String} url the formatted url
   */
  addOutputTypeToUrl: function(url, outputType){
   url = this.attachUrlParam(url, {'name':'outputType', 'value':outputType});
   return url;
  },

  /**
   * 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
   */
  attachUrlParam: function (url, param){
    if(url != null){
      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;
    }
  },
  
  /**
   * 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,
    
    
    
    /**
     * 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){      
      try{
        var trackingUrl = null;
        
        if(this.pageTracker == null){
          this.init();
        }
        
        //if a param is passed, use the defined value
        if(typeof url != 'undefined'){
          trackingUrl = url;        
        }
        
        //an action that was set by the tracking filter, overwrites everything else
        if(sixGroups.Tracking.next != ''){          
          trackingUrl = sixGroups.Tracking.next;
          sixGroups.Tracking.next = '';
        }        
        
        if(sixGroups.settings.tracking == 'on'){
          if(sixGroups.settings.isWidget != null){
            this.pageTracker._setVar('externalPi');
          }
          var pId = sgBar.getPid();
          if(pId >0){
            //maybe use setEvent instead?
            //this.pageTracker._setVar('Partnersite: '+pId);
            //console.info('set Partnersite for tracking', pId);
          }
          if(trackingUrl != null && trackingUrl.length > 0){
            this.pageTracker._trackPageview(trackingUrl);
            //console.info('custom tracking ', trackingUrl);
          }
          else{
            this.pageTracker._trackPageview();
            //console.info('standard tracking ');
          }
        }
        else{
          console.info('tracking is off, url to track: '+trackingUrl);
        }
      }
      
      catch(e){
        console.warn('could not track', trackingUrl, e);
      }      
    },
    
    /**
     * initializes the tracking
     */
    init: function(){
      if(typeof _gat != 'undefined'){
        this.pageTracker = _gat._getTracker("UA-2124570-1");
        this.pageTracker._setDomainName(".sixgroups.com");
        this.pageTracker._setAllowHash(false); 
      }
      else{
        console.warn('google analytics not installed');
      }
    }
  }, 
  


  /**
   * registers event handlers on main content
   */
  registerEventHandlers : function(target){
     //attach all event handlers for forms
    if(typeof target == "undefined"){
      target = $('#page_margins');
    }    
    
    //TODO: refactor to add onclick only
    //attach external links and openInBar Links (not needed in overlay)
    $('a', target).each(
      function(num){
        /*if(this.href.indexOf(sixGroups.settings.sgDomain) > -1){
          this.href = sixGroups.attachUrlParam(this.href, {'name':'partnercodeId', 'value':sixGroups.settings.pId});  
        }*/
       
        if(this.className.indexOf('externalIfInCommunityBar') > -1 && sixGroups.settings.isWidget !== null){
          this.rel= 'external';
        }
        
        $(this).filter('[rel="external"]').unbind('click').click(
          function(){
            var newWindow = window.open(this.href, '_blank');
            newWindow.focus();
            return false;
          }
        );
      }
    );

     $('#footer a[rel=external]').unbind('click').click(
      function(){
        var newWindow = window.open(this.href, '_blank');
        newWindow.focus();
        return false;
      }
    );
    
     //ie6 button fix
     $('button[class=alternateSubmit]').click(
      function(){ 
        $('button[class=alternateSubmit]').attr('disabled', 'disabled');
        $(this).removeAttr('disabled');        
      }
    );


    //this.initDynamicHelp();
    this.initFormButtons();
  },

  /**
   * 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);
    },

  // disables buttons in forms on submit to prevent more than 1 submit
  initFormButtons : function(){
    /* $("form").submit(
      function(){
        $(this).find('button.disableOnSubmit').attr('disabled', 'disabled');
      }
    );*/
  },
  
  /**
   * 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...'
    }
  }
};


/**
 *
 * Bar class
 *
 */

var sgBar = function(){
  
  /**
  * the interval to refresh the bar
  */
  var barRefreshInterval = 30000;
  var barRefreshTask = null;
  
  /**
   * indicates, whether the bar is currently refreshing or not
   */
  var updatingBar = false;
  
  /**
   * number of times the bar was not updated because it wasnt modified
   */
  var noUpdateCount = 0;
  
  /**
   * no of times the super navigation refresh was requested
   */
  var updateCount = 0;
  
  //if opened o an externla bar, this indeicates the partnercodeId
  var pId =0;
  
  /**
   * an array that hold all anchor elements in overlay
   */
  var linksInOverlay = null;
  
  var lastModified = "Thu, 01 Jan 1970 00:00:00 GMT";
  
  /**
   * initializes the sixGroups Bar
   */
  function init(){
    if(sixGroups.settings.barUpdates != 'off' && sixGroups.settings.pId === 0){
      initPeriodicRefresh();  
    }    
    $('#sgBarContentHolder').show();
    lastModified = sixGroups.getCurrentRfcDate();//TODO: use serverside date instead
  }
  
  /**
  *
  *
  */
  function reload(logout, forceUpdate){    
    //TODO: pass the last time, the bar was updated on initial load
    //console.log('update?');
    
    if (updatingBar != true /*&& sixGroups.pendingUpdates.length < 0*/ ){
      //console.log('yes');
      var barUrl = "";
      if(typeof logout != 'undefined' && logout != null){      
        barUrl = '/navigation/superNavigation/?logout=true';
      }
      else{
        barUrl =  '/navigation/superNavigation/';
        
        //ie6 doesnt understand the if-modified header properly so we have ro use a different url each time
        if($.browser.msie && parseInt($.browser.version) < 7){          
          var random = Math.ceil(Math.random()*1000);
          barUrl =  '/navigation/superNavigation/?random='+random;  
        }      
      }
      
      $.ajax({
        url: barUrl,
        ifModified: true,
        beforeSend: function(xhr){
          updatingBar = true;     
          //if bar hasnt updated yet,set the if-modified since header to the current rcf date         
          if(updateCount == 0){
             xhr.setRequestHeader("If-Modified-Since", lastModified);
          }
        },
        
        success:function(data){          
          if(data.length > 0){
            $('#sgBar').html(data);
            var newText =  $('#lastShoutMessage').text();
            if(newText !== ""){
              document.title = $('#lastShoutMessage').text();            
            }
            init();
            updatingBar = false;
            noUpdateCount=0;
            updateCount++;  
          }          
        },
        
        complete: function(){          
          //console.log('');
          updatingBar = false;
        }
      });      
    }
    else {
      //console.log('no');
    }
  }
  
  /**
   * initializes the timer for updating the bar
   */
  function initPeriodicRefresh(){
    //clearInterval(barRefreshTask);
    //console.log('initializing periodic refresh of bar with '+(barRefreshInterval/1000)+' seconds');
    barRefreshTask = setInterval(
        function(){          
          sgBar.reload();
        }, 
        barRefreshInterval
    );
  }
 
 
 
 /**
  * set the partnercode ID
  * @param {Object} pid
  */
 function setPid(pid){   
   pId = pid;
 }
 
 function getPid(pid){
   return pId;
 }


  //return all public functions and variables
  return{
    init: init,    
    reload: reload,
    updatingBar: updatingBar,    
    setPid: setPid,
    getPid: getPid
  };

}();

/**
 * Six Groups help system for small question marks
 */
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
    /* if(activeHelpId == inputElemId){
      $('#dynamicHelp_'+inputElemId).hide();
    }
    activeHelpId = null; */    
    
    $('#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();
      var cookie =  jQuery.cookie(config.cookieName);
      if(cookie != null){//no cookie capabilities :(
        jQuery.cookie(config.cookieName, 'test', {expires: -1, path: '/', domain: config.domain});
      }
      return false;
    });
  };

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