function zm_ps_reloaded() {
 this.store_products_prefix = '/m/pl/malid:';
 this._offer_fetch_url      = '/m/dws/product_offer_enhanced.php';
 this._attr_prefix          = 'zm_att_';
 this.ready                 = 0;                /** interrupteur general **/
 this._moid                 = null;             /** moid demande **/
 this._current_moid         = null;             /** moid courant **/
 this._current_oid          = null;             /** oid courant **/
 this._buyable              = null;             /** offre achetable ou non **/
 this._mpid                 = null;             /** mpid courant **/
 this._mall                 = null;             /** context mall **/
 this._ve_value_id          = null;             /** value_id de VE si on en a un **/
 this._a_av                 = new Object();     /** tableau des av de l'offre courante **/
 this._current_a_av         = new Object();     /** tableau des av de l'offre courante **/
 this._id_map               = [                 /** mapping des id xml vers id html **/
  {'_id': 'offer_name',                '_html_id': '.zm_name'},
  {'_id': 'offer_description_long',    '_html_id': '#zm_description_long'},
  {'_id': 'offer_description_short',   '_html_id': '#zm_description_short'},
  {'_id': 'store_sentence',            '_html_id': '#zm_sentence'},
  {'_id': 'warranty',                  '_html_id': '#zm_warranty'},
  {'_id': 'availability',              '_html_id': '#zm_availability'},
  {'_id': 'price_final',               '_html_id': '#zm_price_final'},
  {'_id': 'ecotax',                    '_html_id': '#zm_ecotax'},
  {'_id': 'currency',                  '_html_id': '#zm_currency'},
  {'_id': 'store_name',                '_html_id': '.zm_store_name'}
  ];


 /** initialisation generale **/
 this.init = function(_mpid, _moid, _mall, _ve_value_id) {
  this.ready  = 1;                  /** objet pret a fonctionner **/
  this._moid  = _moid;
  this._mpid  = _mpid;
  this._mall  = _mall;
  this._ve_value_id  = _ve_value_id;
  
  /** cgv click callback **/
  $('#zm_merchant_url').click(zm_ps.store_sheet_click_cb).addClass('hover');

  /** sales condition click callback **/
  $('#zm_sales_condition_url').click(zm_ps.store_sc_click_cb).addClass('hover');

  /** init des clic sur les valeurs d'attribut **/
  $('dl.attMenu a[id^='+this._attr_prefix+']').click(zm_ps.av_selection_cb);

  /** init pour les clics sur le lien "tous les articles" **/
  $('#zm_store_url').unbind('click').click(zm_ps.store_products_click_cb);


 
/** init titleManager **/
$(document).titleManager({'listnerEvent':'managetitle','titleMotif':"[offerTitle] [values] - Achat/Vente [offerTitle] [values] - [mpid] - [moid] - RueDuCommerce"})
if($('#zm_comparateur').length>0)$('#zm_comparateur').hide().storesManager({'listnerEvent':'managestores','mpid':_mpid,'moid':_moid});
  if(window.location.hash){         /** verification des parametres de l'url **/
   var pattern = /moid:(MO-[0-9|A-Z]+M[0-9]+)/
   var _reg = new RegExp(pattern);
   var _a_moid = _reg.exec(window.location.hash);
   var _u_moid = null ;
   if (_a_moid && _a_moid.length) {
    _u_moid = _a_moid[1] ;
   }
   if(_u_moid) {
    if( (this._moid != _u_moid)){      /** moid de l'url != moid courant => rechargement necessaire **/
     this._moid = _u_moid;
     this.fetch_offer();
     return;
    }
   }
  }
  this.fetch_offer();
  
/* XXX temporairement desactive
  this.attr_init();
  */
 }


 /** methode d'initialisation des valeurs d'attributs **/
 this.update_a_av = function(_ps_xml) {
  $(_ps_xml).find('attribute_value').each(function(_nb){
   zm_ps._current_a_av[$(this).attr('attribute_id')] = $(this).attr('value_id');
   zm_ps.update_av($(this).attr('value_id'), $(this).attr('attribute_id'), $(this).attr('value_state'));
  });
 };

 /** methode de mise à jour d'une valeur d'attribut **/
 this.update_av = function(_av_id, _a_id, _av_state) {
  switch(_av_state) {
   case 'disabled':
    var _class = 'attInactif';
    var _state = 'disabled';

    if (_a_id == "6")
      var _style = 'font-style:normal;color:#000000;';
    else
      var _style = '';
    break;
   case 'selected':
    var _class = 'attSelected';
    var _state = 'selected';
    var _style = '';
    break;
   default:
    var _class = '';
    var _state = 'default';
    var _style = '';
  }
  $('#'+this._attr_prefix+_av_id).attr({'class': _class,'_a_id': _a_id,'_av_id': _av_id,'_state': _state,'style': _style});

 }


 /** chargement des infos d'une offre, par moid ou tableau de value id **/
 this.fetch_offer = function(){
  var _s = '';
  var _sep = '';
  for(var _k in this._a_av) {
   _s = _s + _sep + this._a_av[_k];
   _sep = ';';
  }
  if(this._ve_value_id != null){
    _s = _s + _sep + this._ve_value_id;
  }  
  
  if(this._moid != null) {
   $.ajax(jQuery.extend(this.objAjaxSetup, {data:{mall : this._mall, moid: this._moid, mpid: this._mpid, values: _s}}));
   return;
  }

  $.ajax(jQuery.extend(this.objAjaxSetup,{data:{mall : this._mall, values: _s, mpid: this._mpid}}));
  

 }
 
 

 /** callback de traitement du XML recu **/
 this.display_offer_cb = function(_ps_xml) {
   if(! _ps_xml.responseXML) return;
  if($(_ps_xml.responseXML).find('error').attr('error_code')){
    return zm_ps.display_error();
   }
  zm_ps.display_offer(_ps_xml.responseXML,this.data);
  var ld=$("#loadingData");
   ld.css('height',ld.parent().parent().outerHeight(true)+10);
 }


 /** methode de mise à jour générale de l'affichage de l'offre courante **/
 this.display_offer = function(_ps_xml,paramRequest) {
  /** reinit des donnees courantes **/
  var tmpNOffer=$(_ps_xml).find('offer');
  this._current_moid = tmpNOffer.attr('moid');
  if(this._current_moid){window.location.hash='moid:' + this._current_moid}
  this._current_oid = tmpNOffer.attr('id');
  this._buyable = tmpNOffer.attr('buyable');
  this.reinit_current_a_av();
  /** mise a jour **/
  this.update_a_av(_ps_xml);
  this.update_price_details($("prices_information",_ps_xml));
  this.update_mapped_data(_ps_xml);
  this.update_store_links(_ps_xml);
  this.update_images($(_ps_xml).find('images'))
  this.update_title(_ps_xml);
  this.update_cart_button(_ps_xml);
  this.update_availability(_ps_xml);
  this.update_shipments(_ps_xml);
  this.update_avg_rate_merchant(_ps_xml);
  this.update_pour_noel(_ps_xml);
  this.update_flash(_ps_xml);
  jQuery.event.trigger("managestores", [{xmlData:_ps_xml,moid:this._current_moid}], window, false, null);
 }


 /** iterateur pour update generique **/
 this.update_mapped_data = function(_ps_xml) {
  _l = this._id_map.length;
  for(_k = 0;_k < _l; _k++){
   _data = $(_ps_xml).find(this._id_map[_k]['_id']+':first').text();          /** recuperation de valeur **/
   this.update_data(this._id_map[_k]['_html_id'], _data);           /** mise a jour sur l'element html correspondant **/
  }
 }


 /** methode generique d'update de contenu **/
 this.update_data = function(_id, _val) {
  $(_id).empty().html(_val);
 }


  /** update price details **/
  this.update_price_details = function(dtObj){
    var container = $("#zm_prices_information");
    this.reinit_ps(container);
    var priceDetails=dtObj.find('price_details');
    //container.append('<div id="zm_price_details"></div>');
    var container_details = $("#zm_price_details");
     container_details.empty();
     
    if (priceDetails.length==0)
      return;
    

    var i = 0;
    var priceType = null;
    
      $('price_detail',priceDetails).each(function(){
        priceType=$('price_type', this)[0].firstChild.nodeValue;
        if(priceType == "sale"){
          construct_sales(dtObj,container_details);
          return false;
        }
        container_details.append('<div id="zm_price_detail_'+i+'" class="margin-top '+ priceType +'"></div>');
  
        var container_detail = $("#zm_price_detail_"+i);
  
        // MAJ PRIX BARRE
        var previousPrice=$('previous_price', this)[0].firstChild.nodeValue;
        var currency=$('currency', this)[0].firstChild.nodeValue;
        construct_barred_price(previousPrice, container_detail, i, priceType);
  
  
        i++;
       });
    


     if(priceType !== null){
       /* PROMO PATCH */
      var promo_reduc=$('discount_amount',priceDetails)[0].firstChild;
      if(priceType == 'sale')
        var percents=$('promo_percents',dtObj)[0].firstChild;
      else
        var percents=$('discount_percents',priceDetails)[0].firstChild;
      construct_promo_patch(promo_reduc, percents, priceType);
     }
     
  }
  
  construct_sales = function(dtObj,container){
      var previousPrice=$('price_previous', dtObj)[0].firstChild.nodeValue;
      var priceDetails=dtObj.find('price_details');
      
      var container_detail = $("#zm_price_detail");
      var html_detail = '<div id="zm_price_detail" class="margin-top zm_price_detail sale"  style="display:inline"><div class="span-4">Prix avant les Soldes</div>';
      html_detail +='<div  id="zm_previous_price" class="span-2 last txtright"><span class="previous txt txtitalic">' + previousPrice + '</span></div>';
      var tab_dem = new Array('1ère','2e','3e');
      var k = 0;
      var nb_det = $('price_detail',priceDetails).length;
      $('price_detail',priceDetails).each(function(i){
        var discount_percents=$('discount_percents', this)[0].firstChild.nodeValue;
        var sp = "6";
        if(nb_det>1)
        {
          html_detail +='<div class="span-3">' + tab_dem[i]+ ' démarque : </div>';
          var sp = "3";
        }
        
        html_detail += '<div id="zm_discount_percents"  class="span-'+sp+' last txtright  discountP">' + discount_percents + ' de remise</div>';
        
      });
      html_detail += '</div>';
      container.append(html_detail);
  }
  
  construct_barred_price = function(barred_price, container, i, priceType){
    switch(priceType) {
      case 'flash':                
        var html = '<div class="span-4">  Prix <span class="zm_store_name"></span></div>';
        break;
      case 'sale':                
        var html = '<div class="span-4">Prix avant les Soldes</div>';
        break;
      default:                        
        var html = '<div class="span-4">Prix du marché constaté</div>';
      break;
     }
    
    html += '<div id="zm_previous_price_'+i+'" class="span-2 last txtright txtitalic"><span class="previous txt txtright">';
    html += barred_price+'</span></div>';
    container.append(html);
  }
  construct_remises = function(remise, container, i){
    var html = '<div id="zm_discount_percents_'+i+'" class="span-6 last discountP">';
    html += remise;
    html += '&nbsp; de&nbsp;remise</div>';
    container.append(html);
  }
  
  
  construct_date = function(date_start, date_end, container, i){
    var html = '<span id="zm_date_start_'+i+'" class="promo zm_date_start">&nbsp;';
    html += date_start+'</span>&nbsp;';
    html += '<span id="zm_date_end_'+i+'" class="promo zm_date_end">';
    html += date_end+'</span>';
    container.append(html);
  }

  construct_promo_patch = function(promo_reduc,promo_percents,price_type){
    var container_img = $("#container_img");
    var html ='';
    var patch ='';
    var val_reduc ='';

    if(promo_reduc && price_type!="sale"){
      construct_economie(promo_reduc);
    }
    if(promo_percents)
    {
      if(price_type == "promo")
        patch = 'patch_promo_percents';
      else if(price_type !== null)
        patch = 'patch_'+price_type;

      val_reduc = '<span class="txtxl">' + promo_percents.nodeValue + '</span>';
    }

    html = '<div id="offer_patch" class="offer_patch txtblanc txtbold txtxl '+ patch +'">' + val_reduc + '</div>';

    container_img.prepend(html);
  }
  
  construct_economie = function(promo_reduc){
    if(parseInt(promo_reduc.nodeValue) < 1)
      return
    var html = '<div class="span-4 pad_top txtindent">Vous économisez</div><div class="span-2 last txtright txtitalic txtl">'
      html += promo_reduc.nodeValue+'</div>';
    $("#zm_economie").empty().append(html);
  }
  
   this.reinit_ps = function(container){
    //$('*', container).empty();
    $("#zm_economie").empty();
    //$("#zm_ecotax").empty();
    $("#offer_patch").remove();
   }

    /** methode d'update pour le bandeau "Livré avant Noel" **/
    this.update_pour_noel = function(_ps_xml) {
        var pour_noel =$(_ps_xml).find('delivery').attr('pour_noel');
        if (pour_noel=='1') {
            $(".livre_avant_noel").removeClass('nod');
        } else {
            $(".livre_avant_noel").addClass('nod');
        }
    }
    /**Méthode pour mettre à jour le décompte flash**/
    this.update_flash = function(_ps_xml){
    $VF=$("#VF");
     // $('.vfchronofp', $VF).removeClass('vfchronofp vfCountDown').addClass('nod');
      $VF.empty();
      var date_diff = $("prices_information",_ps_xml).find('period').attr('date_diff');
      if(date_diff > 0){
         $VF.append($('<div />').addClass('txtright txtblanc margin-top').append('Plus que ',$('<strong/>').attr({'class':'vfCountDown margin-top margin-bottom','secs':date_diff}),'!&nbsp;'));       
      }      
    }

  /** methode d'update pour le lien vers la presentation marchand **/
  this.update_store_links = function(_ps_xml) {
    var store_name = $(_ps_xml).find('store_name').text();
    var store_id = $(_ps_xml).find('store').attr('value_id');
    var store_rate = $(_ps_xml).find('store').attr('avg_rate');
    //var merchant_url =$(_ps_xml).find('store_merchant_url').text();
    //var sale_condition_url = $(_ps_xml).find('store_sales_condition_url').text();
    var sale_condition_url = $(_ps_xml).find('store_merchant_url').text();
    var store_link = this.store_products_prefix + store_id;
    var current_oid=this._current_oid;
    if($('.reviewLink').length>0) {$('.reviewLink').data('oId',current_oid);$('.reviewLink').data('sId',$(_ps_xml).find('store').attr('id'));}
    $('#zm_store_url').attr('onclick', null)
      .text('Voir tous les articles du marchand '+store_name)
      .unbind('click')
      .click(function(){window.open(store_link,'_top');});
    $('#zm_merchant_url').attr('onclick', null)
      .unbind('click')
    .click(function(){window.open(merchant_url,'_top');});
    $('#zm_sales_condition_url').attr('onclick', null)
      .unbind('click').
    click(function(){window.open(sale_condition_url,'_top');});
    $('#abus_url').attr('onclick', null)
      .unbind('click')
      .click(function(){window.open('/m/abuses/index.php?oid='+current_oid);});
  }

  /** update des images */
  this.update_images = function(im){
    var container = $("#zm_images");
    var idxImg = 1;
    var typeImg = ['small','big'];
    tmpl = $('.zm_image:first', container);
    $(container).empty();

    $('image', im).each(function(i){
      var newImg = tmpl.clone(true).attr('className', 'zm_image ' + typeImg[idxImg]);
      $('span',newImg).attr({'href_img': $('zoom', this)[0].firstChild.nodeValue,'rel':'images'});
      $('img',newImg).attr('src', $(typeImg[idxImg], this)[0].firstChild.nodeValue);

      if(i==0){
        $('span',newImg).attr('rel','images nocount');
        container.append(newImg);
        var newImg = tmpl.clone().attr({'className':'zm_image small'}); //miniature pour img big
        $('img', newImg).removeAttr('id').attr({'src': $('small', this)[0].firstChild.nodeValue,'width':50,'height':50});
        $('span', newImg).attr({'href_img': $('zoom', this)[0].firstChild.nodeValue,'rel':'images'});

      }

      newImg.css('background-image',"url("+$('big',this)[0].firstChild.nodeValue+")");
      $('img', newImg).removeAttr('id').attr({'width':50,'height':50});
      container.append(newImg);
      idxImg = 0;
    });

  }

  /*** update title **/
  this.update_title = function(_ps_xml){
    var obj_title= {};
    obj_title.offerTitle = $(_ps_xml).find('offer_name').text();
    var tmpValPrefix = this._attr_prefix;
    var tmpArrAtt = [];

    jQuery.each($(this._current_a_av)[0], function(k,v){tmpArrAtt.push(tmpValPrefix+v)});
    obj_title.values = (tmpArrAtt[0]) ? tmpArrAtt.join(';') : '';
    //obj_title.values=jQuery.makeArray($('a.attSelected').map(function(){console.info($(this).text());return $(this).text()})).join(';');
    obj_title.mpid = this._mpid;
    obj_title.moid = this._current_moid;
    jQuery.event.trigger("managetitle", [obj_title], window, false, null);
  }

 /** callback de gestion des choix de valeur - ajout d'un critere **/
 this.av_selection_cb = function(event) {
  event.preventDefault();
  if(! zm_ps.ready) return false; /** objet pas pret => on ne fait rien **/

  switch($(this).attr('_state')) {
   case 'selected':                /** choix d'une av deja selectionnee - pour l'instant on ne fait rien **/
    return;
   case 'disabled':                /** choix d'une av incompatible avec les autres - nouvelle recherche **/
    zm_ps._a_av = new Object();    /** annulation des anciens criteres **/
    zm_ps._moid = null;
    break;
   default:                        /** choix d'une av compatible avec les autres **/
    zm_ps._moid = null;
    break;
  }
  zm_ps._a_av[$(this).attr('_a_id')] = $(this).attr('_av_id');
  zm_ps.fetch_offer();              /** mise à jour générale nécessaire **/
  return;
 }

  /** before send ajax */
  this.before_send_data = function(){
    $("#loadingData").removeClass('hide');
  }

this.success_send_data = function(){
  $("#loadingData").addClass('hide').html('<div></div>');
  }

 /** affichage erreur generique **/
 this.display_error = function() {
  //$('#add-cart').addClass('errorScript');
  zm_ps.desactivate_cart_button();
  $('#loadingData').css({width:980,left:-360,top:-20,opacity:1}).removeClass('hide').html('<div class="error">L\'article est indisponible à la vente pour le moment.<br /> Nous vous prions de bien vouloir nous en excuser.<br /><a href="javascript:history.back()" style="text-decoration:underline">Retour page précédente</a> </div>');
 }


 /** gestion du bouton acheter et des mentions de disponibilité **/
 this.update_cart_button = function(_o_xml) {
   if($(_o_xml).find('store').attr('id') == 178){
     this.desactivate_cart_button();
   }
  
   if($(_o_xml).find('offer').attr('is_for_unique_picking') == 1){
    if ( $("#caddie_data #fzmpu").length == 0 ) {
       $("#caddie_data").append('<input id="fzmpu" type="hidden" name="fzmpu" value="1" />');
     }
   } else {
     $("#caddie_data #fzmpu").remove();
   }
   
   if($(_o_xml).find('offer').attr('is_offer_alapage') == 1){
     if ( $("#caddie_data #fm_store_id").length == 0 ) {
        $("#caddie_data").append('<input type="hidden" id="fm_store_id" name="store_id" value="'+$(_o_xml).find('store').attr('id')+'" />');
      }
     if ( $("#caddie_data #fm_merchant_product_id").length == 0 ) {
       $("#caddie_data").append('<input type="hidden" id="fm_merchant_product_id" name="merchant_product_id" value="'+$(_o_xml).find('offer').attr('merchant_product_id')+'" />');
      }
     $("input[name=fzm]","#caddie_data").remove();
    } else {
      $("#caddie_data #fm_store_id").remove();
      $("#caddie_data #fm_merchant_product_id").remove();
      if ( $("input[name=fzm]","#caddie_data").length == 0 ) {
        $("#caddie_data").append('<input type="hidden" name="fzm" value="1" />');
      }
    }
   
   if(this._buyable == 0)
     this.desactivate_cart_button();
   else
     this.activate_cart_button();
   
   $('#cart-submit').val(this._current_oid);
 }
 
 this.update_availability = function(_o_xml){
   if( this._buyable == 0 ){
     $('div#zm_availability').attr('class','stock_epuise').html('Temporairement Indisponible');
     //$('span#zm_shipping_delay_label').empty().html('');
     return;
   }
   var _class = $(_o_xml).find('availability').attr('class');
   if(typeof(parseInt($(_o_xml).find('availability').attr('status')))!='number'){
     this.display_error();
   return;  
  }
  
  $('#zm_availability').empty();
  $('#zm_availability').append($(_o_xml).find('availability').text());
  
  $('#zm_availability').attr('class', _class);
 }
 
 /** update la note du marchand **/
 this.update_avg_rate_merchant = function(_o_xml){
   var container = $("div#zm_avg_rate_merchant");
   container.empty();
   var store = $(_o_xml).find('store');
   strHtml = '';
   var avg_rate = $(store).find("store_avg_rate");
   if( avg_rate.text() !== '0')
   { 
     var avgStoreNote = parseFloat(avg_rate.text())*2;
     strHtml = 'Prestation de livraison pour le marchand ' + store.find("store_name").text() + ' : '+avgStoreNote+'/10'; 
   }
   container.append(strHtml);
 }
 
 /** update price details **/
 this.update_shipments = function(_o_xml){
   var container = $("ul#zm_shipments_information");
   container.empty();
   $('div a',container.parent()).unbind();
   $('div',container.parent()).remove();
   var shipments=$(_o_xml).find('shipments_information');
   if (shipments.length==0){
     return;
   }
   var shipment = $(shipments).find('shipment');
   shipment.each(function(i,el){
     
     var moyen=($('moyen', this)[0].firstChild)?$('moyen', this)[0].firstChild.nodeValue:'';
     var prix=($('prix', this)[0].firstChild)?$('prix', this)[0].firstChild.nodeValue:'';
     var delai=($('delai', this)[0].firstChild)?$('delai', this)[0].firstChild.nodeValue:'';
    var isHide=(i>1)?{display:'none'}:{};
    var eShip=$('<li />').css(isHide).append($('<span />').addClass('zm_shipping_cost').append($('<span/>').addClass('zm_shipping_cost_label').html(moyen+ ' ')).append($('<span/>').addClass('zm_shipping_cost_amount txtbold').html(prix)))
         eShip.append($('<br />'));
         eShip.append($('<span />').attr('id','zm_shipping_delay_label').addClass('txtbold zm_shipping_delay_label').text(delai)); 
      container.append(eShip);
     i++;
    });
    if(shipment.length>3){
    container.after($('<div />').append(
    $('<a />').attr({'href':"#"}).append(
    $('<span />').addClass('float-right margin_xxs pictoFlecheUp').hide().text('+'),
    $('<span />').addClass('float-right margin_xxs pictoFlecheDown').text('-'),
    $('<div />').addClass('float-right txts hover txtvert txtlign').css('margin-right','5px').text("Plus d'infos")    
    ).click(
      function(e){     
          $('div',this).text(($('span:visible',this).is('.pictoFlecheDown'))?"Moins d'infos":"Plus d'infos");
          $('span',this).toggle();   
          e.preventDefault();
          $("li:gt(1)","ul#zm_shipments_information").stop(true,true).slideToggle('fast',function(){var _this=$(this);if(_this.is(':visible'))_this.css('display','list-item');});
          return true;
      }
    )));
    }
 }
 /** desactivation du bouton acheter **/
 this.desactivate_cart_button = function () {
  $('#cart-submit').attr('disabled', 'disabled').addClass('zm_acheter_off');
 }
 
 /** (re)activation du bouton acheter **/
 this.activate_cart_button = function () {
  $('#cart-submit').removeAttr('disabled').removeClass('zm_acheter_off');
 }

 /** gestion des visualisations des CGV **/
 this.store_sheet_click_cb = function(e) {
  e.preventDefault();
  window.open($(this).attr('_m_url'));
  return false;
 }

 /** gestion des visualisations des CGV **/
 this.store_sc_click_cb = function(e) {
  e.preventDefault();
  window.open($(this).attr('_sc_url'));
  return false;
 }

 /** gestion des clics sur le lien "tous les articles du marchand" **/
 this.store_products_click_cb = function(e) {
  e.preventDefault();
  document.location($(this).attr('_custom_url'));
  return false;
 }

 /** reinit des av courantes **/
 this.reinit_current_a_av = function() {
  this._current_a_av = new Object();
 }
/** init setup ajax **/
this.objAjaxSetup={
  url: this._offer_fetch_url,
  global: false,
  type: "POST",
  dataType:"xml",
  beforeSend:this.before_send_data,
  complete:this.display_offer_cb,
  error:this.display_error,
  success:this.success_send_data
}
}

zm_ps = new zm_ps_reloaded();


/**********************************************************************/
_.q.a(function($) {
jQuery.fn.storesManager = function(options){

  options = jQuery.extend({
    listnerEvent:'',
    value_id:''
    }, options);

  function initialize(dataFixed, element){
    jQuery.extend(options, dataFixed);
    options.eltable = element[0];
    parseData(options.xmlData, 'success');
    $('#zm_comparateur *[id^=rd_]').click(function(e){
      var elm = $(this).attr('id').split('_');
      e.preventDefault();
      if(! zm_ps.ready || !$(this).is(':checked')) return false; /** objet pas pret => on ne fait rien **/
      if(elm[1] == $(options.xmlData).find('store').attr('value_id')) return; /** l'objet en cours non cliquable **/
      zm_ps._a_av = new Object();    /** annulation des anciens criteres **/
      zm_ps._moid = null;
      zm_ps._a_av['6'] = elm[1];
      zm_ps.fetch_offer();
      return;
    });
    
    /*$(options.eltable).unbind().click(function(e){
      var target = null;
      var element = $(e.target);
      var pattern = 'a[id^=oc_]';

      if(element.is(pattern)){
        target = element;
      } else if(element.parent('a').is(pattern)){
        target = element.parent('a');
      } else{
        return;
      }

      e.preventDefault();
      
      loadOffer(target);
    });*/
  }

  var loadTableStores =function(){
    tb_show("","/m/dws/get_offers_comparateurs.php?moid=" + options.moid +"&width=810&height=530&rule=PRICE");
  }

  var loadOffer = function(target){
    var elm = $(target).attr('id').split('_');
    $('*[id$=' + elm[1] + ']').trigger('click');
  }

  var parseData = function(rep, msg){
    var eltable = (this.elTable) ? $('#'+this.elTable) : $(options.eltable);
    $('tbody label', eltable).unbind();
    $('tbody', eltable).empty();

    var storeList = $(rep).find('offer_comparable');
    var storeNumber = $(rep).find('offers_comparable').attr('nb_offers');
    if(storeNumber == 0) {
      eltable.css('display', 'none'); 
       return;
    }
    var store_selected = $(rep).find('store').attr('value_id');
    
    storeList.each(function(){
    var _store=$('oc_store',this)[0];
    var store_id =_store.getAttribute("value_id");
            var marchandObj={         
         bt_radio: tmplRadio({store:_store,
           moid: options.moid,
           store_selected: store_selected}),    
         store: tmplStore({
            moid: options.moid,
            store: _store,
            availability: $('oc_availability', this)[0],
            shipments:$('oc_shipments',this)[0]
        }),
        price: tmplPrice({
          price:$('oc_price',this)[0],
          store:_store}
          )
        //buy: tmplAcheter({offer_id:$(this).attr('id'),availability: $('oc_availability', this)[0]}) 
        }
        $('tbody',eltable).append(createTr(marchandObj,store_id,store_selected));
    });

    $('tfoot td',eltable).empty().append(
      $('<a/>').attr({'href': '#', 'title': 'Comparez'}).addClass('txtred')
        .bind('click', function(){loadTableStores();return false;})
        .html('Comparer les ' + (storeNumber) + ' offres »')
    );
           
   eltable.attr({'style':'display:table'});
    
  }
  var tmplRadio = function(sObj){
    var sel = "";
    var strHtml = '<input '+sel+' type="radio" value="'+sObj.store.getAttribute("value_id")+'" name="rd_store" id="rd_'+sObj.store.getAttribute("value_id")+'">';
    return strHtml;
  }
  var tmplStore = function(sObj){
    var store_name = sObj.store.firstChild.nodeValue;
    var strHtml = "";
    /*if($(sObj.availability).attr('status')> 0)
      strHtml += '<a href="#moid:'+sObj.moid+'" id="oc_'+sObj.store.getAttribute("value_id")+'"  title="Voir l\'offre de '+ store_name +'">';*/
    
    strHtml+= "<span class='txtbold'>"+ store_name +"</span>&nbsp;";
 if(sObj.availability){
 strHtml+= '<br />';
     var txt = sObj.availability.firstChild.nodeValue;
    switch ($(sObj.availability).attr('status')){// State 1 : now available, 0 : unavailable, 2 : soon available  -->
      case '1':
        strHtml+= '<span class="text_dispo_limite">'+ txt +'</span>';
        break;
      case '0':
        strHtml+= '<span class="text_pas_dispo">'+ txt +'</span>';
        break;
      case '2':
      case '3':
        strHtml+= '<span class="text_dispo">'+ txt +'</span>';
        break;
      case false:
      default:
        strHtml+= '<span class="text_pas_dispo">'+ txt +'</span>';
        break;
    }
 }
        
 
    //shippments

    //strHtml+='<br><span class="txtsm">'+$('oc_shipment_name',shipping).text()+' '+$('oc_shipment_amount currency',shipping).text()+'</span>';
    strHtml+= '<br /><span class="txts txtitalic">'+$('oc_shipment_amount_text',sObj.shipments).text()+'</span>';
      
    /*if($(sObj.availability).attr('status')> 0)
      strHtml+= '</a>';*/

    return strHtml;
  }
  var tmplPrice = function(sObj){  
  var priceInformations=sObj.price;
  var strHtml = ""; 
       // AVG rate
  if(sObj.store){
     if(sObj.store.getAttribute("avg_rate") !== '0')
      { 
        var avgStoreNote = parseFloat(sObj.store.getAttribute("avg_rate"))*2;
        strHtml+= '<span class="rate">(note : '+avgStoreNote+'/10)</span><br>'; 
      }
  }
    
  if(sObj.price){   
    /*  var currency=$('currency',priceInformations).get(0).firstChild.nodeValue;*/
    var priceDetails = $(sObj.price).children('price_details').get(0);
    if(priceDetails){
      $('price_detail', priceDetails).each(function(){
        strHtml+= "<div class='"+ $('price_type', this).get(0).firstChild.nodeValue +"'>";
        strHtml+= '<span class="previous">' + $('previous_price', this).text()  + '</span>';
        strHtml+= '<span class="discountP">' + $('discount_percents', this).text() + '</span>';
        strHtml+= '<span class="discountA">' + $('discount_amount', this).text()  + '</span>';
        strHtml+= "</div>";
      });
    }

    strHtml+= '<span class="priceFinal">' + $('price_final', priceInformations).text() + '</span>';
 }
    return strHtml;
  }

  var tmplAcheter = function(sObj){
    offId = sObj.offer_id;
    
    if($(sObj.availability).attr('status')>0)
      var strHtml = '<input type="submit" id="cart-submit-' + offId + '" name="offer_id" value="' + offId +'" class="zm_acheter_mini" />';
    else
      var strHtml = '<input type="button" id="cart-submit-' + offId + '" name="offer_id" value="' + offId +'" class="zm_acheter_mini_off" />';
    
    return strHtml;
  }

  var createTr = function(marchand, store_id, store_selected){

    if(store_id == store_selected){
      var lbl = $('<div/>').css({'clear':'both','display':'inline-block','margin':0,'padding':0,width:'100%'}).addClass('fondgrisclair');
    
   }else{
   
      var lbl = $('<label/>').attr({'title':'Sélectionner cette offre','for':'rd_'+store_id}).css({'clear':'both','cursor':'pointer','display':'inline-block','margin':0,'padding':0,width:'100%'}).hover(function(){$(this).addClass('fondgrisclair')},function(){$(this).removeClass('fondgrisclair')});
     }
    var tr = $('<tr/>'); 
    var trtd = $('<td/>'); 
    for (var m in marchand){
      switch (m){
      case 'store':
        var td=$('<div/>').css({'width':'55%','float':'left'}).html(marchand[m]);
        break;
      case 'bt_radio':
      var td=$('<div/>').css({'width':'10%','float':'left'})
        if(store_id != store_selected){
        td.html(marchand[m]);        
        }else{
        td.html('&nbsp;');
        }
        break;
      case 'price':
        var td=$('<div/>').css({'width':'35%','float':'left'}).html(marchand[m]);
        break;  
      default:
        var td=$('<div/>').css({'width':'35%','float':'left'}).html(marchand[m]);
        break;
      }

     lbl.append(td);
    }
    //lbl.append('<br class="clear"/>');
    trtd.append(lbl);
    tr.append(trtd);   
    return tr;
  }
  
  return $(window).bind(options.listnerEvent,this,function(event,data){
    initialize(data,event.data)});
    
};


$.fn.backMng=function(options){//http://positionabsolute.net/blog/2007/07/javascript-history-service.php
	var options={
		history_array:[],
		history_index:null,
		id_iframe_history:'HISTORYFRAME',
		url_iframe_history:'/m/emptypage.php',
		excludeUrl:['.tpl']
	};



	
	
	return  this.each(function() {
 var	createHistoryIframe=function(){
		hElement=$('<div />').css({'position':'absolute','left':10,'height':100,'width':100,'border':'1px solid red'});
		
		var strIframe='<iframe id="'+options.id_iframe_history+'" name="'+options.id_iframe_history+'" tabindex="-1" src="'+options.url_iframe_history+'">';
				strIframe+='</iframe>';
				strIframe+='<form id="'+options.id_iframe_history+'_form" method="get" target="'+options.id_iframe_history+'" action="'+options.url_iframe_history+'">';
				strIframe+='<input type="hidden" name="indexHistory" id="indexHistory" value="1" />'
				strIframe+='</form>';
		hElement.html(strIframe);
		$(_this).append(hElement);
	}
	var reloadHandle=function(e){
	 console.warn('Reload !',this,_this);
	}
	  var _this=this;
	  createHistoryIframe();
	  $('#'+this.options.id_iframe_history).load(reloadHandle)
	   return  this;
	   })


	
};


  /** init historyMng **/
//$('body').backMng();  


}, 1);






