var Cpu = Class.create();
Cpu.prototype = {
  licence : 'private',
  copyright : '(c) 2011-2012 Création Oueb - http://www.creation-oueb.fr/',
  version : 'v1206',
	pageDimensions : {
		width : null,
		height : null
	},
	initialize : function(options) {
		this.options = Object.extend({
      datas : '[]',
      id_ctlPanelSearch : 'PanelSearch',
      id_ctlSearchService : 'SearchService',
      search_defaut : 'all',
			overlay : {
				opacity : 0.7,
				image : '/themes/default/img/lightwindow/black.png',
				presetImage : '/themes/default/img/lightwindow/black-70.png'
			},
      search_liste : {}
		}, options || {});
    this._getPageDimensions();
    this._addOverlay();
    this._socialNetworkInit();
    this._footerMenuInit();
    this._searchInit();
    this._initLoupeZoomImg();
    this._initPopOvers();
    this._initOpenSignUp();
    this._initPageAbo();
	},

  _socialNetworkInit: function() {
    if($('btnOpenSend2Ami')) {
      $('btnOpenSend2Ami').observe('click', function() {
        Cpu.openPopOver($('divFormSend2Ami'));
      });
    }
  },

  _initOpenSignUp : function() {
    if($('popOverConnect')) {
      if($('btnLogin')) $('btnLogin').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formForgotPwd').hide();$('formSignUp').hide();$('formConnect').show();Cpu.openPopOver( $('popOverConnect'));});
      if($('btnSignup')) $('btnSignup').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formForgotPwd').hide();$('formConnect').hide();$('formSignUp').show();Cpu.openPopOver( $('popOverConnect'));});
      if($('btnGo2ForgotPwd')) $('btnGo2ForgotPwd').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formConnect').fade({duration: 0.3});$('formForgotPwd').appear({duration: 0.3});});
      if($('btnGo2SignUp1')) $('btnGo2SignUp1').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formConnect').fade({duration: 0.3});$('formSignUp').appear({duration: 0.3});});
      if($('btnGo2SignUp2')) $('btnGo2SignUp2').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formForgotPwd').fade({duration: 0.3});$('formSignUp').appear({duration: 0.3});});
      if($('btnGo2Connect1')) $('btnGo2Connect1').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formForgotPwd').fade({duration: 0.3});$('formConnect').appear({duration: 0.3});});
      if($('btnGo2Connect2')) $('btnGo2Connect2').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formForgotPwd').fade({duration: 0.3});$('formConnect').appear({duration: 0.3});});
      if($('btnGo2Connect3')) $('btnGo2Connect3').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formSignUp').fade({duration: 0.3});$('formConnect').appear({duration: 0.3});});
      if($('btnGo2Connect4')) $('btnGo2Connect4').observe('click', function() {$$('.popOverConnectMsg')[0].update('');$('formSignUp').fade({duration: 0.3});$('formConnect').appear({duration: 0.3});});
      if(document.location.hash.substr(1)=='connexion') {
        this.openPopOver( $('popOverConnect'));
      };
    }
  },

  _initPageAbo : function() {
    if($('pgCmd')) {
      $$('.bigbloc h2').each(function(iterator){
        iterator.observe('click',function(){Cpu.switchPageAboDepliable(iterator);});
      },this);
      $$('.bigblocAbo .tabReduit .link').each(function(iterator){
        iterator.observe('click',function(){Cpu.switchPageAboDepliable(iterator);});
      },this);
      $$('.bigblocBuy .link').each(function(iterator){
        iterator.observe('click',function(){Cpu.switchPageAboDepliable(iterator);});
      },this);
      $$('.bigblocCmd .link').each(function(iterator){
        iterator.observe('click',function(){Cpu.switchPageAboDepliable(iterator);});
      },this);
      $$('.header .subscriber')[0].observe('click',function(){Cpu.showPageAboAbonner();});
      $$('.header .buy')[0].observe('click',function(){Cpu.showPageAboAcheter();});

      var ancre = window.location.href.split('#')[1];
      if(ancre!=undefined) {
        if(ancre.indexOf('je-m-abonne')>-1) {
          this.showPageAboAbonner();
        }else if(ancre.indexOf('j-achete')>-1) {
          this.showPageAboAcheter();
        }else if(ancre.indexOf('je-commande')>-1) {
          this.showPageAboAcheter();
        }
      }

      /*
      $$('.bigblocBuy .tabListe input').each(function(iterator){
        if(iterator.value<0) {
          iterator.disabled = true;
          iterator.up().addClassName('epuise');
        }
      },this);
      */
    }
  },

  showPageAboAbonner : function () {
    this.showPageAboBloc($$('.bigblocAbo h2')[0]);
  },

  showPageAboAcheter : function () {
    this.showPageAboBloc($$('.bigblocBuy h2')[0]);
  },

  showPageAboBloc : function (link) {
    if(link!=undefined) {
      Element.scrollTo(link);
      if(link.next().style.display=='none') {
        this.switchPageAboDepliable(link);
      }
    }
  },

  switchPageAboDepliable : function(link) {
    if(link.next().style.display=='none') {
      link.next().blindDown({duration: 0.3});
      link.addClassName('linkActive');
    }else{
      link.next().blindUp({duration: 0.3});
      link.removeClassName('linkActive');
    }
  },

  _initPopOvers : function() {
    var cpt=0;
    $$('.popOver').each(function(iterator){
      var id='popOverBtnClose_'+cpt;
      var html = '<a id="'+id+'" class="popOverBtnClose" href="javascript:// Fermer cette fenêtre"><span>Fermer</span></a>'
      iterator.insert({top:html});
      $(id).observe('click', function() {Cpu.closePopOver(iterator);});
      cpt++;
    },this);
  },

	_getPageDimensions : function() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else {
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		if(yScroll < windowHeight){
			this.pageDimensions.height = windowHeight;
		} else {
			this.pageDimensions.height = yScroll;
		}

		if(xScroll < windowWidth){
			this.pageDimensions.width = windowWidth;
		} else {
			this.pageDimensions.width = xScroll;
		}
	},

  _initLoupeZoomImg : function() {
    $$('a.lightwindow').each(function(iterator){
      if(!iterator.hasClassName('nozoom')) {
        var html = '<span class="loupe"></span>';
        iterator.insert(html);
      }
    },this);
  },

  _footerMenuInit: function() {
    var i=0;
    $$('.footerMenu').each(function(iterator){
      iterator.id = 'footerMenu_'+i;
      new FooterMenu(iterator.id);
      i++;
    },this);
  },

  openPopOver: function (popover) {
    $('cpu_overlay').observe('click', function() {Cpu.closePopOver(popover);});
    this.displayOverlay(true);
    popover.appear({duration: 0.3});
  },

  closePopOver: function (popover) {
    popover.fade({duration: 0.3});
    this.displayOverlay(false);
    $('cpu_overlay').stopObserving('click');
  },

	_addOverlay : function() {
		var overlay = Element.extend(document.createElement('div'));
		overlay.setAttribute('id', 'cpu_overlay');
		// FF Mac has a problem with putting Flash above a layer without a 100% opacity background, so we need to use a pre-made
		if (Prototype.Browser.Gecko) {
			overlay.setStyle({
				backgroundImage: 'url('+this.options.overlay.presetImage+')',
				backgroundRepeat: 'repeat',
				height: this.pageDimensions.height+'px'
			});
		} else {
			overlay.setStyle({
				opacity: this.options.overlay.opacity,
				backgroundImage: 'url('+this.options.overlay.image+')',
				backgroundRepeat: 'repeat',
				height: this.pageDimensions.height+'px'
			});
		}

		var body = document.getElementsByTagName('body')[0];
		body.appendChild(overlay);

		overlay.onclick = function() {return false;};
	},

  _searchInit: function() {
    var html = '';
    html += '<span id="searchService" class="searchService"><span id="searchServiceTxt" class="searchServiceTxt">Tout le site</span></span>';
    html += '<ul id="searchServiceList" class="searchServiceList" style="display:none;">';
    html += '<li><a href="#" class="all">Tout le site</a></li>';
    this.options.search_liste.each(function(publication) {
      html += '<li><a href="#" class="'+publication.url+'">'+publication.nom+'</a></li>';
    },this);
    html += '</ul>';
    $(this.options.id_ctlPanelSearch).insert(html);
    $('searchService').observe('click', function() {$('searchServiceList').show();});
    $('searchServiceList').observe('mouseout', function() {$('searchServiceList').hide();});
    $('searchServiceList').observe('mouseover', function() {$('searchServiceList').show();});

    this.options.search_defaut

    var linkAffinages = $('searchServiceList').getElementsByTagName('a');
    for (var i=0;i<linkAffinages.length;i++) {
      linkAffinages[i].onclick = function() {
        $('searchServiceTxt').innerHTML = this.innerHTML;
        $(Cpu.options.id_ctlSearchService).value = this.className;
        $('searchServiceList').hide();
        return false;
      };
      if(this.options.search_defaut==linkAffinages[i].className) {
        $('searchServiceTxt').innerHTML = linkAffinages[i].innerHTML;
        $(this.options.id_ctlSearchService).value = linkAffinages[i].className;
      }
    }
  },

  displayOverlay: function(show) {
    var overlay = $('cpu_overlay');
    if(show==true) {
      overlay.style.display = 'block';
      overlay.style.visibility = 'visible';
    }else{
      overlay.style.display = 'none';
      overlay.style.visibility = 'hidden';
    }
  },

  showLostPwdForm: function() {
    $$('.popOverConnectMsg')[0].update('');
    $('formForgotPwd').show();
    $('formSignUp').hide();
    $('formConnect').hide();
    Cpu.openPopOver( $('popOverConnect'));
  }
}

function onBlurTxt(i){
  if(i.value==''){
    i.value=i.defaultValue;
    i.style.color='#666';
  }else{
    i.style.color='#000';
  }
}

function onFocusTxt(i){
  if(i.value==i.defaultValue){
    i.value='';
  }
  i.style.color='#000';
}


var FooterMenu = Class.create({

  initialize: function(id) {
    if(!$(id)) throw("Essaye d'initaliser FooterMenu avec l'id : "+ id + ", mais il est introuvable...");
    this.footerMenu = $(id);
    this.options = {
      toggleClass: 'item',
      toggleActive: 'selected',
      contentClass: 'content',
      scrollClass: 'scroll',
      moreClass: 'more',
      categoryClass: 'category'
    }
    this.contents = this.footerMenu.select('div.'+this.options.contentClass);
    this.isAnimating = false;
    this.scrollHeight = 176;
    this.minHeight = 32;
    this.maxHeight = 232;
    this.scallingMin = this.minHeight / this.maxHeight * 100;
    this.current = null;
    this.toExpand = null;

    this.initialHide();

    var overHandler =  this.overHandler.bindAsEventListener(this);
    this.footerMenu.select('.'+this.options.categoryClass).each(function(iterator){
      iterator.observe('mouseover', overHandler);
    });
    var moreClickHandler =  this.moreClickHandler.bindAsEventListener(this);
    this.footerMenu.select('div.'+this.options.moreClass).each(function(iterator){
      iterator.observe('click', moreClickHandler);
    });
  },

  expand: function(el) {
    this.toExpand = el;
    if(this.current != this.toExpand){
      this.animate();
    }
  },

  overHandler: function(e) {
    var el = e.element();
    if(!this.isAnimating) {
      this.expand(el.up('.'+this.options.toggleClass));
    }
  },

  scroll: function(el) {
    var top = (el.offsetTop > 0) ? -this.scrollHeight : (el.offsetTop-this.scrollHeight > - el.offsetHeight ? el.offsetTop-this.scrollHeight : 0);
    new Effect.Move(el, {
        x: 0,
        y: top,
        mode:'absolute',
        duration: 0.75,
        transition: Effect.Transitions.sinoidal
    });
  },

  moreClickHandler: function(e) {
    var el = e.element();
    if(!this.isAnimating) {
      this.scroll(el.up().previous('.'+this.options.scrollClass).down());
    }
  },

  initialHide: function(){
    for(var i=0; i<this.contents.length; i++){
      if(this.contents[i] != this.current) {
        this.contents[i].setStyle({height: this.minHeight+"px"});
        this.contents[i].select('div.'+this.options.scrollClass).each(function(iterator){
          iterator.setStyle({height: '176px'});
        },this);
        this.contents[i].select('div.'+this.options.moreClass).each(function(iterator){
          iterator.show();
        },this);
      }
    }
  },

  animate: function() {
    var effects = new Array();
    var options = {
      sync: true,
      scaleFrom: this.scallingMin,
      scaleContent: true,
      transition: Effect.Transitions.sinoidal,
      scaleMode: {
        originalHeight: this.maxHeight,
        originalWidth: this.footerMenu.getWidth()
      },
      scaleX: false,
      scaleY: true
    };

    effects.push(new Effect.Scale(this.toExpand.down('div.'+this.options.contentClass), 100, options));

    options = {
      sync: true,
      scaleContent: false,
      transition: Effect.Transitions.sinoidal,
      scaleX: false,
      scaleY: true
    };

    var myDuration = 0.75;

    if(this.current==null) {

      new Effect.Parallel(effects, {
        duration: myDuration,
        fps: 35,
        queue: {
          position: 'end',
          scope: 'accordion'
        },
        beforeStart: function() {
          this.isAnimating = true;
          this.toExpand.addClassName(this.options.toggleActive);
        }.bind(this),
        afterFinish: function() {
          this.toExpand.down('div.'+this.options.contentClass).setStyle({height: this.maxHeight+"px"});
          this.current = this.toExpand;
          this.isAnimating = false;
        }.bind(this)
      });
    }else{
      effects.push(new Effect.Scale(this.current.down('div.'+this.options.contentClass), this.scallingMin, options));

      new Effect.Parallel(effects, {
        duration: myDuration,
        fps: 35,
        queue: {
          position: 'end',
          scope: 'accordion'
        },
        beforeStart: function() {
          this.isAnimating = true;
          this.current.removeClassName(this.options.toggleActive);
          this.toExpand.addClassName(this.options.toggleActive);
        }.bind(this),
        afterFinish: function() {
          this.current.down('div.'+this.options.contentClass).setStyle({height: this.minHeight+"px"});
          this.toExpand.down('div.'+this.options.contentClass).setStyle({height: this.maxHeight+"px"});
          this.current = this.toExpand;
          this.isAnimating = false;
        }.bind(this)
      });
    }
  }

});

