if (!FLW) var FLW = {};

FLW.Guide = {
  'participate': function (item) {
    if (_user_id == 0) {
      FLW.Dialog.login();
    } else {
      new Kwo.Dialog('/account/flw/dialog.participate',
         {'item':item},
         {'width':640,'height':150}).onAfterClose = Kwo.reload;
    }
  },
  'subscribe': function (group_id) {
    if (_user_id == 0) {
      FLW.Dialog.login();
    } else {
      new Kwo.Dialog('/account/flw/dialog.subscribe',
         {'group_id':group_id},
         {'width':500,'height':110}).onAfterClose = Kwo.reload;
    }
  },
  'unsubscribe': function (group_id) {
    if (_user_id == 0) {
      FLW.Dialog.login();
    } else {
      new Kwo.Dialog('/account/flw/dialog.unsubscribe',
         {'group_id':group_id},
         {'width':500,'height':110}).onAfterClose = Kwo.reload;
    }
  },
  'removeMedia' : function(elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove.media', args, {'callback':FLW.Guide.removeMediaCallback});
  },
  'removeMediaCallback' : function (r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (r['result']['redirect']) {
      Kwo.go(r['result']['redirect']);
    } else { location.reload(); }
  },
  'removePhoto' : function(elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/guide.photo.remove', args, {'callback':FLW.Guide.removePhotoCallback});
  },
  'removePhotoCallback' : function (r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    $('containerPhotoSelector').update('');
    $('containerPhotoSelector').next('div.actions.removePhoto').hide();
    if ($('containerPhotoSelector').up('.viewport') && $('containerPhotoSelector').up('.panel')) {
      emile($('containerPhotoSelector').up('.viewport'), 'height:' + $('containerPhotoSelector').up('.panel').getDimensions().height + 'px', {duration:250});
    }

  },
  'unGroupMember' : function(elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/data.guide.member.ungroup', args, {'callback':Kwo.reload});
  }
};

FLW.Dialog = {
  'login': function () {
    new Kwo.Dialog('/account/flw/user/', {},
                   {'width':640,'height':520,'id':'signin-container'});
  },
  'rooms': function (accommodation_id, offset) {
    new Kwo.Dialog('/flw/rooms',
                   {'accommodation_id':accommodation_id,'offset':offset},
                   {'width':640,'height':520,'id':'room-container'});
  },
  'photos': function (item, offset) {
    new Kwo.Dialog('/flw/photos',
                   {'item':item,'offset':offset},
                   {'width':640,'height':520,'id':'photo-container'});
  },
  'videos': function (item, offset) {
    new Kwo.Dialog('/flw/videos',
                   {'item':item,'offset':offset},
                   {'width':640,'height':520,'id':'video-container'});
  },
  'invitation': function (item) {
    new Kwo.Dialog('/account/flw/dialog.invitation',
                   {'item':item},
                   {'width':640,'height':440});
  },
  'demande': function (item) {
    new Kwo.Dialog('/account/flw/dialog.demande',
                   {'item':item},
                   {'width':640,'height':440});
  },
  'grouping' : function(item) {
    new Kwo.Dialog('/flw/dialog.grouping',
                   {'item':item},
                   {'width':640,'height':520});
  },
  'destination' : function(item) {
    new Kwo.Dialog('/flw/dialog.destination',
                   {'item':item},
                   {'width':640,'height':520});
  },
  'actor' : function(item) {
    new Kwo.Dialog('/flw/dialog.actor',
                   {'item':item},
                   {'width':640,'height':520});
  },
  'package' : function(item) {
    new Kwo.Dialog('/flw/dialog.package',
                   {'item':item},
                   {'width':640,'height':520});
  },
  'trail' : function(item) {
    new Kwo.Dialog('/flw/dialog.trail',
                   {'item':item},
                   {'width':640,'height':520});
  },
  'abuse' : function(item) {
    new Kwo.Dialog('/flw/dialog.abuse',
                   {'item':item},
                   {'width':500,'height':375});
  }
};

FLW.Invitation = {
  'el': null,
  'send': function (el) {
    FLW.Invitation.el = el;
    if (!$(FLW.Invitation.el).hasClassName('disabled')) {
      $(FLW.Invitation.el).addClassName('disabled');
      Kwo.exec('/account/flw/group.invitation.send', el, {'callback':FLW.Invitation.sendCallBack});
    }
  },
  'sendCallBack': function (h) {
    $(FLW.Invitation.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
    } else {
      $(FLW.Invitation.el).up('div.panel').hide();
      $(FLW.Invitation.el).up('div.panel').next('div.success').show();
    }
  }
};

FLW.Abuse = {
  'el': null,
  'send': function (el) {
    FLW.Abuse.el = el;
    if (!$(FLW.Abuse.el).hasClassName('disabled')) {
      $(FLW.Abuse.el).addClassName('disabled');
      Kwo.exec('/abuse/abuse.report', el, {'callback':FLW.Abuse.sendCallBack});
    }
  },
  'sendCallBack': function (h) {
    $(FLW.Abuse.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
    } else {
      $(FLW.Abuse.el).up('div.panel').hide();
      $(FLW.Abuse.el).up('div.panel').next('div.success').update(h['result']['callback_msg']);
      $(FLW.Abuse.el).up('div.panel').next('div.success').show();
    }
  }
};

FLW.Clist = {
  'el': null,
  'compose': function () {
    new Kwo.Dialog('/account/social/list.new',{},{'width':640,'height':520}).onAfterClose = Kwo.reload;
  },
  'edit': function (id) {
    new Kwo.Dialog('/account/social/list.edit',{'id':id},{'width':640,'height':520}).onAfterClose = Kwo.reload;
  },
  'remove': function (el, id) {
    Kwo.exec("/account/social/list.remove", {'id':id}, {callback: Kwo.reload, confirm: el});
  },
  'add': function (el) {
    FLW.Clist.el = el;
    if (!$(FLW.Clist.el).hasClassName('disabled')) {
      $(FLW.Clist.el).addClassName('disabled');
      Kwo.exec('/account/social/list.add',el,{'callback':FLW.Clist.addCallback});
    }
  },
  'store': function (el) {
    FLW.Clist.el = el;
    if (!$(FLW.Clist.el).hasClassName('disabled')) {
      $(FLW.Clist.el).addClassName('disabled');
      Kwo.exec('/account/social/list.store',el,{'callback':FLW.Clist.storeCallback});
    }
  },
  'addCallback': function (h) {
    $(FLW.Clist.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
    } else {
      $(FLW.Clist.el).up('div.panel').hide();
      $(FLW.Clist.el).up('div.panel').next('div.success').show();
    }
  },
  'storeCallback': function (h) {
    $(FLW.Clist.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
    } else {
      $(FLW.Clist.el).up('div.panel').hide();
      $(FLW.Clist.el).up('div.panel').next('div.success').show();
    }
  }
};

FLW.Message = {
  'el': null,
  'compose': function(item,ref) {
    if (_user_id == 0) {
      FLW.Dialog.login();
    } else {
      new Kwo.Dialog('/account/flw/dialog.message',
                     {'item':item,'ref':ref},
                     {'width':640,'height':410});
    }
  },
  'send' : function(el) {
    FLW.Message.el = el;
    if (!$(FLW.Message.el).hasClassName('disabled')) {
      $(FLW.Message.el).addClassName('disabled');
      Kwo.exec('/community/message.send',FLW.Message.el,{callback:FLW.Message.onSendCallback});
    }
  },
  'onSendCallback' : function(h) {
    $(FLW.Message.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
    } else {
      $(FLW.Message.el).up('div.panel').hide();
      $(FLW.Message.el).up('div.panel').next('div.success').show();
    }
  }
};

FLW.Discussion = {
  'el': null,
  'group' : function(group_id) {
    new Kwo.Dialog('/account/flw/dialog.discussion',
                   {'group_id':group_id},
                   {'width':640,'height':410});
  },
  'send' : function(el) {
    FLW.Message.el = el;
    if (!$(FLW.Message.el).hasClassName('disabled')) {
      $(FLW.Message.el).addClassName('disabled');
      Kwo.exec('/community/discussion.send',FLW.Message.el,{callback:FLW.Message.onSendCallback});
    }
  },
  'onSendCallback' : function(h) {
    $(FLW.Message.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
    } else {
      $(FLW.Message.el).up('div.panel').hide();
      $(FLW.Message.el).up('div.panel').next('div.success').show();
    }
  }
};

FLW.Reserve = {
  'el': null,
  'add': function (item) {
    /*
    if (_user_id == 0) {
      FLW.Dialog.login();
    } else {
    */
      new Kwo.Dialog('/flw/dialog.reserve',
         {'item':item},
         {'width':640,'height':520});
//    }
  },
  'step': function (el,num) {
    $(el).up('div.step').hide();
    $(el).up('div.step').up('div').down('div.step'+num).show();
  },
  'send': function (el) {
    FLW.Reserve.el = el;
    if (!$(FLW.Reserve.el).hasClassName('disabled')) {
      $(FLW.Reserve.el).addClassName('disabled');
      Kwo.exec('/flw/reserve',FLW.Reserve.el,{callback:FLW.Reserve.onSendCallback});
    }
  },
  'onSendCallback' : function(h) {
    $(FLW.Reserve.el).removeClassName('disabled');
    if (h['error'] > 0) {
      alert(h['result']['msg']);
      FLW.Reserve.step(FLW.Reserve.el,1);
    } else {
      FLW.Reserve.step(FLW.Reserve.el,3);
    }
  }
};

FLW.Group = {
  onLeave: function(elt) {
    elt = $(elt);
    Kwo.exec("group.leave",
             {"id": elt.readAttribute("data-id")},
             {callback: Kwo.reload, confirm: true});
  }
};

FLW.Contact = {
  'add' : function(user_id) {
    if (_user_id == 0) {
      FLW.Dialog.login();
    } else {
      new Kwo.Dialog('/account/flw/dialog.contact',
                     {'user_id':user_id},
                     {'width':500,'height':110});
    }
  },
  'remove' : function(elt, user_id) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/contact.remove',{'user_id':user_id},{'callback':Kwo.reload});
  }
};

FLW.Favorite = {
  'add' : function(item) {
    new Kwo.Dialog('/account/flw/dialog.favorite',
                   {'item':item},
                   {'width':640,'height':260});
  },
  'remove' : function(user_id) {
    Kwo.exec('/account/flw/favorite.remove',{'item':item});
  }
};

FLW.Search = {
  'reload': function () {
    FLW.Search.submit();
  },
  'offset': function (offset) {
    $('offset').value = offset;
    FLW.Search.submit();
  },
  'view': function (view) {
    $('view').value = view;
    FLW.Search.offset(0);
  },
  'clear': function () {
    $('country').value = '';
    $('region').value = '';
    //$('department').value = '';
    $('model').value = '';
    $('category').value = '';
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    $('tag').value = '';
    FLW.Search.offset(0);
  },
  'country': function (value) {
    $('country').value = value;
    $('region').value = '';
    //$('department').value = '';
    $('model').value = '';
    $('category').value = '';
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'region': function (value) {
    $('region').value = value;
    //$('department').value = '';
    if ($('hide') && $('hide').value == '') {
      $('model').value = '';
    }
    $('category').value = '';
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'department': function (value) {
    $('department').value = value;
    $('model').value = '';
    $('category').value = '';
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'query': function () {
    if ($('hide').value == '') {
      $('model').value = '';
    }
    $('category').value = '';
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    FLW.Search.offset(0);
  },
  'untag': function () {
    $('tag').value = '';
    FLW.Search.offset(0);
  },
  'tag': function (value) {
    $('tag').value = value;
    FLW.Search.offset(0);
  },
  'model': function (value) {
    $('model').value = value;
    $('category').value = '';
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'category': function (value) {
    $('category').value = value;
    $('subcategory').value = '';
    $('skill').value = '';
    $('type').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'subcategory': function (value) {
    $('subcategory').value = value;
    $('skill').value = '';
    $('type').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'type': function (value) {
    $('type').value = value;
    $('skill').value = '';
    $('category').value = '';
    $('subcategory').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'skill': function (value) {
    $('skill').value = value;
    $('category').value = '';
    $('subcategory').value = '';
    if (value === '' || value > 0) {
      FLW.Search.offset(0);
    }
  },
  'submit': function () {
    if ($('search')) {
      $('search').submit();
    } else {
      location.reload();
    }
  }
};

FLW.Signup = {
  "elt_autocompleter_pro":null,
  "elt_autocompleter_member":null,
  "elt_autocompleter_profile":null,
  "activeForm" : function(type_form, otherForm) {
    var form = $(otherForm) || $('form-signup-'+type_form);
    if (!otherForm) {
      if (form.up('.box')) form.show().up('.box').show().previous('.box').hide();
      form.select('input[name="'  + type_form + '[country_id]"], '+
                  'input[name="'  + type_form + '[zip_code]"], '+
                  'select[name="' + type_form + '[region_id]"], '+
                  'select[name="' + type_form + '[department_id]"]').invoke('observe', 'flw:error_hide',
        function (e){
          $(e.target).up('li').down('span.error_msg').hide().update('');}
        );
      form.select('input[type="text"], input[type="password"]').invoke('observe', 'blur',
        function (e){
          $(e.target).up('li').down('span.error_msg').hide().update('');
          if (e.target.name == type_form + "[city]") {
            form.select('input[name="'  + type_form + '[country_id]"], '+
                        'input[name="'  + type_form + '[zip_code]"], '+
                        'select[name="' + type_form + '[region_id]"], '+
                        'select[name="' + type_form + '[department_id]"]').invoke('fire', 'flw:error_hide');

          }
        });
      if (form.select('input.terms_of_use')) form.select('input.terms_of_use').invoke('observe', 'click', function (e){ $(e.target).up('li').down('span.error_msg').hide().update(''); });
      form.select('select').invoke('observe', 'change', function (e){ if ($(e.target).up('li') && $(e.target).up('li').down('span.error_msg')) $(e.target).up('li').down('span.error_msg').hide().update(''); });
//      form.down('input[name="'+type_form+'[name]"]').observe('keyup', FLW.Signup.generateUrl);
    }
    if(FLW.Signup['elt_autocompleter_' + type_form]) {
      FLW.Signup.startAutocompleter(type_form);
    } else {
      $('ville_autocompleter_'+type_form).observe('keydown', function(e){ if (e.keyCode==13) return e.stop(); });
      $('ville_container_'+type_form).observe('keydown', function(e){ if (e.keyCode==13) return e.stop(); });
      $(type_form+'[country_id]').observe('change', FLW.Signup.onChangeCountry.curry(type_form));
      FLW.Signup['elt_autocompleter_' + type_form] = new Ajax.Autocompleter("ville_autocompleter_"+type_form, "ville_container_"+type_form, "/flw/data.villes",
        { paramName:'city',
          minChars:3,
          afterUpdateElement:FLW.Signup.getInformationVille.curry(type_form),
          parameters:'form_id=' + form.id });
    }
    FLW.Signup.onChangeCountry.curry(type_form).bind($(type_form+'[country_id]'))();
  },
  "desactiveForm" : function(type_form) {
    var form = $('form-signup-'+type_form);
    if (form.up('.box')) form.hide().up('.box').hide().prev('.box').show();
    FLW.Signup.stopAutocompleter(type_form);
  },
  "generateUrl" : function(e) {
    span_url = $($(this).up('form').down('span.url_site'));
    span_url.update(span_url.getAttribute('data-host') + this.value.urlify());
  },
  "onChangeCountry" : function(type_form) {
    if ($F(this) == '250') {
      FLW.Signup.startAutocompleter(type_form);
    } else {
      FLW.Signup.stopAutocompleter(type_form);
    }
  },
  "getInformationVille" : function (type_form, text, li) {
    try {
      var form = $(li.getAttribute('form_id'));
      form[type_form + '[zip_code]'].value = li.getAttribute('zipcode');
      FLW.Select.init("/flw/data.location", $(type_form+"[region_id]"), li.getAttribute('region_id'), 250, {"layout":"restricted"});
      FLW.Select.init("/flw/data.location", $(type_form+"[department_id]"), li.getAttribute('department_id'), li.getAttribute('region_id'), {"layout":"restricted"});
    } catch (e) { console.log(e); }
    return false;
  },
  "stopAutocompleter": function(type_form) {
    FLW.Signup['elt_autocompleter_'+type_form].disable = true;
  },
  "startAutocompleter": function(type_form) {
    FLW.Signup['elt_autocompleter_'+type_form].disable = false;
  }
};

FLW.Select = {
  'active':false,
  'init': function (url,select,value,parent,args) {
    var select = $(select);
    args.id = select.id;
    args.value =  value;
    if (parent) {
      args.parent = parent;
    }
    FLW.Select.clear(select);
    Kwo.exec(url, args, {'async':false,'callback':FLW.Select.load});
  },
  'load': function (resp) {
    var select = $(resp.result.select);
    var datas = resp.result.arr;
    var value = resp.result.value;
    for (var key in datas) {
      if (Object.isFunction(datas[key])) continue;
      var opt = document.createElement('option');
      var txt = document.createTextNode(datas[key]);
      opt.appendChild(txt);
      opt.value = key;
      if (key == value) {
        opt.selected = true;
      }
      select.appendChild(opt);
    }
    if (select.options.length<2) {
      FLW.Select.clear(select);
      select.disable();
    } else {
      select.enable();
    }
    try {
      var selects = select.up('form').select('select.auto');
      var go_disable = false;
      selects.each(function(elt){
                     if (elt.id == select.id) { go_disable = true; return; }
                     if (!go_disable) return;
                     FLW.Select.clear(elt);
                     elt.disable();
                   });
    } catch (e) { console.log(e); }
  },
  'clear': function (obj) {
    if (obj) while (obj.hasChildNodes()) {
      obj.removeChild(obj.firstChild);
    }
  }
};

FLW.UI = {
  'timerPlaylist' : 0,
  'toggleBox': function (el,opt) {
    var box = $(el).up('.box');
    var viewport = box.down('.viewport');
    $(el).hide();
    if ($(el).hasClassName('deploy')) {
      viewport.show();
      var current = (viewport.down('.panel').getDimensions().height+30)+'px';
      var callback_deploy = opt.callback_deploy || null;
      emile(viewport.setStyle({'height':((opt.height)?opt.height:'0px')}),'height:'+current,{duration:250,'after':FLW.UI.toggleBoxCallBack.curry({'show':box.down('.mask')}), 'complete':callback_deploy});
    } else {
      var current = (viewport.down('.panel').getDimensions().height+30)+'px';
      var callback_mask = opt.callback_mask || null;
      if (opt.height) {
        emile(viewport.setStyle({'height':current}),'height:'+opt.height,{duration:250,'after':FLW.UI.toggleBoxCallBack.curry({'show':box.down('.deploy')}), 'complete':callback_mask });
      } else {
        emile(viewport.setStyle({'height':current}),'height:0px',{duration:250,'after':FLW.UI.toggleBoxCallBack.curry({'show':box.down('.deploy'),'hide':viewport}), 'complete':callback_mask});
      }
    }
  },
  'toggleBoxCallBack': function (opt) {
    if (opt.show) $(opt.show).show();
    if (opt.hide) $(opt.hide).hide();
  },
  'loadData' : function(type, arg) {
    Kwo.exec("/flw/data."+type, arg, {'container':type+'-container', 'callback':FLW.UI.loadDataCallBack.curry($(type+'-container'))});
  },
  'loadDataCallBack' : function (el) {
    var box = $(el).up('.box');
    var viewport = box.down('.viewport');
    var current = viewport.down('.panel-selected').getDimensions().height+'px';
    emile(viewport,'height:'+current,{'duration':250});
  },
  'step' : function(step,lat,lng,toggle) {
    if (toggle === true) {
      var toggle = true;
    } else {
      var toggle = false;
    }
    box = $('stepbox');
    if (box.select('.step').length == 0) return;
    box.select('.step').invoke('removeClassName', 'step-selected');
    var selectstep = box.down('.step-'+step);
    selectstep.addClassName('step-selected');
    if (!toggle) {
      selectstep.up('.steps').scrollTop = selectstep.offsetTop - selectstep.up('.steps').offsetTop;
    }
    box.select('.summary').invoke('hide');
    box.down('.summary-'+step).show();
    if (step > 0 && lat != 0 && lng != 0) FLW.Map.panTo(lat,lng);
  },
  'playlist' : function(step, noFocus) {
    box = $('playlist');
    if (box.select('.step').length == 0) return;
    box.select('.step').invoke('removeClassName', 'step-selected');
    var selectstep = box.down('.step-'+step);
    selectstep.addClassName('step-selected');
    if (!noFocus) {
      selectstep.up('.steps').scrollTop = selectstep.offsetTop - selectstep.up('.steps').offsetTop;
    }
    box.select('.summary').invoke('hide');
    box.down('.summary-'+step).show();
  },
  'playlistObserver' : function (box) {
    FLW.UI.playlistToogleSummary(box, 'hide', 5000);
    $(box).observe('mouseover', FLW.UI.playlistToogleSummary.curry(box, 'show'));
    $(box).observe('mouseout', FLW.UI.playlistToogleSummary.curry(box, 'hide'));
  },
  'playlistToogleSummary' : function(box, effect, delay){
    var delay = delay != null && delay > 0 ? delay : 2000;
    var box = $(box);
    if (effect == 'show') {
      clearTimeout(FLW.UI.timerPlaylist)
      box.select('.summaries .legend').invoke('removeClassName', 'hidden');
    } else {
      FLW.UI.timerPlaylist = setTimeout(function() { box.select('.summaries .legend').invoke('addClassName', 'hidden'); }, delay);
    }
  },
  'toggleTabBox': function (el,opt) {
    var box = $(el).up('.box');
    var viewport = box.down('.viewport');
    $(el).hide();
    if ($(el).hasClassName('deploy')) {
      viewport.show();
      var current = viewport.down('.panel-selected').getDimensions().height+'px';
      emile(viewport.setStyle({'height':((opt.height)?opt.height:'0px')}),'height:'+current,{duration:250,'after':FLW.UI.toggleBoxCallBack.curry({'show':box.down('.mask')})});
    } else {
      var current = viewport.down('.panel-selected').getDimensions().height+'px';
      if (opt.height) {
        emile(viewport.setStyle({'height':current}),'height:'+opt.height,{duration:250,'after':FLW.UI.toggleBoxCallBack.curry({'show':box.down('.deploy')})});
      } else {
        emile(viewport.setStyle({'height':current}),'height:0px',{duration:250,'after':FLW.UI.toggleBoxCallBack.curry({'show':box.down('.deploy'),'hide':viewport})});
      }
    }
  },
  'switchTab' : function(el, panel) {
    el = $(el);
    if (el.up('.tab').hasClassName('selected')) return false;
    var box = el.up('.tabbox');
    var viewport = box.down('.viewport');
    var panelactive = viewport.down('.' + panel + 'panel');

    box.select('.tabs .tab').invoke('removeClassName', 'selected');
    box.select('.viewport .panel').invoke('removeClassName', 'panel-selected');
    el.up('.tab').addClassName('selected');
    panelactive.addClassName('panel-selected');
    viewport.select('.panel').invoke('hide');
    panelactive.show();

    if (el.up('.tabs').down('a.deploy') && el.up('.tabs').down('a.deploy').getStyle('display') == 'none') {
      var current = panelactive.getDimensions().height+'px';
      emile(viewport,'height:'+current,{'duration':250});
    }
  },
  'goAnchor' : function(anchor) {
    var ancre = $('anchor-'+anchor);
    var box = ancre.up('.box');
    if (box.down('.deploy') && box.down('.mask')) {
      var deploy = box.down('.deploy');
      var mask = box.down('.mask');
      if (deploy.getStyle('display') != 'none' ) {
        FLW.UI.toggleBox(deploy, {});
        setTimeout(function(){ancre.scrollTo()}, 250);

      } else ancre.scrollTo();
    } else {
      ancre.scrollTo();
    }
  },
  'getCategory':function(arg, opts){
    var arg = arg || null;
    var opts = opts || null;
    Kwo.exec('/flw/data.category', arg, opts);
  },
  'getSubCategory' : function(elt, child, selected_id) {
    elt = $(elt);
    var selected_id = selected_id || 0;
    var opts = {'callback':FLW.UI.getSubCategory_callback.curry(child, selected_id)};
    var args = {'parent_id':$F(elt), 'selected_id':selected_id};

    FLW.UI.getCategory(args, opts);
  },
  'getSubCategory_callback' : function(child, selected_id, r) {
    var child = $(child);
    if (r['result']['categories']) {
      child.update();
      var selectedValue = null;
      $H(r['result']['categories']).each(function(v) {
          child.insert(new Element('option', {'value':v.key}).update(v.value));
        });
      if (selected_id > 0) {
        var optionSelected = child.down('option[value="' + selected_id + '"]');
        if (optionSelected) {
          optionSelected.selected = true;
          optionSelected.writeAttribute({'selected':'selected'});
        }
      }
      child.up('div').show();
    } else {
      child.update();
      child.up('div').hide();
    }
  },
  'getFormEdit' : function() {
    if (_model_name) return $('form' + _model_name + 'Edit');
    return null;
   },
  'AddPublisher' : function (val) {
     var form = FLW.UI.getFormEdit();
     if (form) {
       form.insert(new Element('input', {'type':'hidden', 'name':'publish', 'value':val, 'id':'item_publisher'}));
     }
  },
  'RemovePublisher' : function () {
     var form = FLW.UI.getFormEdit();
     if (form && $('item_publisher')) {
       $('item_publisher').remove();
       return true;
     }
     return false;
  },
  'formReset' : function (elt) {
    var elt = $(elt);
    if (confirm(elt.readAttribute('data-confirm'))) {
      Kwo.reload();
    }
  }
};

FLW.Map = {
  'el':null,
  'map':null,
  'mode':null,
  'overview':null,
  'bounds':null,
  'geo':null,
  'picker':null,
  'geoLocPickerData':{},
  'init': function (opt) {
    if (GBrowserIsCompatible()) {
      Event.observe(window,'unload',FLW.Map.unload);
      FLW.Map.el = $(opt.container);
      FLW.Map.mode = opt.mode || null;
      FLW.Map.map = new GMap2($(opt.container));
      FLW.Map.bounds = new GLatLngBounds();
      if (FLW.Map.mode == 'guide') {
        FLW.Map.el.setStyle({'cursor':'pointer'});
        FLW.Map.map.disableDragging();
        GEvent.addListener(FLW.Map.map, 'click', Kwo.go.curry(opt.link));
      };
    }
  },
  'initGeoLocPicker' : function() {
    if (FLW.Map.picker) return;
    $('map').show();
    if ($('map').next('.error_msg')) $('map').next('.error_msg').hide();
    google.load("maps", "2", {"callback": function () {
      FLW.Map.init({"container":"map"});
      FLW.Map.setControl("normal");
      //FLW.Map.setType("terrain");
      FLW.Map.setOverview("terrain");
      FLW.Map.setMenu();
      FLW.Map.search();
    }});
  },
  'setType': function (type) {
    if (GBrowserIsCompatible()) {
      if (type == 'satellite') {
        FLW.Map.map.setMapType(G_SATELLITE_MAP);
      } else if (type == 'terrain') {
        FLW.Map.map.setMapType(G_PHYSICAL_MAP);
      } else if (type == 'hybrid') {
        FLW.Map.map.setMapType(G_HYBRID_MAP);
      } else {
        FLW.Map.map.setMapType(G_NORMAL_MAP);
      }
    }
  },
  'setControl': function (type) {
    if (GBrowserIsCompatible()) {
      if (type == 'small') {
        FLW.Map.map.addControl(new GSmallZoomControl3D());
      } else {
        FLW.Map.map.addControl(new GLargeMapControl3D());
      }
    }
  },
  'setOverview': function (type) {
    var size = new GSize(150,150);
    var control = new GOverviewMapControl(size,false);
    if (type == 'satellite') {
      control.setMapType(G_SATELLITE_MAP);
    } else if (type == 'terrain') {
      control.setMapType(G_PHYSICAL_MAP);
    } else if (type == 'hybrid') {
      control.setMapType(G_HYBRID_MAP);
    } else {
      control.setMapType(G_NORMAL_MAP);
    }
    FLW.Map.map.addControl(control);
  },
  'setMenu': function () {
    if (GBrowserIsCompatible()) {
       FLW.Map.map.addControl(new GMenuMapTypeControl());
       FLW.Map.map.addMapType(G_PHYSICAL_MAP);
    }
  },
  'setCenter': function (lat,lng,zoom) {
    if (GBrowserIsCompatible()) {
      var point = new GLatLng(lat,lng);
      FLW.Map.map.setCenter(point,zoom);
    }
  },
  'panTo': function (lat,lng) {
    if (GBrowserIsCompatible()) {
      var point = new GLatLng(lat,lng);
      FLW.Map.map.panTo(point);
    }
  },
  'setViewport': function (lat,lng,zoom) {
    if (GBrowserIsCompatible()) {
      //var point = new GLatLng(lat,lng);
      //FLW.Map.map.setCenter(point,zoom);
      FLW.Map.autoZoom();
      FLW.Map.map.setZoom(zoom);
    }
  },
  'openWindow': function (lat,lng,key) {
    if (GBrowserIsCompatible()) {
      FLW.Map.windowHtml(lat,lng,$(key).innerHTML);
    }
  },
  'windowHtml': function (lat,lng,html) {
    if (GBrowserIsCompatible()) {
      FLW.Map.map.openInfoWindowHtml(new GLatLng(lat,lng),html,{'maxWidth':300, 'onOpenFn': function () {
        var info = FLW.Map.map.getInfoWindow();
        var container = $(info.getContentContainers()[0]).down('.window');
        info.reset(info.getPoint(),null,new GSize(container.getWidth(),container.getHeight()));
      }});
    }
  },
  'addStep': function (lat,lng,position, callback) {
    if (GBrowserIsCompatible()) {
      var point = new GLatLng(lat,lng);
      var icon = new GIcon(G_DEFAULT_ICON);
      icon.image = '/app/flw/pix/map/num_'+position+'.png';
      icon.iconSize = new GSize(21, 35);
      icon.iconAnchor = new GPoint(11, 35);
      icon.imageMap = [0,0, 21,0, 21,35, 0,35];
      icon.shadow = '';
      icon.shadowSize = new GSize(0,0);
      var marker = new GMarker(point,{'icon':icon, 'clickable':(FLW.Map.mode == 'guide' ? false : true)});
      if (FLW.Map.mode != 'guide') {
        GEvent.addListener(marker, 'click', callback);
      };
      FLW.Map.map.addOverlay(marker);
      FLW.Map.bounds.extend(point);
    }
  },
  'addMarker': function (lat,lng,model,key,name) {
    if (GBrowserIsCompatible()) {
      var point = new GLatLng(lat,lng);
      var icon = new GIcon(G_DEFAULT_ICON);
      icon.image = '/app/flw/pix/map/dot_'+model+'.png';
      icon.iconSize = new GSize(20,27);
      icon.iconAnchor = new GPoint(0,27);
      icon.imageMap = [0,0, 20,0, 20,27, 0,27];
      icon.shadow = '';
      icon.shadowSize = new GSize(0,0);
      var marker = new GMarker(point,{'icon':icon,'clickable':(FLW.Map.mode == 'guide' ? false : true),'title':name});
      if (FLW.Map.mode != 'guide' ) {
        GEvent.addListener(marker, 'click', FLW.Map.openWindow.curry(lat,lng,key));
      };
      FLW.Map.map.addOverlay(marker);
      FLW.Map.bounds.extend(point);
    }
  },
  'addPoint': function (lat,lng,model) {
    if (GBrowserIsCompatible()) {
      var point = new GLatLng(lat,lng);
      var icon = new GIcon(G_DEFAULT_ICON);
      icon.image = '/app/flw/pix/map/dot_'+model+'.png';
      icon.iconSize = new GSize(20,27);
      icon.iconAnchor = new GPoint(0,27);
      icon.imageMap = [0,0, 20,0, 20,27, 0,27];
      icon.shadow = '';
      icon.shadowSize = new GSize(0,0);
      var marker = new GMarker(point,{'icon':icon,'clickable':false});
      FLW.Map.map.addOverlay(marker);
      FLW.Map.bounds.extend(point);
    }
  },
  'addPicker': function (lat,lng,zoom) {
    if (GBrowserIsCompatible() && !FLW.Map.picker) {
      var point = new GLatLng(lat,lng);
      var icon = new GIcon(G_DEFAULT_ICON);
      FLW.Map.picker = new GMarker(point, {'icon':icon, 'clickable':false, 'draggable': true});
      GEvent.addListener(FLW.Map.picker, 'dragend', FLW.Map.addPickerCallback);
      FLW.Map.map.addOverlay(FLW.Map.picker);
      FLW.Map.bounds.extend(point);
      if (!zoom) zoom = FLW.Map.map.getBoundsZoomLevel(FLW.Map.bounds);
      FLW.Map.map.setCenter(point, zoom);
    }
  },
  'addPickerCallback': function () {
    if (FLW.Map.picker) {
      var point = FLW.Map.picker.getPoint();
      if (point) {
        FLW.Map.picker.lat = point.y;
        FLW.Map.picker.lng = point.x;
        FLW.Map.picker.zoom = FLW.Map.map.getZoom();

        $(FLW.Map.geoLocPickerData.opts.lat).value = point.y;
        $(FLW.Map.geoLocPickerData.opts.lng).value = point.x;
        $(FLW.Map.geoLocPickerData.opts.zoom).value = FLW.Map.map.getZoom();
        FLW.Map.map.setCenter(point);
      }
    }
  },
  'search': function () {
    if (GBrowserIsCompatible()) {
      GEvent.addListener(FLW.Map.map, 'zoomend', FLW.Map.addPickerCallback);
      FLW.Map.map.clearOverlays();
      if (FLW.Map.geoLocPickerData.args.lat != 0 && FLW.Map.geoLocPickerData.args.lng != 0) {
        if (!FLW.Map.geoLocPickerData.args.zoom) FLW.Map.geoLocPickerData.args.zoom = 6;
        FLW.Map.addPicker(FLW.Map.geoLocPickerData.args.lat, FLW.Map.geoLocPickerData.args.lng, FLW.Map.geoLocPickerData.args.zoom);

      } else if (FLW.Map.geoLocPickerData.args.address.length > 0) {
        FLW.Map.geo = new GClientGeocoder();
        FLW.Map.geo.getLatLng(FLW.Map.geoLocPickerData.args.address, FLW.Map.result.curry('simpleaddress', 'address'));

      } else if (FLW.Map.geoLocPickerData.args.simpleaddress.length > 0) {
        FLW.Map.geo = new GClientGeocoder();
        FLW.Map.geo.getLatLng(FLW.Map.geoLocPickerData.args.simpleaddress, FLW.Map.result.curry((FLW.Map.geoLocPickerData.args.country ? 'country' : false), 'simpleaddress'));

      } else if (FLW.Map.geoLocPickerData.args.country.length > 0) {
        FLW.Map.geo = new GClientGeocoder();
        FLW.Map.geo.getLatLng(FLW.Map.geoLocPickerData.args.country, FLW.Map.result.curry(false, 'country'));
      }
    }
  },
  'result': function (force, ask, point) {
    var nextForce = {'address' : 'simpleaddress', 'simpleaddress' : 'country', 'country' : false};
    if (!point && force && FLW.Map.geoLocPickerData.args[force]) {
      FLW.Map.geo = new GClientGeocoder();
      FLW.Map.geo.getLatLng(FLW.Map.geoLocPickerData.args[force], FLW.Map.result.curry(nextForce[force], force));
    } else if (point) {

      if (ask == 'country') {
        alert("L'adresse fournis n'a pu être trouvé.\n\nVeuillez préciser un point manuellement.");
        var zoom = 5;
      } else if (ask == 'simpleaddress') {
        alert("L'adresse fournis n'a pu être trouvé.\n\nVeuillez préciser un point manuellement.");
        var zoom = 13;
      } else if (ask == 'address') {
        var zoom = 16;
      } else {
        var zoom = FLW.Map.map.getBoundsZoomLevel(FLW.Map.bounds);
      }

      FLW.Map.addPicker(point.y, point.x, zoom);

      $(FLW.Map.geoLocPickerData.opts.lat).value = point.y;
      $(FLW.Map.geoLocPickerData.opts.lng).value = point.x;
      $(FLW.Map.geoLocPickerData.opts.zoom).value = zoom;

    } else {
      alert("L'adresse fournis n'a pu être trouvé.\n\nVeuillez préciser un point manuellement.");
      FLW.Map.addPicker(48.8314408, 2.3255684, 3); //centrer sur l'europe si fail !
//      FLW.Map.autoZoom();
//      $('map').hide().next('.error_msg').show();
    }

  },
  'resetGeopicker' : function() {

  },
  'autoZoom': function () {
    //var zoomAdjust = parseInt(zoomAdjust);
    if (GBrowserIsCompatible()) {
      var point = FLW.Map.bounds.getCenter();
      var zoom = FLW.Map.map.getBoundsZoomLevel(FLW.Map.bounds);
      FLW.Map.map.setCenter(point,(zoom-1));
    }
  },
  'clear': function () {
    FLW.Map.bounds = new GLatLngBounds();
    FLW.Map.map.clearOverlays();
  },
  'unload': function () {
    if (GBrowserIsCompatible()) {
      GUnload();
    }
  }
};

// Account

FLW.Validation = {
  'setValidate' : function (opts) {
    var error = false;
    var privacy = opts['privacy'] || false;
    delete(opts['privacy']);
    $H(opts).each(function (el) {
        $$('.validation' + el.key.capitalize()).each(function (elt) {
            if (elt.up('.title')) elt.update(el.value ? '' : '<strong>incomplet</strong>');
            else elt.update(el.value ? 'complet' : '<strong>incomplet</strong>');
            if (!el.value) error = true;
          });
      });
      var validationBox = $$('.smallcol .validationbox');
      if (validationBox.length == 1) {
        if (error) {
          $('buttonValidateBox').hide();
          if ($('item_publisher')) alert(validationBox[0].readAttribute('data-confirm'));
          validationBox[0].down('.viewport').removeClassName('isValidate');
          validationBox[0].down('.viewport').addClassName('isUnValidate');
        } else {
          $('buttonValidateBox').show();
          validationBox[0].down('.viewport').removeClassName('isUnValidate');
          validationBox[0].down('.viewport').addClassName('isValidate');
        }
        if (privacy) $('buttonValidateBox').hide();
      }
  },
  'hasPublish' : function(v) {
    if (!$('btnItemPublish') || !$('btnItemUnPublish')) return;
    if (v) {
      $('btnItemPublish').hide();
      $('btnItemUnPublish').show();
    } else {
      $('btnItemPublish').show();
      $('btnItemUnPublish').hide();
    }
    FLW.UI.RemovePublisher();
  },
  'uniqTag' : function(elt) {
    var elt = $(elt);
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      form = elt;
    } else {
      form = elt.up('form');
    }
    var tag_values = [];
    var i = 0;
    form.select('input[name="product[tags][]"]').each(function(elt){ if (!$F(elt).blank()) { tag_values.push($F(elt).toLowerCase()); } elt.setValue(''); });
    tag_values = tag_values.uniq();
    form.select('input[name="product[tags][]"]').each(function(elt){ if (tag_values[i]) elt.setValue(tag_values[i]); i++ });
  }
};

FLW.Grouping = {
  'create' : function(args) {
    Kwo.exec('/account/flw/guide.create', args, {'callback':FLW.Grouping.create_callback});
  },
  'create_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (r['result']['redirect']) Kwo.go(r['result']['redirect']);
  },
  'save' : function(elt) {
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', elt, {'callback':FLW.Grouping.save_callback});
  },
  'save_callback' : function(r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'add' : function (args) {
    if ($('map')) $('map').id = 'map-suspend';
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'groupingSelectorProductDialog'}).onAfterClose = FLW.Grouping.onAfterClose;
    Kwo.getDialog('groupingSelectorProductDialog').onAfterCommit = FLW.Grouping.onAfterCommit;
  },
  'onAfterClose' : function () {
    if ($('map-suspend')) $('map-suspend').id = 'map';
    location.reload();
  },
  'showMediaSelector' : function(media, args) {
    args = args || {};
    args.showContainer = true;
    new Kwo.Dialog('/account/flw/data.selection.' + media + 's', args, {width:780, height:360, 'containerMedia': media + 'Drag', 'name':'wizMediaSelectorDialog'}).onAfterCommit = FLW.Grouping.onAfterCommit;
  },
  'showMediaCreator' : function(media, args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.' + media + '.create', args, {'width':500, 'height':(media == 'photo' ? 400 : 300), 'containerMedia': media + 'Drag', 'name': media + 'CreateDialog'}).onAfterCommit = FLW.Grouping.onAfterCommit;
  },
  'onAfterCommit' : function () {
    location.reload();
  },
  'addSteps' : function(args) {
    if ($('map')) $('map').id = 'map-suspend';
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'groupingSelectorStepsDialog'}).onAfterClose = FLW.Grouping.onAfterClose;
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Package.save($('formGroupingEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Package.save($('formGroupingEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Grouping.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  },
  'removeProduct' : function(elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove.product', args, {'callback':FLW.Grouping.removeProduct_callback});
  },
  'removeProduct_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Search.reload();
  }
};

FLW.Destination = {
  'create' : function(args) {
    Kwo.exec('/account/flw/guide.create', args, {'callback':FLW.Destination.create_callback});
  },
  'create_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (r['result']['redirect']) Kwo.go(r['result']['redirect']);
  },
  'save' : function(elt) {
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', elt, {'callback':FLW.Destination.save_callback});
  },
  'save_callback' : function(r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'add' : function (args) {
    if ($('map')) $('map').id = 'map-suspend';
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'groupingSelectorProductDialog'}).onAfterClose = FLW.Grouping.onCloseDialog;
    Kwo.getDialog('destinationSelectorProductDialog').onAfterCommit = FLW.Grouping.onAfterCommit;
  },
  'onCloseDialog' : function () {
    if ($('map-suspend')) $('map-suspend').id = 'map';
  },
  'showMediaSelector' : function(media, args) {
    args = args || {};
    args.showContainer = true;
    new Kwo.Dialog('/account/flw/data.selection.' + media + 's', args, {width:780, height:360, 'containerMedia': media + 'Drag', 'name':'wizMediaSelectorDialog'}).onAfterCommit = FLW.Grouping.onAfterCommit;
  },
  'showMediaCreator' : function(media, args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.' + media + '.create', args, {'width':500, 'height':(media == 'photo' ? 400 : 300), 'containerMedia': media + 'Drag', 'name': media + 'CreateDialog'}).onAfterCommit = FLW.Grouping.onAfterCommit;
  },
  'onAfterCommit' : function () {
    location.reload();
  },
  'addSteps' : function(args) {
    if ($('map')) $('map').id = 'map-suspend';
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'destinationSelectorStepsDialog'}).onAfterClose = FLW.User.onAfterClose;
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Package.save($('formDestinationEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Package.save($('formDestinationEdit'));
  }
};

FLW.Duration = {
  'change': function (day,hour,min,res) {
    $(res).value = (parseInt($(hour).value)*60)+parseInt($(min).value); //(parseInt($(day).value)*3600)+
  }
};

FLW.Room = {
  'change': function(accommodation_id,offset) {
    Kwo.exec("/flw/rooms",
             {'accommodation_id':accommodation_id,'offset':offset},
             {'container':'room-container'});
  },
  'create' : function(args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.room.create', args, {'width':500, 'height':400, 'name':'roomCreateDialog'});
  },
  'createPhotos' : function(args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.photo.create', args, {'width':500, 'height':400, 'containerMedia':'roomPhotoDrag', 'name':'roomCreatePhotosDialog'});
  },
  'showMediaSelector' : function(media, args, opts) {
    args = args || {};
    args.showContainer = true;
    new Kwo.Dialog('/account/flw/data.selection.' + media + 's', args, {width:780, height:360, 'containerMedia':'roomPhotoDrag', 'name':'roomMedia' + media + 'SelectorDialog'});//.onAfterCommit = FLW.Room.reloadRoom.curry($H(args).update(opts));
  },
  'edit' : function(args) {
    var args = args || null;
    var opts = {'width':600, 'height':500, 'containerMedia':'roomPhotoDrag', 'name':'roomEditDialog'};
    if (Kwo.getDialog('roomEditDialog')) {
      opts.container = Kwo.getDialog('roomEditDialog').support;
      Kwo.exec('/account/flw/data.room.edit', args, opts);
    } else {
      new Kwo.Dialog('/account/flw/data.room.edit', args, opts);
    }
  },
  'createEntry' : function(args) {
    args = $(args);
    if (args.down('input[name="room[price]"]') && args.down('input[name="room[price]"]').value.blank()) {
      alert("Vous devez d'abord saisir les informations obligatoires pour continuer.");
      return false;
    }
    Kwo.exec('/account/flw/data.room.add', args, {'callback':FLW.Room.createEntry_callback.curry(args)});
  },
  'createEntry_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Kwo.getDialog('roomCreateDialog')) Kwo.getDialog('roomCreateDialog').close();
//console.log(args, r);
    FLW.Room.addPhotos({'room':r['result']['room'], 'accommodation_key':$F(args.accommodation_key)});
  },
  'addPhotos' : function(args) {
    new Kwo.Dialog('/account/flw/data.room.create.photos', args, {width:780, height:550, 'containerMedia':'roomPhotoDrag', 'name':'roomCreateDialogPhoto'}).onAfterCommit = FLW.Room.onAfterCommit.curry(args);
  },
  'onAfterCommit' : function(args) {
    Kwo.getDialog('roomCreateDialog').close();

//    FLW.Room.reloadItems({'accommodation_key' : args.accommodation_key});
  },
  'store' : function(args) {
    if (args.select('#roomPhotoDrag .dragbox').length == 0) {
      alert("Vous devez d'abord saisir les informations obligatoires pour continuer");
      return false;
    }
    Kwo.exec('/account/flw/data.room.store', args, {'callback':FLW.Room.store_callback.curry(args)});
  },
  'store_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    FLW.Room.reloadItems(args);
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Kwo.getDialog('roomCreateDialogPhoto')) Kwo.getDialog('roomCreateDialogPhoto').close();
    if (Kwo.getDialog('roomEditDialog')) Kwo.getDialog('roomEditDialog').close();
  },
  'setPositions' : function() {
    var container = $('roomDrag');
    var result = container.next('#roomDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[rooms][' + elt.down('.item').readAttribute('key')+ ']', 'value':pos++})});
        });
    }
  },
  'remove' : function (elt, accommodation_key) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.room.remove', {'room':$(elt).up('div.dragbox').down('a.item').readAttribute('key'), 'accommodation_key':accommodation_key}, {'callback':FLW.Room.remove_callback.curry(elt, accommodation_key)});
  },
  'remove_callback' : function (elt, item, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    $(elt).up('div.dragbox').remove();
    FLW.Room.reloadItems({'accommodation_key':item});
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
  },
  'removeIntoDialog' : function (elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.room.remove', args, {'callback':FLW.Room.remove_callback.curry(args)});
  },
  'removeIntoDialog_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    $('roomDrag').down('div[key="' + args.room + '"]').remove();
    Kwo.getDialog().close();
    FLW.Room.reloadItems(args);
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
  },
  'reloadItems' : function(args) {
    if ($('containerRooms')) {
      Kwo.exec('/account/flw/data.room.load', args, {'container':'containerRooms', 'callback':FLW.Room.reloadItems_callback});
    }
  },
  'reloadItems_callback' : function() {
    if ($('roomDrag').up('.viewport') && $('roomDrag').up('.panel')) {
      emile($('roomDrag').up('.viewport'), 'height:' + $('roomDrag').up('.panel').getDimensions().height + 'px', {duration:250});
    }
    Sortable.create("roomDrag", {"revert":true, "overlap":"horizontal", "scroll":window, "ghosting":false, "constraint":false, "tag":"div", "onChange":FLW.Room.setPositions});
  },
  'reloadRoom' : function(args) {
    if (Kwo.getDialog('roomMediaphotoSelectorDialog')) Kwo.getDialog('roomMediaphotoSelectorDialog').close();
    if (Kwo.getDialog('roomCreateDialogPhoto')) Kwo.getDialog('roomCreateDialogPhoto').close();
/*
    if (Kwo.getDialog('roomEditDialog') && Kwo.getDialog('roomEditDialog').close()) {
      while (Kwo.getDialog('roomEditDialog')) ;
    }
*/
    FLW.Room.edit(args);
  }
};

FLW.Period = {
  'activeAllYear' : function(elt) {
    elt = $(elt);
    if (elt.checked) {
      $('periodsContainer').hide();
      $('periodsContainer').select('div.period').invoke('remove');
    } else {
      $('periodsContainer').show();
    }
    if (elt.up('.viewport') && elt.up('.panel')) emile(elt.up('.viewport'), 'height:' + elt.up('.panel').getDimensions().height + 'px', {duration:0});
  },
  'setDate' : function (elt) {
    var elt = $(elt);

    var day   = $F(elt.up(0).down('select.day'));
    var month = $F(elt.up(0).down('select.month'));
    var year  = $F(elt.up(0).down('select.year'));
    elt.up(0).down('input.date').value = year + '-' + month + '-' + day;

    if (elt.up(0).down('input.time')) {
      var h = $F(elt.up(0).down('select.hour'));
      var m = $F(elt.up(0).down('select.minute'));
      elt.up(0).down('input.time').value = h + ':' + m;
    }
  },
  'addPeriod' : function() {
    Kwo.exec('/account/flw/data.period.create', {'item':$F('item_key')}, {'container':'item_periods', 'callback':FLW.Period.addPeriod_callback});
  },
  'addPeriod_callback' : function () {
    if ($('item_periods').up('.viewport')) emile($('item_periods').up('.viewport'), 'height:' + $('item_periods').up('.panel').getDimensions().height + 'px', {duration:0});
  },
  'remove' : function(elt, key) {
    if (!confirm('Êtes-vous sur de vouloir supprimer cette période ?')) return;
    Kwo.exec('/account/flw/data.period.remove', {'item':$F('item_key'), 'period':key}, {'callback':FLW.Period.remove_callback.curry(elt)});
  },
  'remove_callback' : function(elt, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    $(elt).up('.period').remove();
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Period.reload();
  },
  'reload' : function(){
    Kwo.exec('/account/flw/data.periods', {'item':$F('item_key')}, {'container':'item_periods'});
    if ($('item_periods').up('.viewport') && $('item_periods').up('.panel')) {
      if ($('item_periods').up('.viewport')) emile($('item_periods').up('.viewport'), 'height:' + $('item_periods').up('.panel').getDimensions().height + 'px', {duration:0});
    }
  }
};

FLW.Video = {
  'change': function(item,offset) {
    Kwo.exec("/flw/videos",
             {'item':item,'offset':offset},
             {'container':'video-container'});
  },
  'create' : function(args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.video.create', args, {'width':520, 'height':300, 'containerMedia':'videoDrag', 'name':'videoCreateDialog'});
  },
  'addEntry' : function(elt) {
    var elt = $(elt);
    var entries = elt.up('.viewport').down('.entries');
    var entry = entries.down('.template').clone(true).removeClassName('template').addClassName('entry');
    entry.down('div.remove').show();
    entry.down('input').value='http://';
    entries.insert(entry);
  },
  'removeEntry' : function(elt) {
    var elt = $(elt);
    elt.up('.entry').remove();
  },
  'createEntry' : function(args) {
    Kwo.exec('/account/flw/data.video.add',
             args,
             {'callback':FLW.Video.createEntry_callback.curry(args)});
  },
  'createEntry_callback' : function(args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    } else {
      var guide = args.guide ? args.guide.clone(true) : null;
      Kwo.exec('/account/flw/data.video.add.detail',
               {'videos_id[]':r['result']['videos_id']},
               {'container':'dataCreateVideo',
                'callback':function(){ if (guide) { $('dataCreateVideo').insert({'top': guide }); }}});
    }
  },
  'storeEntry' : function(args) {
    Kwo.exec('/account/flw/data.video.store', args, {'callback':FLW.Video.storeEntry_callback.curry(args)});
  },
  'storeEntry_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['loadItems']) {
      var item = args.guide.clone(true);
      item.name = 'item';
      FLW.Video.getSelections_callback(item, r);
    } else {
      if (Kwo.getDialog()) Kwo.getDialog().close();
    }
  },
  'store' : function(args) {
    Kwo.exec('/account/flw/data.video.edit', args, {'callback':FLW.Video.store_callback.curry(args)});
  },
  'store_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
  },
  'remove' : function(args) {
    if (!confirm('La video sera retiré de tout les éléments où elle a été lié.\n\nÊtes vous sûr de vouloir supprimer cette video ?')) return;
    Kwo.exec('/account/flw/data.video.remove', args, {'callback':FLW.Video.remove_callback.curry(args)});
  },
  'remove_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go(r['result']['redirect']);
  },
  'getSelections' : function(elt, args) {
    var args = args || $('selection-list-video').down('form');
    if (args.select('.item').length == 0) {
      alert($(elt).readAttribute('data-error-no-selection'));
      return;
    }
    Kwo.exec('/account/flw/catalog.add.media', args, {'callback':FLW.Video.getSelections_callback.curry(args.item)});
  },
  'getSelections_callback' : function(item, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    var items = r['result']['videos'];
    var args = new Element('form');
    args.insert(item);
    var pos = 0;
    items.each(function(elt){args.insert(new Element('input', {'type':'hidden', 'name':'product[videos]['+elt+']', 'value':pos++}))});
    FLW.Video.loadItems(args);
  },
  'loadItems' : function (args) {
    if ($('videoDrag')) {
      Kwo.exec('/account/flw/data.selection.load.items', args, {'container':$('videoDrag'), 'callback':FLW.Video.loadItems_callback });
      if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
    } else {
      if (Kwo.getDialog()) {
        if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
        Kwo.getDialog().close();
      }
    }
  },
  'loadItems_callback' : function(r) {
    Sortable.create("videoDrag", {"revert":true, "overlap":"horizontal", "scroll":window, "ghosting":false, "constraint":false, "tag":"div", "onChange":FLW.Video.setPositions});
    $('videoDrag').insert({'bottom':new Element('div', {'class':'clear', 'style':'position:static'})});
    FLW.Video.setPositions();
    if ($('videoDrag').up('.viewport')) {
      emile($('videoDrag').up('.viewport'), 'height:' + $('videoDrag').up('.panel').getDimensions().height + 'px', {duration:250});
    }
    Kwo.getDialog().close();
  },
  'addToSelection':function(elt) {
    elt = $(elt);
    var classname = elt.up('div.item').down('input[type="hidden"]').value;
    if ($('selection-list-video').select('.' + classname).length > 0) {
      return;
    }
    var item = elt.up('.item').clone(true);
    item.addClassName(classname);
    item.select('div.action').invoke('remove');
    item.down('div.remove').show();
    item.down('input').enable();
    $('selection-list-video').down('.container').insert({'bottom':item});

    FLW.Video.countSelection();
    FLW.Video.resizeSelection();
  },
  'removeFromSelection':function(elt){
    $(elt).up('.item').remove();
    FLW.Video.countSelection();
    FLW.Video.resizeSelection();
  },
  'countSelection':function(){
    var countSelection = $('selection-list-video').down('.container').select('.item ').length;
    $('selection-count-video').update(countSelection);
  },
  'resizeSelection' : function() {
    if ($('selection-list-video').getDimensions().width <= 260) {
      $('selection-list-video').scrollTop = $('selection-list-video').getDimensions().height;
      return;
    }
    var width = 0;
    var height = 0;
    var container = $('selection-list-video').down('.container');
    var items = container.select('.item');
    items.each(function(elt){
                 var dim = $(elt).getDimensions();
                 height = dim.height > height ? dim.height : height;
                 width += Number($(elt).getDimensions().width)
                              + Number($(elt).getStyle('marginLeft').replace('px', ''))
                              + Number($(elt).getStyle('marginRight').replace('px', ''));
                            });
    height += 10;
    $('selection-list-video').down('.container').setStyle({'width':width+'px', 'height':height+'px'});
    $('selection-list-video').scrollLeft = $('selection-list-video').scrollWidth;
  },
  'setPositions' : function() {
    var container = $('videoDrag');
    var result = container.next('#videoDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[videos][' + elt.down('.item').readAttribute('key')+ ']', 'value':pos++})});
        });
    }
  },
  'removeRelation' : function (elt, item) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove.media', {'media':$(elt).up('div.dragbox').down('a.item').readAttribute('key'), 'item':item}, {'callback':FLW.Video.removeRelation_callback.curry(elt)});
  },
  'removeRelation_callback' : function (elt) {
    $(elt).up('div.dragbox').remove();
    if ($('videoDrag').up('.viewport')) {
      emile($('videoDrag').up('.viewport'), 'height:' + $('videoDrag').up('.panel').getDimensions().height + 'px', {duration:250});
    }
    FLW.Video.setPositions();
  },
  'skipDetails' : function (args) {
    if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
    Kwo.getDialog().close();
  }
};

FLW.Photo = {
  'create' : function(args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.photo.create', args, {'width':500, 'height':400, 'containerMedia':'photoDrag', 'name':'photoCreateDialog'});
  },
  'addEntry' : function(elt) {
    var form = $('dataCreatePhoto');
    $('dataCreatePhotoContrainer').down('.throbber').show();
    form.submit();
    form.disable();
  },
  'addEntry_callback' : function(r) {
    var form = $('dataCreatePhoto');
    form.enable();
    $('dataCreatePhotoContrainer').down('.throbber').hide();
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);

    if (r['result']['mode'] == 'user') {
      var btn_action = false;
    } else {
      var btn_action = true;
    }
    $('dataCreatePhotoContrainer').down('.espace_occupe_photo').update(r['result']['pcent']);
    var photo = (new Element('div')).update(r['result']['photo']).down(0);

    var input = photo.down('input[name="product[photos][]"]').enable();
    photo.down('.action').remove();
    if (Kwo.getDialog().opts.container) var container = $(Kwo.getDialog().opts.container);
    if (container && container.down('#thumbPhotoSelector') && !$('containerPhotoSelector')) {
//      if (container.down('#thumbPhotoSelector')) {
        input.name = 'product[rubriques][' + container.id.substr(4) + '][photo]';
        container.down('#thumbPhotoSelector').update(input);
        container.down('#thumbPhotoSelector').setStyle({'backgroundImage':photo.down('a.thumbnail').getStyle('backgroundImage')});
/*
      } else {
        input.name = "product[photo]";
        container.down('#containerPhotoSelector').update(photo);
      }
*/
      Kwo.getDialog().close();
    } else if ($('containerPhotoSelector')){
      input.name = "product[photo]";
      photo.down('.remove').remove();
      var url = photo.down('a.thumbnail').getStyle('backgroundImage');
      url = url.substr(5, url.length-7);
      var path = url.dirname();
      var file = url.basename().pop();
      var img = 'url(' + path + '/_533_' + file.match(/^_[0-9]*_(.*)/).pop() + ')';
      photo.down('a.thumbnail').setStyle({'backgroundImage':img}).addClassName('noclick').removeAttribute('href');
      $('containerPhotoSelector').update(photo);
      if ($('containerPhotoSelector').next('div.actions .removePhoto')) {
        $('containerPhotoSelector').next('div.actions .removePhoto').show();
      }
      if ($('containerPhotoSelector').up('.viewport') && $('containerPhotoSelector').up('.panel')) {
        emile($('containerPhotoSelector').up('.viewport'), 'height:' + $('containerPhotoSelector').up('.panel').getDimensions().height + 'px', {duration:250});
      }

      $('containerPhotoSelector').update(photo);
      Kwo.getDialog().close();
    } else {
      if (!btn_action) {
        photo.down('input[type="hidden"]').remove();
        photo.down('.remove').remove();
      } else {
        input.name = "photos[]";
        photo.down('.remove').show();
      }
      $('dataCreatePhotoContrainer').down('.entries .clear:last-child').insert({'before':photo});
      if ($('dataCreatePhotoContrainer').select('.entries .item').length%2 == 0) {
        $('dataCreatePhotoContrainer').down('.entries').insert({'bottom':new Element('div').addClassName('clear')});
      }
      form.reset();
    }
  },
  'removeEntry' : function(elt) {
    var elt = $(elt);
    elt.up('.entry').remove();
  },
  'storeEntry' : function(args) {
    Kwo.exec('/account/flw/data.photo.add.relations', args, {'callback':FLW.Photo.storeEntry_callback.curry(args)});
  },
  'storeEntry_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['loadItems']) {
      var item = args.guide.clone(true);
      item.name = 'item';
      FLW.Photo.getSelections_callback(item, r);
    } else {
      if (Kwo.getDialog()) Kwo.getDialog().close();
    }
  },
  'store' : function(args) {
    Kwo.exec('/account/flw/data.photo.edit', args, {'callback':FLW.Photo.store_callback.curry(args)});
  },
  'store_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
  },
  'remove' : function(args) {
    if (!confirm('La photo sera retirée de tout les éléments où elle a été liée.\n\nÊtes vous sûr de vouloir supprimer cette photo ?')) return;
    Kwo.exec('/account/flw/data.photo.remove', args, {'callback':FLW.Photo.remove_callback.curry(args)});
  },
  'remove_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go(r['result']['redirect']);
  },
  'change': function(item,offset) {
    Kwo.exec("/flw/photos",
             {'item':item,'offset':offset},
             {'container':'photo-container'});
  },
  'load': function (url) {
    var img = new Image();
    img.onload = FLW.Photo.show;
    img.src = url;
  },
  'show': function () {
    var photo_box = $('photo');
    if (photo_box.getWidth() < 800) {
      var max_width = 640;
      var max_height = 450;
    } else {
      var max_width = 800;
      var max_height = 600;
    }
    var div = photo_box.down('.image');
    var img = div.down('img');
    if (this.width > max_width || this.height > max_height) {
      var width = max_width;
      var height = max_width / (this.width/this.height);
      if (height > max_height) {
               width = max_height * (this.width/this.height);
               height = max_height;
      }
    } else {
      var width = this.width;
      var height = this.height;
    }
    width = Math.round(width);
    height = Math.round(height);
    div.removeClassName('loading');
    img.src = this.src;
    img.setStyle({"height":height+"px","width":width+"px"});
    img.show();
  },
  'getSelections' : function(elt, args) {
    var args = args || $('selection-list-photo').down('form');
    if (args.select('.item').length == 0) {
      alert($(elt).readAttribute('data-error-no-selection'));
      return;
    }
    Kwo.exec('/account/flw/catalog.add.media', args, {'callback':FLW.Photo.getSelections_callback.curry(args.item)});
  },
  'getSelections_callback' : function(item, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      if ($F(item).split('-')[0] == 11113 && Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    var items = r['result']['photos'];
    var args = new Element('form');
    args.insert(item);
    var pos = 0;
    items.each(function(elt){args.insert(new Element('input', {'type':'hidden', 'name':'product[photos]['+elt+']', 'value':pos++}))});
    FLW.Photo.loadItems(args);
  },
  'loadItems' : function (args){
    var container = Kwo.getDialog() ? Kwo.getDialog().opts['containerMedia'] : 'photoDrag';
    if ($(container)) {
      Kwo.exec('/account/flw/data.selection.load.items', args, {'container':$(container), 'callback':FLW.Photo.loadItems_callback});
      if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
    } else {
      if (Kwo.getDialog()) {
        if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
        Kwo.getDialog().close();
      }
    }
  },
  'loadItems_callback': function(r) {
    var containerPhoto = Kwo.getDialog() ? Kwo.getDialog().opts['containerMedia'] : 'photoDrag';
    Sortable.create(containerPhoto, {"revert":true, "overlap":"horizontal", "scroll":window, "ghosting":false, "constraint":false, "tag":"div", "onChange":FLW.Photo.setPositions});
    $(containerPhoto).insert({'bottom':new Element('div', {'class':'clear', 'style':'position:static'})});
    FLW.Photo.setPositions();
    if ($(containerPhoto).up('.viewport') && $(containerPhoto).up('.panel')) {
      emile($(containerPhoto).up('.viewport'), 'height:' + $(containerPhoto).up('.panel').getDimensions().height + 'px', {duration:250});
    }
    Kwo.getDialog().close();
  },
  'addToSelection':function(elt) {
    elt = $(elt);
    if (Kwo.getDialog().opts.container) var container = $(Kwo.getDialog().opts.container);
    if (!$('selection-list-photo') && $('containerPhotoSelector')) {
      var item  = elt.up('.item').clone(true);
      item.down('.action').remove();
      item.down('.remove').remove();
      var input = item.down('input[name="product[photos][]"]').enable();
      var url = item.down('a.thumbnail').getStyle('backgroundImage');
      url = url.substr(5, url.length-7);
      var path = url.dirname();
      var file = url.basename().pop();
      var img = 'url(' + path + '/_533_' + file.match(/^_[0-9]*_(.*)/).pop() + ')';
      if (container) {
        if (container.down('#thumbPhotoSelector')) {
          input.name = 'product[rubriques][' + container.id.substr(4) + '][photo]';
          container.down('#thumbPhotoSelector').update(input);
          container.down('#thumbPhotoSelector').setStyle({'backgroundImage':item.down('a.thumbnail').getStyle('backgroundImage')});
        } else {
          item.down('a.thumbnail').setStyle({'backgroundImage':img});
          input.name = 'product[photo]';
          container.down('#containerPhotoSelector').update(item);
        }
        if (container.down('#containerPhotoSelector').up('.viewport') && $('containerPhotoSelector').up('.panel')) {
          emile(container.down('#containerPhotoSelector').up('.viewport'), 'height:' + container.down('#containerPhotoSelector').up('.panel').getDimensions().height + 'px', {duration:250});
        }
      } else {
        item.down('a.thumbnail').setStyle({'backgroundImage':img}).addClassName('noclick').removeAttribute('href');
        input.name = "product[photo]";
        $('containerPhotoSelector').update(item);
        $('containerPhotoSelector').next('div.actions.removePhoto').show();
        if ($('containerPhotoSelector').up('.viewport') && $('containerPhotoSelector').up('.panel')) {
          emile($('containerPhotoSelector').up('.viewport'), 'height:' + $('containerPhotoSelector').up('.panel').getDimensions().height + 'px', {duration:250});
        }
      }
      Kwo.getDialog().close();
      return;
    } else if (container && container.down('#thumbPhotoSelector')) {
      var item  = elt.up('.item').clone(true);
      item.down('.action').remove();
      item.down('.remove').remove();
      var input = item.down('input[name="product[photos][]"]').enable();
      input.name = 'product[rubriques][' + container.id.substr(4) + '][photo]';
      container.down('#thumbPhotoSelector').update(input);
      container.down('#thumbPhotoSelector').setStyle({'backgroundImage':item.down('a.thumbnail').getStyle('backgroundImage')});
      Kwo.getDialog().close();
      return;
    }
    var classname = elt.up('div.item').down('input[type="hidden"]').value;
    if ($('selection-list-photo').select('.' + classname).length > 0) {
      return;
    }
    var item = elt.up('.item').clone(true);
    item.addClassName(classname);
    item.select('div.action').invoke('remove');
    item.down('div.remove').show();
    item.down('input').enable();
    $('selection-list-photo').down('.container').insert({'bottom':item});

    FLW.Photo.countSelection();
    FLW.Photo.resizeSelection();
  },
  'removeFromSelection':function(elt){
    $(elt).up('.item').remove();
    try {
      FLW.Photo.countSelection();
      FLW.Photo.resizeSelection();
    } catch (e) {};
  },
  'countSelection':function(){
    var countSelection = $('selection-list-photo').down('.container').select('.item ').length;
    $('selection-count-photo').update(countSelection);
  },
  'resizeSelection' : function() {
    if ($('selection-list-photo').getDimensions().width <= 260) {
      $('selection-list-photo').scrollTop = $('selection-list-photo').getDimensions().height;
      return;
    }
    var width = 0;
    var height = 0;
    var container = $('selection-list-photo').down('.container');
    var items = container.select('.item');
    items.each(function(elt){
                 var dim = $(elt).getDimensions();
                 height = dim.height > height ? dim.height : height;
                 width += Number($(elt).getDimensions().width)
                              + Number($(elt).getStyle('marginLeft').replace('px', ''))
                              + Number($(elt).getStyle('marginRight').replace('px', ''));
                            });
    height += 10;
    $('selection-list-photo').down('.container').setStyle({'width':width+'px', 'height':height+'px'});
    $('selection-list-photo').scrollLeft = $('selection-list-photo').scrollWidth;
  },
  'setPositions' : function() {
    var containerPhoto = Kwo.getDialog() ? Kwo.getDialog().opts['containerMedia'] : 'photoDrag';
    var container = $(containerPhoto);
    var result = container.next('#photoDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[photos][' + elt.down('.item').readAttribute('key')+ ']', 'value':pos++})});
        });
    }
  },
  'removeRelation' : function (elt, item, callback) {
    var callback = callback || null;
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove.media',
             {'media':$(elt).up('div.dragbox').down('a.item').readAttribute('key'),
              'item':item},
              {'callback':FLW.Photo.removeRelation_callback.curry(elt, callback)});
  },
  'removeRelation_callback' : function (elt, callback) {
    var containerPhoto = Kwo.getDialog() ? Kwo.getDialog().opts['containerMedia'] : 'photoDrag';
    if ($(containerPhoto).up('.viewport') && $(containerPhoto).up('.panel')) {
      emile($(containerPhoto).up('.viewport'), 'height:' + $(containerPhoto).up('.panel').getDimensions().height + 'px', {duration:250});
    }
    $(elt).up('div.dragbox').remove();
    FLW.Photo.setPositions();
    if (callback) callback();
  }
};

FLW.Link = {
  'create' : function(args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.link.create', args, {'width':520, 'height':300, 'containerMedia':'linkDrag', 'name':'linkCreateDialog'});
  },
  'addEntry' : function(elt) {
    var elt = $(elt);
    var entries = elt.up('.viewport').down('.entries');
    var entry = entries.down('.template').clone(true).removeClassName('template').addClassName('entry');
    entry.down('div.remove').show();
    entry.down('input').value='http://';
    entries.insert(entry);
  },
  'removeEntry' : function(elt) {
    var elt = $(elt);
    elt.up('.entry').remove();
  },
  'createEntry' : function(args) {
    Kwo.exec('/account/flw/data.link.add', args, {'callback':FLW.Link.createEntry_callback.curry(args)});
  },
  'createEntry_callback' : function(args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    } else {
      var guide = args.guide ? args.guide.clone(true) : null;
      Kwo.exec('/account/flw/data.link.add.detail',
               {'links_id[]':r['result']['links_id']},
               {'container':'dataCreateLink',
                'callback':function(){ if (guide) { $('dataCreateLink').insert({'top': guide }); }}});
    }
  },
  'edit' : function(args) {
    new Kwo.Dialog('/account/flw/data.link.edit.modal', args, {'callback':FLW.Link.edit_callback});
  },
  'edit_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
  },
  'storeEntry' : function(args) {
    Kwo.exec('/account/flw/data.link.store', args, {'callback':FLW.Link.storeEntry_callback.curry(args)});
  },
  'storeEntry_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['loadItems']) {
      var item = args.guide.clone(true);
      item.name = 'item';
      FLW.Link.getSelections_callback(item, r);
    } else {
      if (Kwo.getDialog()) Kwo.getDialog().close();
    }
  },
  'store' : function(args) {
    Kwo.exec('/account/flw/data.link.edit', args, {'callback':FLW.Link.store_callback.curry(args)});
  },
  'store_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'remove' : function(elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/data.link.remove', args, {'callback':FLW.Link.remove_callback.curry(args)});
  },
  'remove_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go(r['result']['redirect']);
  },
  'getSelections' : function(elt, args) {
    var args = args || $('selection-list-link').down('form');
    if (args.select('.item').length == 0) {
      alert($(elt).readAttribute('data-error-no-selection'));
      return;
    }
    Kwo.exec('/account/flw/catalog.add.media', args, {'callback':FLW.Link.getSelections_callback.curry(args.item)});
  },
  'getSelections_callback' : function(item, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    var items = r['result']['links'];
    var args = new Element('form');
    args.insert(item);
    var pos = 0;
    items.each(function(elt){args.insert(new Element('input', {'type':'hidden', 'name':'product[links]['+elt+']', 'value':pos++}))});
    FLW.Link.loadItems(args);
  },
  'loadItems' : function (args) {
    if ($('linkDrag')) {
      Kwo.exec('/account/flw/data.selection.load.items', args, {'container':$('linkDrag'), 'callback':FLW.Link.loadItems_callback});
      if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
    } else {
      if (Kwo.getDialog()) {
        if (Object.isFunction(Kwo.getDialog().onAfterCommit)) Kwo.getDialog().onAfterCommit();
        Kwo.getDialog().close();
      }
    }
  },
  'loadItems_callback' : function(r) {
    Sortable.create("linkDrag", {"revert":true, "overlap":"horizontal", "scroll":window, "ghosting":false, "constraint":false, "tag":"div", "onChange":FLW.Link.setPositions});
    $('linkDrag').insert({'bottom':new Element('div', {'class':'clear', 'style':'position:static'})});
    FLW.Link.setPositions();
    if($('linkDrag').up('.viewport')) {
      emile($('linkDrag').up('.viewport'), 'height:' + $('linkDrag').up('.panel').getDimensions().height + 'px', {duration:250});
    }
    Kwo.getDialog().close();
  },
  'addToSelection':function(elt) {
    elt = $(elt);
    var classname = elt.up('div.item').down('input[type="hidden"]').value;
    if ($('selection-list-link').select('.' + classname).length > 0) {
      return;
    }
    var item = elt.up('.item').clone(true);
    item.addClassName(classname);
    item.select('div.action').invoke('remove');
    item.down('div.remove').show();
    item.down('input').enable();
    $('selection-list-link').down('.container').insert({'bottom':item});

    FLW.Link.countSelection();
    FLW.Link.resizeSelection();
  },
  'removeFromSelection':function(elt){
    $(elt).up('.item').remove();
    FLW.Link.countSelection();
    FLW.Link.resizeSelection();
  },
  'countSelection':function(){
    var countSelection = $('selection-list-link').down('.container').select('.item ').length;
    $('selection-count-link').update(countSelection);
  },
  'resizeSelection' : function() {
    if ($('selection-list-link').getDimensions().width <= 260) {
      $('selection-list-link').scrollTop = $('selection-list-link').getDimensions().height;
      return;
    }
    var width = 0;
    var height = 0;
    var container = $('selection-list-link').down('.container');
    var items = container.select('.item');
    items.each(function(elt){
                 var dim = $(elt).getDimensions();
                 height = dim.height > height ? dim.height : height;
                 width += Number($(elt).getDimensions().width)
                              + Number($(elt).getStyle('marginLeft').replace('px', ''))
                              + Number($(elt).getStyle('marginRight').replace('px', ''));
                            });
    height += 10;
    $('selection-list-link').down('.container').setStyle({'width':width+'px', 'height':height+'px'});
    $('selection-list-link').scrollLeft = $('selection-list-link').scrollWidth;
  },
  'setPositions' : function() {
    var container = $('linkDrag');
    var result = container.next('#linkDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[links][' + elt.down('.item').readAttribute('key')+ ']', 'value':pos++})});
        });
    }
  },
  'removeRelation' : function (elt, item) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove.media', {'media':$(elt).up('div.dragbox').down('a.item').readAttribute('key'), 'item':item}, {'callback':FLW.Link.removeRelation_callback.curry(elt)});
  },
  'removeRelation_callback' : function (elt) {
    $(elt).up('div.dragbox').remove();
    if ($('linkDrag').up('.viewport')) {
      emile($('linkDrag').up('.viewport'), 'height:' + $('linkDrag').up('.panel').getDimensions().height + 'px', {duration:250});
    }
    FLW.Link.setPositions();
  }
};

FLW.Attachment = {
  'create' : function(args) {
    var args = args || null;
    new Kwo.Dialog('/account/flw/data.attachment.create', args, {'width':500, 'height':400, 'containerMedia':'attachmentDrag', 'name':'attachmentCreateDialog'});
  },
  'add' : function(elt) {
    var form = $('dataCreateAttachment');
    $('dataCreateAttachmentContrainer').down('.throbber').show();
    form.submit();
    form.disable();
  },
  'add_callback' : function(r) {
    var form = $('dataCreateAttachment');
    form.enable();
    $('dataCreateAttachmentContrainer').down('.throbber').hide();
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    $('dataCreateAttachmentContrainer').down('.espace_occupe_attachment').update(r['result']['pcent']);
    form.remove();
    FLW.Attachment.loadItems({'guide':r['result']['guide']});
  },
  'loadItems' : function (args){
    Kwo.exec('/account/flw/data.attachment.load', args, {'container':$('attachmentDrag'), 'callback':FLW.Attachment.loadItems_callback});
  },
  'loadItems_callback': function(r) {
    var containerAttachment = $('attachmentDrag');
    if (containerAttachment.up('.viewport') && containerAttachment.up('.panel')) {
      emile(containerAttachment.up('.viewport'), 'height:' + containerAttachment.up('.panel').getDimensions().height + 'px', {duration:250});
    }
    if (Kwo.getDialog()) Kwo.getDialog().close();
  },
  'remove' : function (elt, args) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.attachment.remove', args,
              {'callback':FLW.Attachment.remove_callback.curry(args)});
  },
  'remove_callback' : function (args, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Attachment.loadItems(args);
  }
};

FLW.Selection = {
  'add':function(elt) {
    elt = $(elt);
    var block = elt.up('.item');
    var classname = block.down('input[type="hidden"]').value;
    if ($('selection-list').select('.' + classname).length > 0) {
      return;
    }
    var item = block.clone(true);
    item.addClassName(classname);
    item.down('.out-cart').remove();
    item.down('.in-cart').show();
//    item.down('.thumbnail').setStyle({'height':45+'px', 'width':45+'px'});
    item.down('input').enable();
    $('selection-list').down('.container').insert({'bottom':item});

    FLW.Selection.count();
    FLW.Selection.resize();
  },
  'remove':function(elt){
    $(elt).up('.item').remove();
    FLW.Selection.count();
    FLW.Selection.resize();
  },
  'count':function(){
    var countSelection = $('selection-list').down('.container').select('.item ').length;
    if (countSelection > 0) $('selection-list').down('p',0).hide();
    else if($('selection-list').down('p')) $('selection-list').down('p',0).show();
    $('selection-count').update(countSelection);
  },
  'resize' : function() {
    if ($('selection-list').getDimensions().width <= 260) {
      $('selection-list').scrollTop = $('selection-list').getDimensions().height;
      return;
    }
    var width = 0;
    var height = 0;
    var container = $('selection-list').down('.container');
    var items = container.select('.item');
    items.each(function(elt){
                 var dim = $(elt).getDimensions();
                 height = dim.height > height ? dim.height : height;
                 width += Number($(elt).getDimensions().width)
                              + Number($(elt).getStyle('marginLeft').replace('px', ''))
                              + Number($(elt).getStyle('marginRight').replace('px', ''));
                            });
    height += 10;
    $('selection-list').down('.container').setStyle({'width':width+'px', 'height':height+'px'});
    $('selection-list').scrollLeft = $('selection-list').scrollWidth;
  },
  'userCatalogue': function (user) {
    $('selection').down('#user_catalogue').value = user;
    FLW.Selection.country(0);
    FLW.Selection.region(0);
    if ($('selection').mode.value != 'article') {
      FLW.Selection.model(0);
    }
    FLW.Selection.category(0);
    FLW.Selection.subcategory(0);
    FLW.Selection.offset(0);
  },
  'offset': function (offset) {
    $('selection').down('#offset').value = offset;
    FLW.Selection.submit();
  },
  'view': function (view) {
    $('selection').down('#view').value = view;
    FLW.Selection.offset(0);
  },
  'query': function () {
    FLW.Selection.model(0);
    FLW.Selection.category(0);
    FLW.Selection.subcategory(0);
    FLW.Selection.offset(0);
  },
  'country': function (value) {
    $('selection').down('#country').value = value;
    FLW.Selection.region(0);
    FLW.Selection.model(0);
    FLW.Selection.category(0);
    FLW.Selection.subcategory(0);
    if (value === '' || Number(value) > 0) {
      FLW.Selection.offset(0);
    }
  },
  'region': function (value) {
    $('selection').down('#region').value = value;
    FLW.Selection.model(0);
    FLW.Selection.category(0);
    FLW.Selection.subcategory(0);
    if (value === '' || Number(value) > 0) {
      FLW.Selection.offset(0);
    }
  },
  'model': function (value) {
    $('selection').down('#model').value = value;
    FLW.Selection.category(0);
    FLW.Selection.subcategory(0);
    if (value === '' || Number(value) > 0) {
      FLW.Selection.offset(0);
    }
  },
  'category': function (value) {
    $('selection').down('#category').value = value;
    FLW.Selection.subcategory(0);
    if (value === '' || Number(value) > 0) {
      FLW.Selection.offset(0);
    }
  },
  'subcategory': function (value) {
    $('selection').down('#subcategory').value = value;
    if (value === '' || Number(value) > 0) {
      FLW.Selection.offset(0);
    }
  },
  'submit': function () {
    var container = $('selection').up('.container-selection');
    Kwo.exec('/flw/selection', $('selection'), {'container':container});//, 'callback':FLW.Selection.submit_callback
  }
};

FLW.Wizard = {
  'maxStep' : 0,
  'addSelection' : function () {
    $('et2-result').innerHTML = '';
    var items = $('selection-list').select('input');
    if (items.length >= 2) {
      var pos = 0;
      $('et2-result').insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[steps][new_entry]', 'value':1})});
      items.each(function(elt){
          $('et2-result').insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[steps][' + elt.value+ '][position]', 'value':pos++})});
        });
        return true;
    } else {
      alert("Vous devez d'abord saisir les informations obligatoires pour pouvoir continuer");
    }
    return false;
  },
  'addSelectionSummary' : function(){
    var args = new Element('form');
    var items = $('et2-result').select('input[type="hidden"]');
    items.each(function(elt){args.insert({'bottom':elt.clone(true)})});
    Kwo.exec('/account/flw/data.create.items.summary', args, {'container':$('et4').down('.items')});
  },
  'removeSelection':function(elt){
    $(elt).up('.dragbox').remove();
    FLW.Wizard.setPositions(null);
  },
  'save' : function(args, opts) {
    var opts = opts || {};
    var args = $(args);
    if (opts.publish == true && Object.isFunction (window['verifForm'][(FLW.Wizard.maxStep-1)])) {
      if (!window['verifForm'][(FLW.Wizard.maxStep-1)]()) return false;
    }
    if (args.tagName.toUpperCase() != 'FORM') args = args.up('form');
    if (args.down('input[name="item"]') && args.down('input[name="item"]').value.length > 0) {
      Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Wizard.save_callback});
    } else {
      Kwo.exec('/account/flw/catalog.add?'+($H(opts).toQueryString()), args, {'callback':FLW.Wizard.save_callback});
    }
  },
  'save_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    var href;
    if ($($('wizard').guide)) {
      href = "/account/flw/grouping/-/id/" + $F($('wizard').guide).split('-')[1] ;
    } else {
      href = "/account/flw/user";
    }
    Kwo.go(href);
//    Kwo.go('/account/flw/user/?tab=catalog');
  },
  'cancel' : function () {
    if (!confirm("Êtes-vous sûr de vouloir annuler la création de cette fiche ?")) return;
    var href;
    if ($($('wizard').guide)) {
      href = "/account/flw/grouping/-/id/" + $F($('wizard').guide).split('-')[1] ;
    } else {
      href = "/account/flw/user";
    }
    location.href = href;
  },
  'goEtape' : function(num, callback) {
    if (num > parseInt($('etape-count').innerHTML)) return false;
    if (Object.isFunction (window['verifForm'][(num-2)])) {
      if (!window['verifForm'][(num-2)]()) return false;
    }
    var callback = callback || null;
    FLW.Wizard.add($('wizard'), {'callback':callback});

    $('etape-num').innerHTML = num;
    if ($('et' + (num-1))) $('et' + (num-1)).hide();
    if ($('et' + num))     $('et' + num).show();
  },
  'loadItems' : function() {
    if ($('et2-result').down('input[name="product[steps][new_entry]"]')) $('et2-result').down('input[name="product[steps][new_entry]"]').remove();
    Kwo.exec('/account/flw/data.create.items.drag', $('et2-result').select('input[type="hidden"]'), {'container':$('et3').down('.items-drag')});
  },
  'setPositions' : function(elt) {
    $('et2-result').update('');
    var items = $$('#itemSelectionDrag .dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          $('et2-result').insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[steps][' + elt.down('.item').readAttribute('key')+ '][position]', 'value':pos++})});
        });
    }
  },
  'showMediaSelector' : function(media, args) {
    args = args || {};
    args.showContainer = true;
    new Kwo.Dialog('/account/flw/data.selection.' + media + 's', args, {width:780, height:360, 'containerMedia': media + 'Drag', 'name':'wizMediaSelectorDialog'});
  },
  'addPhotosFromGalerie' : function (container, args) {
    Kwo.exec('/account/flw/data.selection.photos', args, {'container':container});
  },
  'addPhotoFromGalerie' : function (container, args) {
    Kwo.exec('/account/flw/data.selection.photo', args, {'container':container});
  },
  'addVideosFromGalerie' : function (container, args) {
    Kwo.exec('/account/flw/data.selection.videos', args, {'container':container});
  },
  'addLinksFromGalerie' : function (container, args) {
    Kwo.exec('/account/flw/data.selection.links', args, {'container':container});
  },
  'loadUserCoordonnee' : function () {
    Kwo.exec('/account/flw/data.user.coordonnee', null, {'callback':FLW.Wizard.loadUserCoordonnee_callback});
  },
  'loadUserCoordonnee_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    var coordonnee = $$('form#wizard ul#coordonnee')[0];
    coordonnee.down('input[name="product[com_name]"]').value = r['result']['name'];
    coordonnee.down('input[name="product[com_phone_1]"]').value = r['result']['phone1'];
    coordonnee.down('input[name="product[com_phone_2]"]').value = r['result']['phone2'];
    coordonnee.down('input[name="product[com_email]"]').value = r['result']['email'];
    coordonnee.down('input[name="product[com_web_site]"]').value = r['result']['site'];
  },
  'add' : function(args, opts) {
    Kwo.exec('/account/flw/catalog.add?presave=true', args, {'callback':FLW.Wizard.add_callback.curry(opts)});
  },
  'add_callback' : function(opts, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    $('item_key').value = r['result']['item'];
    if (opts && Object.isFunction (opts.callback)) opts.callback();
  }
};

FLW.Package = {
  'reloadSteps' : function(guide){
    if ($('containerSteps')) {
      Kwo.exec('/account/flw/catalog.steps',
        {'item':guide},
        {'container':'containerSteps',
         'callback':function() {
             var viewport = $('containerSteps').up('.viewport');
             var current = viewport.down('.panel').getDimensions().height+'px';
             emile(viewport,'height:'+current,{'duration':250});
             FLW.Package.setPositions();
           }
        });
    }
  },
  'save' : function(elt) {
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', elt, {'callback':FLW.Package.save_callback});
  },
  'save_callback' : function(r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'addSteps' : function(args) {
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'packageSelectorStepsDialog'});
  },
  'createSteps' : function(elt, item_key, mode) {
    var args = $('selection-list').down('form');
    if (args.select('input[type="hidden"]').length < 1) {
      alert($(elt).readAttribute('data-error-no-selection'));
      return;
    }
    args.insert(new Element('input', {'type':'hidden', 'name':'item', 'value':item_key}));
    args.insert(new Element('input', {'type':'hidden', 'name':'mode', 'value':mode}));
    Kwo.exec('/account/flw/catalog.add.steps', args, {'callback':FLW.Package.createSteps_callback.curry(item_key)});
  },
  'createSteps_callback' : function(guide, r){
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Object.isFunction(Kwo.getDialog().onAfterCommit)) {
      Kwo.getDialog().onAfterCommit();
    } else {
      FLW.Package.reloadSteps(guide);
    }
    Kwo.getDialog().close();
  },
  'setPositions' : function() {
    var container = $('stepSelectionDrag');
    var result = container.next('#stepSelectionDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          $('selectionListPanel').down('.item[key="'+elt.down('.item').readAttribute('key')+'"] .info .pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[steps][' + elt.down('.item').readAttribute('key')+ '][position]', 'value':pos++})});
        });
      var container_arranges = $('selectionListPanel').down('.list').clone(true);
      $('selectionListPanel').down('.list').update('');
      result.select('input[name*="product[steps]"]').each(function(elt) {
          var item_key = elt.readAttribute('name').split('][')[1];
          $('selectionListPanel').down('.list').insert({'bottom':container_arranges.down('.item[key="'+item_key+'"]')});
        });
    }
  },
  'removeStep' : function(elt, guide) {
    if (!confirm('Êtes-vous sûr de vouloir retirer cette étape ?')) return;
    if ($(elt).up('.item')) {
      var item = $(elt).up('.item').readAttribute('key');
    } else if ($(elt).up('.dragbox')) {
      var item = $(elt).up('.dragbox').down('.item').readAttribute('key');
    } else return;
    $('selectionListPanel').down('.item[key="'+item+'"]').remove();
    $('selectionDragPanel').down('.item[key="'+item+'"]').up('.dragbox').remove();
    FLW.Package.setPositions();
    Kwo.exec('/account/flw/catalog.remove.step', {'item':guide, 'step':item}, {'callback':FLW.Package.removeStep_callback.curry(guide)});
  },
  'removeStep_callback' : function(guide, r){
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Package.reloadSteps(guide);
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Package.save($('formPackageEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Package.save($('formPackageEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Package.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Trail = {
  'reloadSteps' : function(guide){
    Kwo.exec('/account/flw/catalog.steps',
      {'item':guide},
      {'container':'containerSteps',
       'callback':function() {
           var viewport = $('containerSteps').up('.viewport');
           var current = viewport.down('.panel').getDimensions().height+'px';
           emile(viewport,'height:'+current,{'duration':250});
         }
      });
  },
  'save' : function(elt) {
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', elt, {'callback':FLW.Trail.save_callback});
  },
  'save_callback' : function(r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'addSteps' : function(args) {
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'trailSelectorStepsDialog'});
  },
  'createSteps' : function(item_key) {
    var args = $('selection-list').down('form');
    if (args.select('input[type="hidden"]').length < 1) return;
    args.insert(new Element('input', {'type':'hidden', 'name':'item', 'value':item_key}));
    Kwo.exec('/account/flw/catalog.add.steps', args, {'callback':FLW.Trail.createSteps_callback.curry(item_key)});
  },
  'createSteps_callback' : function(guide, r){
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Trail.reloadSteps(guide);
    Kwo.getDialog().close();
  },
  'setPositions' : function() {
    var container = $('stepSelectionDrag');
    var result = container.next('#stepSelectionDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          $('selectionListPanel').down('.item[key="'+elt.down('.item').readAttribute('key')+'"] .info .pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[steps][' + elt.down('.item').readAttribute('key')+ '][position]', 'value':pos++})});
        });
      var container_arranges = $('selectionListPanel').down('.list').clone(true);
      $('selectionListPanel').down('.list').update('');
      result.select('input[name*="product[steps]"]').each(function(elt) {
          var item_key = elt.readAttribute('name').split('][')[1];
          $('selectionListPanel').down('.list').insert({'bottom':container_arranges.down('.item[key="'+item_key+'"]')});
        });
    }
  },
  'removeStep' : function(elt, guide) {
    if (!confirm('Êtes-vous sûr de vouloir retirer cette étape ?')) return;
    var item = $(elt).up('.item').readAttribute('key');
    $('selectionListPanel').down('.item[key="'+item+'"]').remove();
    $('selectionDragPanel').down('.item[key="'+item+'"]').up('.dragbox').remove();
    FLW.Trail.setPositions();
    Kwo.exec('/account/flw/catalog.remove.step', {'item':guide, 'step':item}, {'callback':FLW.Trail.removeStep_callback.curry(guide)});
  },
  'removeStep_callback' : function(guide, r){
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Trail.reloadSteps(guide);
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Trail.save($('formTrailEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Trail.save($('formTrailEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Trail.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Event = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Event.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                       args['product[city]'].value + " " +
                                       args['product[zip_code]'].value + " " +
                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                       args['product[zip_code]'].value + " " +
                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Event.save($('formEventEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Event.save($('formEventEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Event.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Accommodation = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Accommodation.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                                 args['product[city]'].value + " " +
                                                 args['product[zip_code]'].value + " " +
                                                 args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                                       args['product[zip_code]'].value + " " +
                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Accommodation.save($('formAccommodationEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Accommodation.save($('formAccommodationEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Accommodation.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  },
  'setModel' : function(elt) {
    elt = $(elt);
    var model_id = category_model[$F(elt)]["id"];
    var model_name = category_model[$F(elt)]["name"];
    $('wizard').down('#model_id').value = model_id;
    $('wizard').down('#model_name').value = model_name;
    $('etape-count').update(FLW.Accommodation.maxSteps[model_name]);
    FLW.Wizard.maxStep = FLW.Accommodation.maxSteps[model_name];
  },
  'setModelForm' : function() {
    var model_name = $F($('wizard').down('#model_name'));
    $('wizard').select('div[id^="formModel"][id!="formModel' + model_name.ucfirst() + '"]').invoke('remove');
    $('formModel' + model_name.ucfirst()).show();
  }
};

FLW.Rental = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Rental.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                                 args['product[city]'].value + " " +
                                                 args['product[zip_code]'].value + " " +
                                                 args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                                       args['product[zip_code]'].value + " " +
                                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Rental.save($('formRentalEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Rental.save($('formRentalEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Rental.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Activity = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Activity.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                                 args['product[city]'].value + " " +
                                                 args['product[zip_code]'].value + " " +
                                                 args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                                       args['product[zip_code]'].value + " " +
                                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Activity.save($('formActivityEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Activity.save($('formActivityEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Activity.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Place = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM') {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Place.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                                 args['product[city]'].value + " " +
                                                 args['product[zip_code]'].value + " " +
                                                 args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                                       args['product[zip_code]'].value + " " +
                                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Place.save($('formPlaceEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Place.save($('formPlaceEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Place.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  },
  'setModel' : function(elt) {
    elt = $(elt);
    var model_id = category_model[$F(elt)]["id"];
    var model_name = category_model[$F(elt)]["name"];
    $('wizard').down('#model_id').value = model_id;
    $('wizard').down('#model_name').value = model_name;
    $('etape-count').update(FLW.Place.maxSteps[model_name]);
    if ($('formPartCommercial')) {
      if (model_name == 'place') {
        $('formPartCommercial').show();
        $('formPartCommercial').select('input[type="radio"]').invoke('enable');
        $('formPartCommercial').select('input[type="hidden"]').invoke('disable');
      } else {
        $('formPartCommercial').hide();
        $('formPartCommercial').select('input[type="radio"]').invoke('disable');
        $('formPartCommercial').select('input[type="hidden"]').invoke('enable');
      }
    }
  },
  'setModelForm' : function() {
    var model_name = $F($('wizard').down('#model_name'));
    $('wizard').select('div[id^="formModel"][id!="formModel' + model_name.ucfirst() + '"]').invoke('remove');
    $('formModel' + model_name.ucfirst()).show();
    if (model_name == 'suggestion') {
      $('formPartCommercial').select('input[type="hidden"]').invoke('remove');
    }
  }
};

FLW.Suggestion = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Suggestion.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                                 args['product[city]'].value + " " +
                                                 args['product[zip_code]'].value + " " +
                                                 args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                                       args['product[zip_code]'].value + " " +
                                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Suggestion.save($('formSuggestionEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Suggestion.save($('formSuggestionEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Suggestion.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Restaurant = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Restaurant.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    if (Number(args['product[latitude]'].value) == 0 && Number(args['product[longitude]'].value) == 0) {
      FLW.Map.geoLocPickerData.args = {"lat":args['product[latitude]'].value,
                                       "lng":args['product[longitude]'].value,
                                       "zoom":args['product[zoom]'].value,
                                       "address":args['product[address]'].value + " " +
                                                 args['product[city]'].value + " " +
                                                 args['product[zip_code]'].value + " " +
                                                 args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML,
                                       "simpleaddress":args['product[city]'].value + " " +
                                                       args['product[zip_code]'].value + " " +
                                                       args['product[country_id]'][args['product[country_id]'].selectedIndex].innerHTML
                                      };
      FLW.Map.geoLocPickerData.opts = {"lat":"product[latitude]",
                                       "lng":"product[longitude]",
                                       "zoom":"product[zoom]"
                                      };
      FLW.UI.toggleBox($('carteGeoPicker').down('.box .title a.deploy'), {callback_deploy:FLW.Map.initGeoLocPicker});
    } else {
      location.reload();
    }
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Restaurant.save($('formRestaurantEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Restaurant.save($('formRestaurantEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Restaurant.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.Article = {
  'save' : function(elt) {
    if (elt.tagName.toUpperCase() == 'FORM' ) {
      args = elt;
    } else {
      args = elt.up('form');
    }
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/catalog.store', args, {'callback':FLW.Article.save_callback.curry(args)});
  },
  'save_callback' : function(args, r) {
    FLW.Validation.setValidate(r['result']['validations']);
    FLW.Validation.hasPublish(r['result']['published']);
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'publish' : function() {
    FLW.UI.AddPublisher(1);
    FLW.Article.save($('formArticleEdit'));
  },
  'unpublish' : function() {
    FLW.UI.AddPublisher(0);
    FLW.Article.save($('formArticleEdit'));
  },
  'remove' : function(elt) {
    if (!confirm($(elt).readAttribute('data-confirm'))) return;
    Kwo.exec('/account/flw/catalog.remove',{'item':$F('item_key')}, {'callback':FLW.Article.remove_callback});
  },
  'remove_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    Kwo.go('/account/flw/user/?tab=catalog');
  }
};

FLW.User = {
  'save' : function(elt) {
    FLW.Validation.uniqTag(elt);
    Kwo.exec('/account/flw/user.store', elt, {'callback':FLW.User.save_callback});
  },
  'save_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Validation.setValidate(r['result']['validations']);
    location.reload();
  },
  'addSteps' : function(args) {
    if ($('map')) $('map').id = 'map-suspend';
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'UserSelectorStepsDialog'}).onAfterClose = FLW.User.onAfterClose;
  },
  'showMediaCreator' : function(media, guide) {
    new Kwo.Dialog('/account/flw/data.' + media + '.create', {'mode':'user', 'item':guide}, {'width':500, 'height':(media == 'photo' ? 400 : 300), 'containerMedia': media + 'Drag', 'name': media + 'CreateDialog'}).onAfterClose = FLW.User.onAfterCommit;
  },
  'onAfterCommit' : function () {
    location.reload();
  },
  'onAfterClose' : function () {
    if ($('map-suspend')) $('map-suspend').id = 'map';
    location.reload();
  },
  'setAcl' : function (elt, args) {
    var elt = $(elt);
    if (elt.readAttribute('data-confirm') && elt.readAttribute('data-confirm').length > 0) {
      if (!confirm(elt.readAttribute('data-confirm'))) return;
    }
    Kwo.exec('/account/flw/data.acl.set', args, {'callback':FLW.User.setAcl_callback});
  },
  'setAcl_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Search.reload();
  }
};

FLW.Rubrique = {
  'save' : function(elt) {
    Kwo.exec('/account/flw/data.catalog.store', elt, {'callback':FLW.Rubrique.save_callback});
  },
  'save_callback' : function(r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
  },
  'remove' : function(elt) {
    elt = $(elt);
    if (!confirm(elt.readAttribute('data-confirm'))) return;
    var key = (elt.up('.dragbox') ? elt.up('.dragbox').down ('.item') : elt.up('.item')).readAttribute('key');
    Kwo.exec('/account/flw/data.rubrique.remove', {'item':key}, {'callback':FLW.Rubrique.remove_callback.curry(elt)});
  },
  'remove_callback' : function(elt, r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    var key = (elt.up('.dragbox') ? elt.up('.dragbox').down ('.item') : elt.up('.item')).readAttribute('key');
    $('selectionListPanel').down('div.item[key="'+key+'"]').remove();
    $('rubriqueSelectionDrag').down('a.item[key="'+key+'"]').up('div.dragbox').remove();
    if (elt.up())
    FLW.Rubrique.setPositions();
  },
  'create' : function (args) {
    new Kwo.Dialog('/account/flw/data.rubrique.create', args, {'width':570, 'height':320, 'name':'rubriqueCreateDialog'});
  },
  'add' : function (args) {
    Kwo.exec('/account/flw/data.rubrique.add',args,{'callback':FLW.Rubrique.add_callback});
  },
  'add_callback' : function (r) {
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    FLW.Rubrique.addSteps({'item':r['result']['item'], 'mode':r['result']['mode']});
  },
  'cancel' : function () {
    Kwo.getDialog('rubriqueCreateDialog').close();
  },
  'addSteps' : function(args) {
    if ($('map')) $('map').id = 'map-suspend';
    var isCreateStep = false;
    if (Kwo.getDialog("rubriqueCreateDialog")) {
      Kwo.getDialog("rubriqueCreateDialog").close();
      isCreateStep = true;
    }
    new Kwo.Dialog('/account/flw/catalogue.selection', args, {width:800, height:550, 'name':'rubriqueSelectorStepsDialog'}).onAfterClose = FLW.Rubrique.onCloseDialog;
    Kwo.getDialog('rubriqueSelectorStepsDialog').onAfterCommit = FLW.Rubrique.onAfterCommit.curry(isCreateStep);
  },
  'removeStep' : function(elt, guide) {
    if (!confirm('Êtes-vous sûr de vouloir retirer ce contenu ?')) return;
    elt = $(elt);
    var item = elt.up('.item').readAttribute('key');
    Kwo.exec('/account/flw/catalog.remove.step', {'item':guide, 'step':item}, {'callback':FLW.Rubrique.removeStep_callback.curry(elt, guide)});
  },
  'removeStep_callback' : function(elt, guide, r){
    if (r['error'] == 1) {
      alert(r['result']['msg']);
      return;
    }
    if (r['result']['msg'] && r['result']['msg'].length > 0) alert(r['result']['msg']);
    location.reload();
    /*
    item = elt.up('.item');
    $(item.readAttribute('key')).remove();
    item.remove();
    */
  },
  'onAfterCommit' : function (isCreateStep) {
    if (isCreateStep) {
      alert('Rubrique créée et publiée avec succès');
    }
    location.reload();
  },
  'onCloseDialog' : function () {
    //if ($('map-suspend')) $('map-suspend').id = 'map';
    //if (Kwo.getDialog("rubriqueCreateDialog")) Kwo.getDialog("rubriqueCreateDialog").close();
    location.reload();
  },
  'addPhoto' : function (opts) {
    opts = opts || {};
    var container = opts.container || null;
    args = {};
    args.showContainer = true;
    args.mode = 'rubrique';
    new Kwo.Dialog('/account/flw/data.selection.photo', args, {width:780, height:200, 'name':'rubriquePhotoSelectorDialog', 'container':container});
  },
  'createPhoto' : function(opts) {
    opts = opts || {};
    var container = opts.container || null;
    var args = {};
    args.mode = 'rubrique';
    new Kwo.Dialog('/account/flw/data.photo.create', args, {'width':500, 'height':400, 'name':'rubriquePhotoCreateDialog', 'container':container});
  },
  'setPositions' : function() {
    var container = $('rubriqueSelectionDrag');
    var result = container.next('#rubriqueSelectionDragResult');
    result.update('');
    var items = container.select('.dragbox');
    if (items.length > 0) {
      var pos = 0;
      items.each(function(elt){
          elt.down('.pos').update(pos+1);
          $('selectionListPanel').down('.item[key="'+elt.down('.item').readAttribute('key')+'"] .info .pos').update(pos+1);
          result.insert({'bottom':new Element('input', {'type':'hidden', 'name':'product[rubriques][' + elt.down('.item').readAttribute('key')+ '][position]', 'value':pos++})});
        });
      var container_arranges = $('selectionListPanel').down('.list').clone(true);
      $('selectionListPanel').down('.list').update('');
      result.select('input[name*="product[rubriques]"]').each(function(elt) {
          var item_key = elt.readAttribute('name').split('][')[1];
          $('selectionListPanel').down('.list').insert({'bottom':container_arranges.down('.item[key="'+item_key+'"]')});
        });
    }
  }
}

// Misc

String.prototype.urlify = function () {
  return this.replace(/[^\w\s\.\-]/g, '')
             .replace(/^\s+|\s+$/g, '')
             .replace(/[-\s]+/g, '-')
             .toLowerCase();
}

String.prototype.ucfirst = function () {
 return this.toLowerCase().replace(/\b([a-z])/gi,function(c){return c.toUpperCase()});
};

document.observe("dom:loaded", function() {
  $$('input[type="text"][data-limit], textarea[data-limit]').each(function(elt) {
      elt.observe('keypress', function(e){
        var elt = e.findElement();
        var limit = Number(elt.readAttribute('data-limit'));
        if (limit <= 0) return;
        if ($F(elt).length >= limit) {
          elt.value = $F(elt).substr(0, limit - 1);
          e.stop();
          return false;
        }
      });
      elt.observe('keyup', function(e){
        var elt = e.findElement();
        var limit = Number(elt.readAttribute('data-limit'));
        if (limit <= 0) return;
        elt.value = $F(elt).substr(0, limit - 1);
        e.stop();
        return false;
      });
   });
});

