/*************************************************************
Damien Benier for iShopYouShop.com
*************************************************************/

var browserIsIE = (document.all && !window.opera);
var browserIsIE6 = browserIsIE && !window.XMLHttpRequest;

/**************** Logger stuff ****************/
MyLogger = {
  doLog: false,
  
  log: function(text){
    if (this.doLog){
      if (window['console'] === undefined) console.log(text);
      else                                 alert(text);
    }
  }
};


/* Helper for calling a function when page is loaded */
document.executeOnceLoaded = function(callback)
{
  if (document.loaded) window.setTimeout(function(){ callback(); }, 10);
  else                 Event.observe(document, 'dom:loaded', callback);
}


/* Helper for setting the url part after the # without scrolling */
document.location.updateHash = function(hashValue)
{
  var scroll = document.viewport.getScrollOffsets();
  
  if (hashValue.include('#')) hashValue = hashValue.split('#')[1];
  
  window.location.href = '#' + hashValue;
  window.scrollTo(scroll[0], scroll[1]);
  
  return false;
}


/* Helper for loading a new url */
document.location.load = function(url, options)
{
  MyLogger.log('loading ' + url);

  options = Object.extend({forceReload:true}, options);
 
  if (url != '#')
  {
    var urlParts = normalizeUrl(url).split('#');
    var currentUrlParts = window.location.href.split('#');
   
    if ((urlParts[0] != currentUrlParts[0]) || !options.forceReload) window.location.href = url;
    else
    {
      if (urlParts[1]) document.location.updateHash(urlParts[1]);
      document.location.reload();
    }
  }
  
  return false;
}

/* Ajax request helper */
function ajaxRequest(url, options)
{
  MyLogger.log('ajax request: ' + url);
  
  options = Object.extend({evalJS:true, onSuccess: function(response){ response.responseText.extractScripts().each(function(text){ eval(text); }); }}, options);
  
  new Ajax.Request(url, options);
  
  return false;
}

/* Json request helper */
function JsonRequest(url, onCompleteCallback)
{
  this.onCompleteCallback = onCompleteCallback;
  this.request = ajaxRequest(url, {
    method:'get',
    onSuccess: function(transport, json){
      if (!json) json = transport.responseText.evalJSON();
      onCompleteCallback(json);
    },
    onFailure: function(transport){
      onCompleteCallback(null);
     }
  });
}

Element.addMethods({

  deactivate: function(elt, options){
    options = Object.extend({ time: 0, loading: false }, options || {});
    
    elt.makePositioned();
    
    var deactivator = new Element('div', { className: 'deactivated' + (options.loading ? ' deactivated-loading' : '') });
    deactivator.innerHTML = '&nbsp;';
    deactivator.clonePosition(elt, {setLeft:false, setTop:false});
    elt.insert(deactivator);
    elt.deactivator = deactivator;
    
    elt.onclickSave = elt.onclick;
    
    if (options.time > 0) window.setTimeout(function(){ elt.reactivate() }, options.time * 1000);
  },
  
  reactivate: function(elt){
    elt.undoPositioned();
    if (elt.deactivator) elt.deactivator.remove();
    if (elt.onclickSave) elt.onclick = elt.onclickSave;
  },
  
  load: function(elt, url, options){
    options = Object.extend({force:false, replace:false, scroll:true, method:'get', parameters:'', callback:null}, options || {});
    
    url = normalizeUrl(url);
    
    if ((elt.url != url) || options.force)
    {
      elt.deactivate({time:30, loading:true});
      if (options.scroll) new Effect.ScrollTo(elt);
      
      ajaxRequest(url, {
        method: options.method,
        parameters: options.parameters,
        onSuccess: function(transport){
          elt.reactivate();
          if (options.replace) elt.replace(transport.responseText);
          else                 elt.update(transport.responseText);
          elt.url = url;
          processContent(elt);
          if (options.callback) options.callback(url, elt);
          if (pageTracker) pageTracker._trackPageview(url + ' [AJAX]'); /* Google Analytics */
        }
      });
    }
    else if (options.callback) options.callback(url, elt);
    
    return false;
  },
  
  simulateClick: function(elt){
    if (!elt.click) elt.click = function(){ if ((!elt.onclick || elt.onclick() != false) && elt.href) document.location.load(elt.href); };
    
    elt.click();
  }
  
});

function onPageExit()
{
  //$(document.getElementsByTagName('body')[0]).deactivate({time:30, loading:true});
}

Event.observe(window, 'unload', onPageExit, false);


/**************** Social Sharing Stuff ****************/

SocialSharer = {
  
  facebookShare: function(url, text){
    url = normalizeUrl(url);
    
    return popup('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(url) + '&t=' + encodeURIComponent(text), 'facebook', {width:650, height:300});
  },
  
  twitterShare: function(url, text){
    url = normalizeUrl(url);
    
    return popup('http://twitter.com/home?status=' + encodeURIComponent(text + ' ' + url), 'twitter', {width:800, height:400});
  }
  
};

/* Helper for popup windows */
function popup(href, name, options)
{
  options = Object.extend({details:'no', width:500, height:400}, options || {});
  
  window.open(href, options.name, 'menubar=' + options.details + ', status=' + options.details + ', scrollbars=' + options.details + ', menubar=' + options.details + ', width=' + options.width + ', height=' + options.height);
  return false;
}

var uniqueIdPointer = 100;
function getUniqueId(){ return uniqueIdPointer++; }

/* Helper to get an url argument */
function getUrlArg(name, url)
{
  url = url || document.location.href;
  
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = '[\\?&]' + name + '=([^&#]*)';
  var regex = new RegExp(regexS);
  var results = regex.exec(url);
  if (results == null) return '';
  else                 return unescape(results[1]);
}

/* Helper to normalize a relative url */
// http://www.json.com/2008/04/08/the-future-ajax-wrapper/
function normalizeUrl(url, baseUrl)
{
  var relativeUrl = url;
  baseUrl = baseUrl || document.location.href;
  
	if (relativeUrl.match(/\w+:\/\//)) return relativeUrl;
	if (relativeUrl.charAt(0) == '/')
  {
    baseUrl = baseUrl.match(/.*\/\/[^\/]+/);
    return (baseUrl ? baseUrl[0] : '') + relativeUrl;
	}
  
	baseUrl = baseUrl.substring(0,baseUrl.length - baseUrl.match(/[^\/]*$/)[0].length);
	
  if (relativeUrl == '.') return baseUrl;
	
  while (relativeUrl.substring(0,3) == '../')
  {
    baseUrl = baseUrl.substring(0, baseUrl.length - baseUrl.match(/[^\/]*\/$/)[0].length);
    relativeUrl = relativeUrl.substring(3);
  }
  
  return baseUrl + relativeUrl;
}


/* by Jonas Raoni Soares Silva http://jsfromhell.com/array/shuffle [v1.0] */
function shuffleArray(o)
{
  for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  return o
}

function parseIntNoNan(value)
{
  var parsedIn = parseInt(value);
  return isNaN(parsedIn) ? 0 : parsedIn;
}

function checkUrlForAutoClick()
{
  var urlParts = document.location.href.split('#click:');
  
  if (urlParts[1]) window.setTimeout('$(\'' + urlParts[1] + '\').simulateClick();', 500);
}

document.executeOnceLoaded(checkUrlForAutoClick);


/**************** Header stuff ****************/

Header = {
  hideExpansionsTimer: null,

  init: function(){
    var menuExpansionsContainer = $('menu-expansions-container');
    $$('.menu-item').each(function(menuItem){
      var menuExpansion = $(menuItem.id + '-expansion');
      if (menuExpansion)
      {
        menuItem.observe('mouseover', function(e){ Header.stopHideExpansionsTimer(); Header.hideExpansions(); $(menuExpansion).show(); });
        menuItem.observe('mouseout',  function(e){ Header.startHideExpansionsTimer(); });
        menuExpansion.observe('mouseover', function(e){ Header.stopHideExpansionsTimer(); });
        menuExpansion.observe('mouseout',  function(e){ Header.startHideExpansionsTimer(); });
        menuExpansion.clonePosition(menuExpansionsContainer, {setWidth:false, setHeight:false});
      }
    });
  },

  hideExpansions: function(){
    $$('.menu-expansion').invoke('hide');
    Header.hideExpansionsTimer = null;
  },
  
  startHideExpansionsTimer: function(){
    if (!Header.hideExpansionsTimer) Header.hideExpansionsTimer = window.setTimeout('Header.hideExpansions();', 500);
  },
  
  stopHideExpansionsTimer: function(){
    window.clearTimeout(Header.hideExpansionsTimer);
    Header.hideExpansionsTimer = null;
  }
};

Event.observe(document, 'dom:loaded', Header.init, false);


/**************** Carrousel stuff ****************/

Carrousel = Class.create();
Object.extend(Carrousel.prototype, {
  
  sectionsCount: 0,
  currentSection: null,
  currentScrollEffect: null,
  currentResizeEffect: null,
  
  initialize: function(containerId, options){
    this.container = $(containerId);
    this.options = Object.extend({width:parseInt(this.container.getWidth()), height:0, defaultSection:null, sectionClassName:'carrousel-section', contentClassName:'carrousel-content', transition:Effect.Transitions.sinoidal, callback:null}, options || {});
    this.content = this.container.down('.' + this.options.contentClassName);
    this.currentSection = this.getSectionAt(0);
    
    var _this = this;
    this.content.select('.' + this.options.sectionClassName).each(function(section){
      _this.sectionsCount++;
      section.setStyle({float:'left', width: _this.options.width + 'px'});
    });
    this.content.setStyle({width:this.options.width * this.sectionsCount + 'px'});
    this.content.insert('<br style="clear:both;" />');
    
    /*if (!this.options.defaultSection)
    {
      var urlParts = document.location.href.split('#');
      var gotoSectionElt = this.content.down('#' + urlParts[1] + '-page');
      
      this.options.defaultSection = gotoSectionElt ? gotoSectionElt : this.getSectionAt(0);
    }*/
    
    if (!this.options.defaultSection) this.options.defaultSection = this.getSectionAt(0);
    
    this.goTo(this.options.defaultSection, true);
  },

  goTo: function(section, resizeAfterEffect){
    if (this.currentScrollEffect) this.currentScrollEffect.cancel();
    
    var gotoSection = $(section);
    var offset = gotoSection.positionedOffset().left;
    var resizeCallback = resizeAfterEffect ? this.adaptSizeToContent.bindAsEventListener(this) : null;
    
    this.currentScrollEffect = new Effect.Move(this.content, {x: -offset, duration: 0.5, transition: this.options.transition, mode:'absolute', afterFinish:resizeCallback});
    this.currentSection = gotoSection;
    
    if (this.options.callback) this.options.callback(this, gotoSection);
    
    return false;
  },

  getSectionAt: function(i){
    return this.content.down('.' + this.options.sectionClassName, i);
  },

  goToNext: function(){
    var nextSection = this.currentSection.next('.' + this.options.sectionClassName);
    if (!nextSection) nextSection = this.getSectionAt(0);
    return this.goTo(nextSection);
  },

  goToPrevious: function(){
    var previousSection = this.currentSection.previous('.' + this.options.sectionClassName);
    if (!previousSection) previousSection = this.getSectionAt(this.sectionsCount - 1);
    return this.goTo(previousSection);
  },

  parseAndGo: function(url){
    var urlParts = url.split('#');
    var section = this.content.down('#' + urlParts[1]);
    var loadUrl = normalizeUrl(urlParts[0]);
    var loadContent = loadUrl && (loadUrl != document.location.href.split('#')[0]) && (loadUrl != section.url);
    
    if (loadContent) section.load(loadUrl, {scroll:false, duration: 0.5, callback:this.adaptSizeToContent.bind(this)});
    
    return this.goTo(section, !loadContent);
  },

  adaptSizeToContent: function(){
    if (this.currentResizeEffect) this.currentResizeEffect.cancel();
    
    var height = this.options.height ? this.options.height : this.currentSection.getHeight();
    
    this.currentResizeEffect = new Effect.Morph(this.container, {style: {height: height + 'px'}, transition: this.options.transition})
  }

});

function carrouselTabsOnChange(carrousel, section)
{
  $(carrousel.container.id + 'Tabs').select('.tab').each(function(tab){
    tab.className = tab.href.endsWith('#' + section.id) ? 'tab tabSelected' : 'tab';
  });
}

/**************** Polaroid stuff ****************/

Polaroid = {

  fill: function (elt, polaroid){
    if (!(elt = $(elt))) return;
    
    if (polaroid.text)  elt.down('.textContainer').down().innerHTML = polaroid.text;
    if (polaroid.label) elt.down('.label').replace((polaroid.label == 'none') ? '<span class="label">&nbsp;</span>' : '<img src="' + imagesRepository + 'label_' + polaroid.label + '.gif" class="label" />');
    if (polaroid.image) new ImagePreview(polaroid.image, {div:elt.down('.pictureContainer').down(), nolink:true});
    if (polaroid.url){
      elt.down('.pictureContainer').down('a').href = polaroid.url;
      elt.down('.textContainer').down('a').href = polaroid.url;
    }
    if (polaroid.buttonsValue) this.setButtons(elt, polaroid.buttonsValues);
  },
  
  getText: function(elt){
    if (!(elt = $(elt))) return;
    
    return elt.down('.textContainer').down().innerHTML;
  },

  clear: function(elt){
    if (!(elt = $(elt))) return;
    
    elt.down('p').innerHTML = '';
    elt.down('.pictureContainer').innerHTML = '';
  },
  
  setButtons: function(elt, values){
    if (!(elt = $(elt))) return;
    var buttons = elt.hasClassName('polaroid-buttons') ? elt : elt.next('.polaroid-buttons');

    if (buttons){
      for (key in values) {
        if (button = buttons.down('.btn-' + key)) button[values[key] ? 'addClassName' : 'removeClassName']('btn-on');
      };
    }
  },
  
  buttonsValues: {},
  
  setButtonsFromRecord: function(elt){
    if (!(elt = $(elt))) return;
    var buttons = elt.hasClassName('polaroid-buttons') ? elt : elt.next('.polaroid-buttons');
    var results = /polaroid-buttons-(\S+)/.exec(buttons.className);
    
    if (results){
      var key = results[1];
      var values = this.getButtonsValueRecord(key);
      if (values) this.setButtons(buttons, values);
    }
  },
  
  addButtonsValueRecord: function(className, values){
    this.buttonsValues[className] = values;
  },
  
  getButtonsValueRecord: function(key){
    return this.buttonsValues[key];
  },
  
  parseAndSetButtonsValuesFromRecords: function(filter){
    var _self = this;
    $$(filter ? filter : '.polaroid-buttons').each(function(polaroidButtonsElt)
    {
      _self.setButtonsFromRecord(polaroidButtonsElt);
    });
  }

};


/**************** Products listing stuff ****************/

ProductsListing = Class.create();
Object.extend(ProductsListing.prototype, {
  
  selectedId: 0,
  type: '',
  clickCallback: null,
  buttonClickCallback: null,
  
  initialize: function(type, options){
    this.type = type;
    this.options = Object.extend({clickCallback:null, buttonClickCallback:false, container:null}, options || {});
  },
  
  click: function(elt, product){
    elt = $(elt);
    var buttonsElt = $('polaroid-' + this.type + '-buttons')
    
    this.selectedId = product.id;
    Polaroid.fill('polaroid-' + this.type, {image:elt.down().src, text:elt.getAttribute('alt'), url:product.url});
    buttonsElt.classNames().each(function(className){ buttonsElt.removeClassName(className); });
    buttonsElt.addClassName('polaroid-buttons');
    buttonsElt.addClassName('polaroid-buttons-product-' + product.id);
    Polaroid.setButtons(buttonsElt, {like:false, dislike:false, own:false});
    Polaroid.setButtonsFromRecord(buttonsElt);
    
    return false;
  },
  
  buttonClick: function(id, btn, buttonElt){
    if (this.selectedId)
    {
      var url = buttonElt.href.replace('/' + id, '/' + this.selectedId);
      if (btn == 'list') lightbox.load(url);
      else               ajaxRequest(url);
    }
    return false;
  }
  
});

/**************** Image preview stuff ****************/
ImagePreview = Class.create();
Object.extend(ImagePreview.prototype, {

  initialize: function(url, options){
    this.url = url;
    this.isLoaded = false;
    this.image = null;
    this.options = Object.extend({div:null, callback:null, chop:true, data:null, title:'', nolink:false}, options || {});
    this.options.div = $(this.options.div);
    this.options.previewWidth = this.options.width || options.size || (this.options.div ?  this.options.div.getWidth() - parseIntNoNan(this.options.div.getStyle('border-left-width')) - parseIntNoNan(this.options.div.getStyle('border-right-width')) - (2 * parseIntNoNan(this.options.div.getStyle('border-width'))) : 100);
    this.options.previewHeight = this.options.height || options.size || (this.options.div ?  this.options.div.getHeight() - parseIntNoNan(this.options.div.getStyle('border-top-width')) - parseIntNoNan(this.options.div.getStyle('border-bottom-width')) - (2 * parseIntNoNan(this.options.div.getStyle('border-width'))) : 100);
    
    this.load();
  },
  
  load: function(){
    this.image = new Image();
    Event.observe(this.image, 'load', this.onImageLoaded.bindAsEventListener(this));
    this.image.src = this.url;
  },
  
  onImageLoaded: function(){
    this.isLoaded = true;
    
    if (this.options.callback) this.options.callback(this, this.options.data);
    if (this.options.div) this.options.div.innerHTML = this.getHTML(this.options.nolink ? '' : this.options.div.href);
  },
  
  getHTML: function(href){
    if (!this.isLoaded) return 'not loaded';
    
    var imageRatio = (this.image.width / this.image.height);
    var previewRatio = (this.options.previewWidth / this.options.previewHeight);
    var isImageTooWide = (imageRatio > previewRatio);
    var keepPreviewWidth = (this.options.chop != isImageTooWide);
    
    this.displayWidth = keepPreviewWidth ? this.options.previewWidth : Math.round(this.options.previewHeight * imageRatio);
    this.displayHeight = keepPreviewWidth ? Math.round(this.options.previewWidth / imageRatio) : this.options.previewHeight;
    
    var xOffset = Math.round((this.options.previewWidth - this.displayWidth) / 2);
    var yOffset = Math.round((this.options.previewHeight - this.displayHeight) / 2);
    
    var titleHtml = this.options.title ? ' title="' + this.options.title + '"' : '';
    var onclickHtml = href ? ' onclick="return document.location.load(\'' + href + '\');"' : '';
    
    html = '';
    html += '<span style="display:block; margin:0px; padding:0px; width:' + this.options.previewWidth + 'px; height:' + this.options.previewHeight + 'px; overflow:hidden !important;">';
    html +=   '<img' + onclickHtml + ' src="' + this.url + '" style="width:' + this.displayWidth + 'px !important; height:' + this.displayHeight + 'px !important; margin:' + yOffset + 'px ' + xOffset + 'px !important;"' + titleHtml + '>';
    html += '</span>';
    
    return html;
  }
  
});

ImagePicker = Class.create();
Object.extend(ImagePicker.prototype, {

  initialize: function(options){
    this.images = {};
    this.options = Object.extend({div:null, minSize:32, previewSize:100, defaultClass:'', selectedClass:'', chop:false, onSelectCallback:null, onDoubleClickCallback:null}, options);
    if (this.options.div) $(this.options.div).imagesPicker = this;
  },
  
  onImageReadyToBeAdded: function(imagePreview, _this){
    _this.images[imagePreview.url].isDisplayable = (imagePreview.image.width >= _this.options.minSize) && (imagePreview.image.height >= _this.options.minSize);
    _this.refreshDiv();
    if (_this.images[imagePreview.url].isSelected) _this.select(imagePreview.url, true);
  },
  
  getCount: function(selected){
    selected = selected || false;
    var num = 0;
    for (url in this.images)
    {
      if (this.images[url].isDisplayable && (!selected || this.images[url].isSelected)) num++;
    }
    return num;
  },
  
  add: function(url, selected){
    if (!this.images[url]) this.images[url] = {imagePreview:new ImagePreview(url, {size:this.options.previewSize, callback:this.onImageReadyToBeAdded, chop:this.options.chop, data:this}), isSelected:selected, isDisplayable:false, div:null};
    else if (selected) this.select(url, true);
  },
  
  click: function(url){
    this.select(url, !this.images[url].isSelected);
  },
  
  doubleClick: function(url){
    if (this.options.onDoubleClickCallback)  this.options.onDoubleClickCallback(url, this.images[url].isSelected);
  },
  
  select: function(url, selected){
    if ($(this.images[url].div))
    {
      if (selected) $(this.images[url].div).addClassName(this.options.selectedClass);
      else          $(this.images[url].div).removeClassName(this.options.selectedClass);
    }
    
    this.images[url].isSelected = selected;
    
    if (this.options.onSelectCallback)  this.options.onSelectCallback(url, selected);
  },
  
  refreshDiv: function(){
    if (!this.options.div) return;
    
    var html = '';
    
    for (url in this.images)
    {
      if (!this.images[url].isDisplayable) continue;
      
      var id = this.options.div + '_' + url;
      
      html += '<div id="' + id + '"';
      html += ' style="width:' + this.options.previewSize + 'px; height:' + this.options.previewSize + 'px;"';
      html += ' class="' + this.options.defaultClass + (this.images[url].isSelected ? ' ' + this.options.selectedClass : '') + '"';
      html += ' onclick="$(\'' + this.options.div + '\').imagesPicker.click(\'' + url + '\');"';
      html += ' ondblclick="$(\'' + this.options.div + '\').imagesPicker.doubleClick(\'' + url + '\');"';
      html += '>';
      html +=   this.images[url].imagePreview.getHTML();
      html += '</div>\n';
      
      this.images[url].div = id;
    }
    
    $(this.options.div).innerHTML = html;
  }
  
});

/**************** Mosaic stuff ****************/;

Mosaic = {

  preload: function(imageName)
  {
    var image = new Image();
    image.onload = function(){ window.setTimeout(Mosaic.show, 1000); }
    image.src = imageName;
    
    return image;
  },

  show: function()
  {
    var mosaics = shuffleArray(['A', 'B', 'C', 'D']);
    
    $('mosaic-'+mosaics[0]).className += ' topleft';
    $('mosaic-'+mosaics[1]).className += ' topright';
    $('mosaic-'+mosaics[2]).className += ' bottomleft';
    $('mosaic-'+mosaics[3]).className += ' bottomright';
    
    $('mosaics-list').select('a').each(function(mosaicElt){ mosaicElt.addClassName('bubble-info bubble-info-blue'); });
    
    InfoBubble.addInfoBubbleEvents('mosaic');
    
    $('mosaic-loader').innerHTML = '';
    new Effect.Fade('mosaic-loader', {duration:3});
  }

};


/**************** Info bubbles stuffs ****************/;

InfoBubble = {
  
  bubbleElt: null,
  
  showForElt: function(elt)
  {
    if (!elt.alt) elt.alt = elt.getAttribute('alt');
    
    var isBlue = elt.hasClassName('bubble-info-blue');
    this.bubbleElt[isBlue ? 'addClassName' : 'removeClassName']('hover-bubble-blue');
    this.bubbleElt[isBlue ? 'removeClassName' : 'addClassName']('hover-bubble-pink');
    
    this.bubbleElt.clonePosition(elt, {setWidth:false, setHeight:false});
    this.bubbleElt.innerHTML =  elt.alt;
    this.bubbleElt.show();
    
    return false;
  },
  
  hide: function(e)
  {
    this.bubbleElt.hide();
  },
  
  addInfoBubbleEvents: function(elt)
  {
    if (!this.bubbleElt) this.init();
    
    var _self = this;
    
    $(elt).select('.bubble-info').each(function(bubbleInfoElt){
      bubbleInfoElt.observe('mouseover', function(e){ _self.showForElt(this); });
      bubbleInfoElt.observe('mouseout',  function(e){ _self.hide(); });
    });
  },
  
  init: function()
  {
    this.bubbleElt = new Element('div', { id:'hover-bubble', style:'display:none;' });
    document.getElementsByTagName('body')[0].appendChild(this.bubbleElt);
  }
};

/**************** User login stuff ****************/

User = Class.create();
Object.extend(User.prototype, {
  isLoggedIn: false,
  id: -1,
  name: null,
  image: null,
  facebookUid: -1,
  connectedFacebookUid: -1,
  logInCallbacks: new Array(),
  lists: new Array(),
  
  initialize: function(){
  },
  
  logIn: function(userValues, options){
    MyLogger.log('User logIn (id: ' + userValues.id + ')');

    options = Object.extend({callCallbacks:true, updateFacebookStatus:true, closeLightbox:true, lists:null}, options);
    
    this.isLoggedIn = true;
    this.id = userValues.id;
    this.name = userValues.name;
    this.image = userValues.image.length ? userValues.image + '.thumb.small' : userValues.facebookImage;
    this.facebookUid = userValues.facebookUid;
    
    bod = document.getElementsByTagName('body')[0];
    bod.className = 'memberLoggedIn';
    
    $('member-name').innerHTML = this.name;
    new ImagePreview(this.image.length ? this.image : imagesRepository + 'no_member_image.png.thumb.small', {div:$('member-image').down()});
    
    if (options.lists) this.addLists(options.lists);
    if (options.closeLightbox && lightbox.closingTime) lightbox.close();
    if (options.callCallbacks) this.callLogInCallbacks();
  },
  
  logOut: function logOut(options){
    options = Object.extend({redirectToHomepage:false, closeLightbox:true, facebookLog:false}, options);
    this.isLoggedIn = false;
    //this.lists.clear();
   
    bod = document.getElementsByTagName('body')[0];
    bod.className = '';
    
    new ImagePreview(imagesRepository + 'no_member_image.png.thumb.small', {div:$('member-image')});
    
    if (options.redirectToHomepage && (document.location.href != homepageUrl)) document.location.load(homepageUrl);
    if (options.closeLightbox && lightbox.closingTime) lightbox.close();
    if (options.facebookLog) MyFacebook.callOnConnexion(function(uid){ ajaxRequest(facebookLogInUrl); });
  },
  
  addLists: function(lists){
    var _this = this;
    var sampleElt = $('menu-lists-disconnected').down('a');
    lists.each(function(list){
      var newElt = sampleElt.cloneNode(true);
      newElt.href = list.url;
      newElt.innerHTML = list.name
      $('menu-lists-connected').insert(newElt);
      
      _this.lists.push(list); 
    });
  },
  
  ensureLoggedIn: function(link){
    if (this.isLoggedIn) return true;
    if (!lightbox.closingTime) return false;
    
    if (!link.id) link.id = 'link' + getUniqueId();
    lightbox.addOnCloseCallback(function(){ if (user.isLoggedIn) $(link.id).simulateClick(); });
    
    return lightbox.load(logInUrl + '?referer');
  },
  
  addLogInCallback: function(callback){
    this.logInCallbacks.push(callback);
  },

  callLogInCallbacks: function(){
    var _this = this;
    this.logInCallbacks.each(function(callback){ callback(_this.id, _this); });
  }
});

var user = new User();


/**************** Facebook stuff ****************/

/* callback after facebook connexion */
function onFacebookConnection()
{
  MyLogger.log('Facebook connected');

  return lightbox.load(user.isLoggedIn ? facebookSetUidUrl : facebookLogInUrl);
}


/**************** Post processing stuff ****************/

function processContent(elt)
{
  elt = $(elt) || $(document.getElementsByTagName('body')[0]);
  
  /* create info bubbles */
  InfoBubble.addInfoBubbleEvents(elt);
  
  /* set polaroid buttons values */
  Polaroid.parseAndSetButtonsValuesFromRecords();
  
  /* called when facebook user is loaded */
  var updateMemberFacebokImages = function(user)
  {
    $$('.member-facebook-image-' + user.memberId + '-' + user.uid).each(function(memberImageElt){
      new ImagePreview(user.imageUrl, {div:memberImageElt.up()});
    });
  }
  
  /* push facebook users */
  elt.select('.member-facebook-image').each(function(memberFacebookElt){
  //$$('.member-facebook-image').each(function(memberFacebookElt){
    var results = /member-facebook-image-(\d+)-(\d+)/.exec(memberFacebookElt.className);
    if (true) MyFacebook.pushUser(results[2], results[1], {callback:updateMemberFacebokImages});
  });
  
  MyFacebook.loadUsers();
}

Event.observe(document, 'dom:loaded', function(){ processContent(); });







/* backward compatibility */
updateUrlHash = document.location.updateHash;
reload = document.location.reload;
twitterShare = SocialSharer.twitterShare;
facebookShare = SocialSharer.facebookShare;
load = document.location.load;
function simulateClick(elt){ return $(elt).simulateClick(); }
function loadIntoDiv(url, elt, options){ return $(elt).load(url, options); }
