var Pulceo = Class.create();
Pulceo.prototype = {
  licence : 'private',
  copyright : '(c) 2008-2011 Création Oueb - http://www.creation-oueb.fr/',
	windowDimensions : {
		width : null,
		height : null
	},
	pageDimensions : {
		width : null,
		height : null
	},
  codeEmbedIFrame : '<iframe width="__WIDTH__" height="__HEIGHT__" src="__URL__" frameborder="0" allowfullscreen></iframe>',
  codeEmbedObject : '<object type="application/x-shockwave-flash" data="http://www.pulceo.com/medias/com/player_flv_pulceo_embed.swf" width="__WIDTH__" height="__HEIGHT__"><param name="movie" value="http://www.pulceo.com/medias/com/player_flv_pulceo_embed.swf"><param name="allowFullScreen" value="true"><param name="wmode" value="transparent"><param name="FlashVars" value="flv=__URL_FLV__&amp;startimage=http://www.pulceo.com/medias/com/video_pulceo.jpg&amp;onclick=__URL_RPTG__"></object>',
	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'
			}
		}, options || {});
    this._getPageDimensions();
    this._addOverlay();
    this._signupInit();
    this._socialBarInit();
    this._footerMenuInit();
    this._searchInit();
    this._txtPliableInit();
    this._listeRegionInit();
    this._listeCatsInit();
    this._initLoupeZoomImg();
    this._initPopOvers();
	},

  _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() {Pulceo.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;
		}

		if (self.innerHeight) {
			this.windowDimensions.width = self.innerWidth;
			this.windowDimensions.height = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			this.windowDimensions.width = document.documentElement.clientWidth;
			this.windowDimensions.height = document.documentElement.clientHeight;
		} else if (document.body) {
			this.windowDimensions.width = document.body.clientWidth;
			this.windowDimensions.height = document.body.clientHeight;
		}
    
		if(yScroll < this.windowDimensions.height){
			this.pageDimensions.height = this.windowDimensions.height;
		} else {
			this.pageDimensions.height = yScroll;
		}

		if(xScroll < this.windowDimensions.width){
			this.pageDimensions.width = this.windowDimensions.width;
		} 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);
  },

  _signupInit: function() {
    if($('formLoginSignUp')) {
      $('btnLogin').observe('click', function() {Pulceo.openSignUp();});
      $('btnSignup').observe('click', function() {Pulceo.openSignUp();});
      $('loginSignupClose').observe('click', function() {Pulceo.closeSignUp();});
      $('loginSignupClose2').observe('click', function() {Pulceo.closeSignUp();});
      $('forgotPasswordLink').observe('click', function() {$('loginForm').fade({duration: 0.3});$('forgotPasswordForm').appear({duration: 0.3, queue: 'end'});});
      $('rememberedPasswordLink').observe('click', function() {$('forgotPasswordForm').fade({duration: 0.3});$('loginForm').appear({duration: 0.3, queue: 'end'});});
      $('actionShowSignupPrompt').observe('click', function() {$('promptForFBConnect').fade({duration: 0.3});$('promptForSignup').appear({duration: 0.3, queue: 'end'});});
    }
    if($('monCompte')) {
      $('monCompte').observe('click', function() {$('monComteMenu').show();});
      $('monComteMenu').observe('mouseout', function() {$('monComteMenu').hide();});
      $('monComteMenu').observe('mouseover', function() {$('monComteMenu').show();});
    }
  },

  openSignUp: function() {
    if($('formLoginSignUp')) {
      Pulceo.displayOverlay(true);
      $('signupForm2Left').hide();
      $('signupForm2').hide();
      $('signupForm2Bottom').hide();
      $('forgotPasswordForm').hide();
      $('promptForSignup').hide();
      $('promptForFBConnect').show();
      $('loginForm').show();
      $('signupForm').show();
      this._getPageDimensions();
      $('formLoginSignUp').show();
      $('formLoginSignUp').setStyle({
				top: parseInt((this.windowDimensions.height-$('formLoginSignUp').clientHeight)/2) +'px'
			});      
    }
  },

  closeSignUp: function() {
    $('formLoginSignUp').fade({duration: 0.3});
    Pulceo.displayOverlay(false);
  },

  switch2signupForm2: function() {
    if($('formLoginSignUp')) {
      $('signupForm').fade({duration: 0.3});
      $('loginForm').fade({duration: 0.3});
      $('forgotPasswordForm').fade({duration: 0.3, afterFinish: function(){
        $('signupForm2Left').appear({duration: 0.3});
        $('signupForm2').appear({duration: 0.3});
        $('signupForm2Bottom').appear({duration: 0.3});
      }});
    }
  },

  signupFinish: function() {
    this.closeSignUp();
    var html = '<p class="msgBeforePgTitre"><b>Note : </b> Pour activer ton compte, ouvre l\'e-mail de Pulceo que tu viens de recevoir, et cliques sur le lien d\'activation de ton compte.</p>'
    $('pgTitre').insert({before:html});
    Pulceo.displayOverlay(false);
  },

  signupFinishFB: function() {
    this.closeSignUp();
    Pulceo.displayOverlay(false);
  },

  _socialBarInit: function() {
    if($('socialBar')) {
      $('socialBarShare').observe('click', function() {
        if($('socialBarCpts').hasClassName('visible')){
          $('socialBarCpts').blindUp({duration: 0.3, queue: 'end'});
          $('socialBarCpts').removeClassName('visible')
        }else{
          $('socialBarCpts').blindDown({duration: 0.3, queue: 'end'});
          $('socialBarCpts').addClassName('visible')
        }
      });
      $('btnOpenSend2Ami').observe('click', function() {
        $('pulceo_overlay').observe('click', function() {Pulceo.closePopOver($('divFormSend2Ami'));});
        Pulceo.displayOverlay(true);
        $('divFormSend2Ami').show();
        $('divFormSend2Ami').setStyle({
          top: parseInt((Pulceo.windowDimensions.height-$('divFormSend2Ami').clientHeight)/2) +'px'
        });
      });
      if($('btnOpenEmbed')) {
        $('btnOpenEmbed').observe('click', function() {
          $('pulceo_overlay').observe('click', function() {Pulceo.closePopOver($('divFormEmbed'));});
          Pulceo.displayOverlay(true);
          $('divFormEmbed').show();
          $('divFormEmbed').setStyle({
            top: parseInt((Pulceo.windowDimensions.height-$('divFormEmbed').clientHeight)/2) +'px'
          });
          Pulceo.embedCodeUpdate(true);
        });
        $$('.formEmbedSize').each(function(iterator){
          iterator.observe('click', function() {
            var is_selected = iterator.hasClassName('selected');
            $$('.formEmbedSize').each(function(iterator){
              iterator.removeClassName('selected');
            },this);
            var setfocus = true;
            if(iterator.hasClassName('custom')) {
              if(!is_selected) {
                $('formEmbedSizeCustomWidth').focus();
              }
              setfocus = false;
            }
            iterator.addClassName('selected');
            Pulceo.embedCodeUpdate(setfocus);
          });
        },this);
        $('formEmbedSizeCustomWidth').observe('keydown', function() {Pulceo.embedCustomUpdateValues(this);});
        $('formEmbedSizeCustomWidth').observe('keyup', function() {Pulceo.embedCustomUpdateValues(this);});
        $('formEmbedSizeCustomHeight').observe('keydown', function() {Pulceo.embedCustomUpdateValues(this);});
        $('formEmbedSizeCustomHeight').observe('keyup', function() {Pulceo.embedCustomUpdateValues(this);});
        $('formEmbedOption').observe('click', function() {Pulceo.embedCodeUpdate(true);});
      }
      $('socialBarAdd').observe('click', function() {$('socialBarAddMenu').show();});
      $('socialBarAddMenu').observe('mouseout', function() {$('socialBarAddMenu').hide();});
      $('socialBarAddMenu').observe('mouseover', function() {$('socialBarAddMenu').show();});
      $$('.btnLove')[0].observe('mouseover', function() {
        if($$('.btnLove')[0].hasClassName('btnLoveHate')) $('infoHate').show();
      });
      $('infoHate').observe('mouseout', function() {$('infoHate').hide();});
      $('infoHate').observe('mouseover', function() {$('infoHate').show();});
    }
  },

  embedCodeUpdate : function(setfocus) {
    var w = 480;
    var h = 390;
    $$('.formEmbedSize').each(function(iterator){
      if(iterator.hasClassName('selected')) {
        if(iterator.hasClassName('custom')) {
          var custom_w = Math.abs(parseInt($F('formEmbedSizeCustomWidth')));
          var custom_h = Math.abs(parseInt($F('formEmbedSizeCustomHeight')));
          if(custom_w>300 && custom_h>170) {
            if(custom_w < custom_h) {
              $('formEmbedSizeCustomWidth').value = custom_h;
              $('formEmbedSizeCustomHeight').value = custom_w;
              var tmp = custom_h;
              custom_h = custom_w;
              custom_w = tmp;
            }
            w = custom_w;
            h = custom_h;
          }
        }else{
          var selected = iterator.down('input');
          w = selected.readAttribute('data-width');
          h = selected.readAttribute('data-height');
        }
      }
    },this);
    var code = this.codeEmbedIFrame.replace('__WIDTH__',w).replace('__HEIGHT__',h).replace('__URL__',$F('formEmbedCodeUrlIFrame'));
    if($('formEmbedOption').checked){
      code = this.codeEmbedObject.replace('__WIDTH__',w).replace('__HEIGHT__',h).replace('__URL_FLV__',$F('formEmbedCodeUrlObject')).replace('__URL_RPTG__',$F('formEmbedCodeUrlRptg'));
    }
    $('formEmbedCode').value = code;
    if(setfocus) {
      $('formEmbedCode').focus();
      $('formEmbedCode').select();
    }
  },

  embedCustomUpdateValues : function(ctrl) {
    if(ctrl.id=='formEmbedSizeCustomWidth') {
      var custom_w = Math.abs(parseInt($F('formEmbedSizeCustomWidth')));
      if(Math.abs(parseInt($F('formEmbedSizeCustomWidth')))) {
        $('formEmbedSizeCustomHeight').value = parseInt(380 / 670 * custom_w);
      }else{
        $('formEmbedSizeCustomHeight').value = 0;
      }
    }else{
      var custom_h = Math.abs(parseInt($F('formEmbedSizeCustomHeight')));
      if(Math.abs(parseInt($F('formEmbedSizeCustomWidth')))) {
        $('formEmbedSizeCustomWidth').value = parseInt(670 / 380 * custom_h);
      }else{
        $('formEmbedSizeCustomWidth').value = 0;
      }
    }
    this.embedCodeUpdate(false);
  },

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

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

	_addOverlay : function() {
		var overlay = Element.extend(document.createElement('div'));
		overlay.setAttribute('id', 'pulceo_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;};
	},

  _txtPliableInit: function() {
    var cpt=0;
    $$('.txtPliable').each(function(iterator){
      var html = '';
      html += '<span class="txtPliableBtnP" id="txtPliableBtnP_'+cpt+'" cpt="'+cpt+'"><span>plus</span></span>';
      html += '<span class="txtPliableBtnM" id="txtPliableBtnM_'+cpt+'" cpt="'+cpt+'" style="display:none;"><span>moins</span></span>';
      iterator.insert(html);
      iterator.addClassName('txtPliableResu');
      iterator.id = 'txtPliable_'+cpt;

      $('txtPliableBtnP_'+cpt).observe('click', function() {
        var cpt = this.readAttribute('cpt');
        $('txtPliable_'+cpt).removeClassName('txtPliableResu');
        $('txtPliable_'+cpt).addClassName('txtPliableFull');
        $('txtPliableBtnP_'+cpt).hide();
        $('txtPliableBtnM_'+cpt).show();
      });
      $('txtPliableBtnM_'+cpt).observe('click', function() {
        var cpt = this.readAttribute('cpt');
        $('txtPliable_'+cpt).removeClassName('txtPliableFull');
        $('txtPliable_'+cpt).addClassName('txtPliableResu');
        $('txtPliableBtnM_'+cpt).hide();
        $('txtPliableBtnP_'+cpt).show();
      });
      cpt++;
    },this);
  },

  _listeRegionInit : function() {
    $$('.listeRegion .bloc input').each(function(iterator){
      iterator.observe('change', function() {
        Pulceo.listeRegionChanged();
      });
    },this);
    if($('btnAllRegions')) {
      $('btnAllRegions').observe('click', function() {
        $$('.listeRegion .bloc input').each(function(iterator){
          iterator.checked = true;
        },this)
        Pulceo.listeRegionChanged();
      });
      $('btnNoRegion').observe('click', function() {
        $$('.listeRegion .bloc input').each(function(iterator){
          iterator.checked = false;
        },this)
        Pulceo.listeRegionChanged();
      });
    }
    $$('.listeRegion .bloc input').each(function(iterator){
      iterator.checked = true;
    },this)
    this.listeRegionChanged();
  },

  listeRegionChanged : function() {
    if($$('.pageVilleCat')[0]!=undefined) {
      this.listeRegionChangedPgVilleCat();
    }
  },

  listeRegionChangedPgVilleCat : function() {
    $$('.listeRegion .bloc input').each(function(iterator){
      if(iterator.checked) {
        $$('.villeAccordeon .'+iterator.value).each(function(iterator){
          iterator.show();
        },this)
      }else{
        $$('.villeAccordeon .'+iterator.value).each(function(iterator){
          iterator.hide();
        },this)
      }
    },this)
  },

  _listeCatsInit : function() {
    $$('.listCats .bloc_sscat').each(function(iterator){
      iterator.observe('click', function() {
        Pulceo.listCatsView(this);
      });
    },this);
  },

  listCatsView : function(cat) {
    $$('.listCats .sscats').each(function(iterator){
      iterator.hide();
    },this);
    $$('#'+cat.id+'_sscats').each(function(iterator){
      iterator.show();
    },this);
  },

  _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>';
    html += '<li><a href="#" class="articles">Articles</a></li>';
    html += '<li><a href="#" class="reportages">Reportages</a></li>';
    html += '<li><a href="#" class="evenements">Évènements</a></li>';
    html += '<li><a href="#" class="membres">Membres</a></li>';
    html += '<li><a href="#" class="annonces">Annonces</a></li>';
    html += '<li><a href="#" class="associations">Associations</a></li>';
    html += '<li><a href="#" class="entreprises">Entreprises</a></li>';
    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;
        $(Pulceo.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 = $('pulceo_overlay');
    if(show==true) {
      overlay.style.display = 'block';
      overlay.style.visibility = 'visible';
    }else{
      overlay.style.display = 'none';
      overlay.style.visibility = 'hidden';
    }
  }
}

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)
      });
    }
  }

});

