if (!Kwo) var Kwo = {};

if (swfobject) {
  swfobject.registerObject("visiochat", "9.0.0", "/app/epsycho/swf/expressInstall.swf");
  swfobject.registerObject("video", "9.0.0", "/app/epsycho/swf/expressInstall.swf");
}

Epsycho = {
  'method': "show",
  'changeTextSize': function (size) {
    if ($('epsycho-focus')) {
      $('epsycho-focus').select('div.epsycho-focus-content').each(function(elm) {
        elm.removeClassName('text-simple');
        elm.removeClassName('text-half');
        elm.removeClassName('text-double');
        elm.addClassName('text-' + size);
      });
    } else {
      $('epsycho-fragment').removeClassName('text-simple');
      $('epsycho-fragment').removeClassName('text-half');
      $('epsycho-fragment').removeClassName('text-double');
      $('epsycho-fragment').addClassName('text-' + size);
    }
  },
  'checkBoxes': function () {
    if ($('ctrler').checked == true) {
      $('cats').select('input').each(function (elm) {
        elm.checked = true;
      });
    } else {
      $('cats').select('input').each(function (elm) {
        elm.checked = false;
      });
    }
  },
  'checkProfileSubmit': function () {
    if ($('input-adeli') && $('input-bg')) {
      if ($F('input-adeli') != "" && $F('input-bg') != "") {
        Epsycho.onProfileSubmit($('profile-form'));
      } else {
        return Kwo.warn('Vous devez remplir les champs obligatoires.');
      }
    } else {
      Epsycho.onProfileSubmit($('profile-form'));
    }
  },
  'checkSend': function () {
    if ($F('msg') == "") {
      Kwo.warn('Vous devez écrire un message à transmettre à vos amis.');
      $('msg').activate();
    } else if ($F('deliver') == "") {
      Kwo.warn('Vous devez spécifier au moins une adresse mail.');
      $('deliver').activate();
    } else {
      Kwo.exec('/epsycho/dossier.deliver/', {'identity':$F('you'), 'msg':$F('msg'), 'deliver':$F('deliver'), 'folder':$F('folder')}, {'callback': function (res) {
        if (Kwo.hasError(res)) {
          Kwo.warn('Une erreur est survenue dans l\'envoi de votre message.');
        } else if (res.result.failed) {
          Kwo.warn('L\'envoi vers certains de vos destinataires a échoué:\n'+res.result.failed);
        } else {
          Kwo.warn('Votre message a bien été transmis à vos amis.');
        }
      }});
    }
  },  

  'checkSignUp': function () {
    if ($F('input-last-name') != "" && $F('input-first-name') != "" &&
        $F('input-email') != "" && $F('input-password') != "" &&
        $F($('signup-panel').select('input.birthdate_input').first()) != "" &&
        ($('input-gender-0').checked == true || $('input-gender-1').checked == true) &&
        ($('input-type-0').checked == true || $('input-type-1').checked == true)) {
           var today = new Date();
            if ((today.getFullYear() - $F($('signup-panel').select('input.birthdate_input').first()).substring(0, 4)) >= 18) {
              Kwo.Auth.onSignUp($('signup-form'));
            } else {
              return Kwo.warn('Vous devez être majeur afin de vous inscrire sur ePsychologie.');
            } 
        } else {
      return Kwo.warn('Vous devez remplir les champs obligatoires.');
    }
  },
   
  'contact': function () {
    var send = true;
    var consult_id = ($('consult_id')) ? $F('consult_id') : 0;
    var params = new Hash({'first_name':$F('input-first-name'), 'last_name':$F('input-last-name'), 'type':$F('input-type'), 'email':$F('input-email'),
                             'object':$F('object'), 'desc':$F('input-desc'), 'consult_id':consult_id});
    params.each(function (pair) {
      if (pair.value === "") {
        send = false;
        return Kwo.warn('Le message ne peut être envoyé si tous les champs ne sont pas remplis');
      }
    });
    if (send) {
      Kwo.exec('/epsycho/contact.send', params, {'callback': function (res) {
        if (Kwo.hasError(res)) {
          Kwo.warn('Une erreur est survenue dans l\'envoi de votre message.');
        } else {
          Kwo.warn('Votre message a bien été transmis à l\'administrateur');
          Kwo.home();
        }
      }});
    }
  },
  'onProfileSubmit': function (args) {
    Kwo.exec('user.save', args, {'callback': function () {
      Kwo.warn('Vos informations ont bien été enregistrées.');
    }});
  },
  onPasswordSubmit: function(args) {
    Kwo.exec("/account/community/password.save", args, {callback:true, disable:true, reset:true});
  },
  'onSignIn': function(args) {
    Kwo.exec('/community/user.signin', args, {callback: Epsycho.onSigninCallback, disable: true});
  },
  'onSigninCallback': function (res) {
    if (Kwo.hasError(res)) {
      Kwo.warn('Identifiant ou mot de passe incorrect.');
    } else {
      Kwo.reload();
    }
  },
/*
  'placeAvatar': function () {
    $('account-box').select('img.img-pro').each(function(elm) {
      var mw = parseInt(($('avatar-border').getWidth() - elm.getWidth()) / 2);
      var mh = parseInt(($('avatar-border').getHeight() - elm.getHeight()) / 2);
      elm.setStyle({ margin: mh + 'px ' + mw + 'px'});
    });
    window.clearTimeout(Epsycho.prepareTimer);
  },
  'prepareTimer': null,
  'prepareAvatar': function () {
    window.clearTimeout(Epsycho.prepareTimer);
    for (var i = 0; i < document.images.length; i++) {
      if (document.images[i].hasClassName("img-pro")) {
        if (document.images[i].getWidth() > 0) {
          Epsycho.placeAvatar();
          break;
        } else {
          Epsycho.prepareTimer = window.setTimeout("Epsycho.prepareAvatar()", 500);
          break;
        }
      }
    }
  },
*/
  'refreshPsychologue': function (cp, method) {
    if (!isNaN(cp) && parseInt(cp) == cp) {
      Kwo.exec('/epsycho/psychologue.list', {'cp':cp, 'method':method}, {'container':'psy-list'});
    } else {
      return Kwo.warn('Le code postal n\'est pas valide.');
    }
  },
  'roll': function () {
    if ($('trombi-content').getStyle('display') == 'none') {
      Effect.SlideDown('trombi-content');
    } else {
      Effect.SlideUp('trombi-content');
    }
  },
  'search': function (offset) {
    if ($F('field') == "") {
      Kwo.warn('Le champs de recherche est vide.');
      $('field').activate();
    } else if ($F('field').length < 3) {
      Kwo.warn('La requête de recherche est trop courte. Entrez au moins 3 lettres.');
      $('field').activate();
    } else {
      Kwo.go('/epsycho/search', {'query':$F('field'), 'offset':offset});
    }
  },
  'showCalendar': function (request, logger) {
    Kwo.exec('/epsycho/calendar', {'request[]':request}, {'container':'calendar-box'});
/*
    if (Epsycho.method == "show") {
      if (logger == false) {
        Kwo.warn('Seuls les utilisateurs connectés peuvent prendre des rendez-vous.');
      } else {
        if ($('date-img')) {
          $('date-img').src = '/app/epsycho/pix/psycho_rdv_fade.png';
        }
        $('epsycho-folder').hide();
        if ($('dossier-container')) {
          $('dossier-container').hide();
        }
        if ($('categories')) {
          $('categories').hide();
        }
        $('calendar-box').show();
        Kwo.exec('/epsycho/calendar', {'request[]':request}, {'container':'calendar-box'});
//        Epsycho.method = "hide";
        
      }
    } else {

      if ($('date-img')) {
        $('date-img').src = '/app/epsycho/pix/psycho_rdv.png';
      }
      $('epsycho-folder').show();
      if ($('dossier-container')) {
        $('dossier-container').show();
      }
      if ($('categories')) {
        $('categories').show();
      }
      $('calendar-box').hide();
      Epsycho.method = "show";
    }
*/
  },
  'stopConsult': function (loc, txt) {
    $('visio-box').innerHTML = '<div class="closed">'+txt+'</div>';
    window.setTimeout("Kwo.go('/account/epsycho/consultations');", 2000);
  }
};

Epsycho.Pager = {
  'offset': null,
  'count': null,
  'down': function () {
    Epsycho.Pager.offset -= 1;
    Epsycho.Pager.change(Epsycho.Pager.offset);
  },
  'up': function () {
    Epsycho.Pager.offset += 1;
    Epsycho.Pager.change(Epsycho.Pager.offset);
  },
  'start': function (starter, counter) {
    Epsycho.Pager.offset = starter;
    Epsycho.Pager.count = counter;
    Epsycho.Pager.change(starter);
  },
  'change': function (starter) {
    $('phantom').childElements().each(function (elm) {
      elm.hide();
    });
    if (starter > 0) {
      $('pager-down').show();
    }
    if (starter + 2 < Epsycho.Pager.count) {
      $('pager-up').show();
    }
    $('pager-'+starter).show();
    $('pager-'+(starter+1)).show();
    $('pager-'+(starter+2)).show();
  }
};

Epsycho.Publication = {
  'add': function () {
    $('add-link').hide();
    $('next-publication').show();
    Kwo.exec('publication.new', null, {'container': 'next-publication'});
  },
  'callback': function (res) {
    if (Kwo.hasError(res)) {
      Kwo.warn(res);
    }
    else {
      Epsycho.Publication.list();
      Kwo.warn('Publication correctement enregistrée.');
      $('add-link').show();
      $('next-publication').hide();
    }
  },
  'edit': function (id) {
    $('add-link').hide();
    $('next-publication').show();
    Kwo.exec('publication.new', {'id': id}, {'container': 'next-publication'});
  },
  'list': function () {
    Kwo.exec('publication.list', null, {'container': 'publication-list'});
  },
  'remove': function (id) {
    Kwo.exec('publication.remove', {'publication_id': id}, {'callback': function (res) {
      if (Kwo.hasError(res)) {
        Kwo.warn(res);
      } else {
        Epsycho.Publication.list();
        Kwo.warn("Publication supprimée avec succès.");
      }
    }});
  },
  'submit': function (args) {
    Kwo.exec('publication.save', args, {disable:true, callback: Epsycho.Publication.callback});
  }
};

Epsycho.Reservation = {
  refresher: null,
  'alertRemaining': function() {
    time = $('join-link').innerHTML.stripTags().substring(18);
    Kwo.warn('La consultation n\'a pas démarré, merci de patienter '+time+'.');
  },
  'allocate': function (td, day, month, year, hour) {
    Kwo.exec('/account/epsycho/reservation.allocate', {'day':day, 'month':month, 'year':year, 'hour':hour}, {'callback': function (res) {
      if (res.result == "add") {
        $(hour+'_'+day+'_'+month).addClassName('allocated');
        $(hour+'_'+day+'_'+month).innerHTML = "DISPO";
      } else if (res.result == "remove") {
        $(hour+'_'+day+'_'+month).removeClassName('allocated');
        $(hour+'_'+day+'_'+month).innerHTML = "";
      } else {
        Kwo.warn("Vous ne pouvez pas allouer de séances sur une date déjà dépassée.");
      }
    }});
  },
  'callAllocator': function (request) {
    Kwo.exec('/epsycho/calendar', {'request[]':request}, {'container':'calendar-box'});
  },
  'cancel': function () {
    $('datepicker').hide();
  },
  'changeMonth': function (month, year, request) {
    Kwo.exec('/epsycho/daypicker', {'month':month, 'year':year, 'request[]':request}, {'container':'daypicker'});
  },
  'chooseDay': function (day, num, total, month, last, year, request) {
    $$('td.day-selected').each(function(elem) {
      elem.removeClassName('day-selected');
    });
    $('day'+num).up('tr').childElements().each(function (elem) {
      elem.addClassName('day-selected');
    });
    days = [];
    if (num >= 7 && num <= (total - 6)) {
      $('day'+num).up('tr').childElements().each(function (elem, index) {
        if (elem.down('a')) {
          days[index] = elem.down('a').innerHTML;
        }
        limit = new Array(0, 0, 0);
      });
    } else if (num < 7) {
      $('day'+num).up('tr').childElements().each(function (elem, index) {
        if (index < (day - num + 1)) {
          days[index] = last - day + index + num;
        } else if (elem.down('a')) {
          days[index] = elem.down('a').innerHTML;
        }
        limit = new Array((day - num + 1), ((month === 1) ? 12 : month - 1), 1);
      });
    } else if (num > (total - 6)) {
      $('day'+num).up('tr').childElements().each(function (elem, index) {
        if (index > (total - num + day)) {
          days[index] = index - total - day + num;
        } else if (elem.down('a')) {
          days[index] = elem.down('a').innerHTML;
        }
        limit = new Array((total - num + day), ((month === 12) ? 1 : month + 1), 2);
      });
    }
    $('calendar').show();
    Kwo.exec('/epsycho/calendar.select',
             {'days[]':days, 'month':month, 'year':year, 'limit[]':limit, 'request[]':request},
             {'container':'calendar'});
  },
  'learnMore': function (element, id, profile) {
    if ($('cm_'+id)) {
      $('cm_'+id).up('tr').show();
    } else {
      element = $(element);
      element.insert({'after': '<tr class="'+element.className+'"><td id="cm_'+id+'" colspan="3"></td></tr>'});
      Kwo.exec('/account/epsycho/consultation.more',
               {'reservation_id':id, 'profile':profile},
               {'container':'cm_'+id});
    }
  },
  'select': function (reservation_id, refresher) {
    $('datepicker').show();
    Epsycho.Reservation.refresher = refresher;
    Kwo.exec('/epsycho/date.form',
             {'id':reservation_id},
             {'container':'datepicker'});
  },
  'validate': function (elt) {
    var elt = $(elt);
    Kwo.exec('/epsycho/reservation.validate', elt, {'callback':Epsycho.Reservation.callback});
  },
  'validateCallback': function(res) {
    if (Kwo.hasError(res)) {
      alert(res.result.msg);
    }
    else {
      $('datepicker').hide();
      Kwo.Cart.addPurchase(res["result"]["item_key"], 1);
      var days = Epsycho.Reservation.refresher[0];
      var month = Epsycho.Reservation.refresher[1];
      var year = Epsycho.Reservation.refresher[2];
      var limit = Epsycho.Reservation.refresher[3];
      var request = Epsycho.Reservation.refresher[4];
      Kwo.exec('/epsycho/calendar.select',
               {'days[]':days, 'month':month, 'year':year, 'limit[]':limit, 'request[]':request},
               {'container':'calendar'});
    }
  },
  'countdownCallback': function(res) {
    $('join-room').update(res['result']['html']['content']);
    $('join-room').removeClassName('join-access');
    $('join-room').removeClassName('join-waiting');
    $('join-room').addClassName('join-'+res['result']['html']['method']);
  },
  'frontHandlerBoth': function() {
    //Epsycho.Reservation.frontHandlerDate($F('reservation-date'));
    //Epsycho.Reservation.frontHandlerTime($F('reservation-time'));
    $('step2').show();
  },
  'frontHandlerDate': function(date) {
    $('step2').down('.dates-start').down('.date-block').update(date);
    $('step2').down('.dates-end').down('.date-block').update(date);
    $('reservation-time').select('option').each(function(elm) {
      elm.remove();
    });
    var json = $('reservation-date').down('option', $('reservation-date').selectedIndex).readAttribute('data-src-item').evalJSON();
    var rendered = '';
    json.each(function(json_element) {
      rendered = rendered + '<option data-src-id="'+ json_element['id'] +'" value="'+ json_element['time'] +'">'+ json_element['time'] +'h</option>';
    });
    $('reservation-time').update(rendered);
    Epsycho.Reservation.frontHandlerTime($F('reservation-time'));
  },
  'frontHandlerTime': function(time) {
    $('step2').down('.dates-start').down('.time-block').update(time.substr(0, 2) + ':00:00');
    $('step2').down('.dates-end').down('.time-block').update(time.substr(0, 2) + ':45:00');
    $('reservation-id').value = $('reservation-time').down('option', $('reservation-time').selectedIndex).readAttribute('data-src-id');
  },
  'callback': function(res) {
    if (Kwo.hasError(res)) {
      alert(res.result.msg);
    } else {
      $('step2').hide();
      Kwo.Cart.addPurchase(res["result"]["item_key"], 1);
    }
  }
};

Epsycho.Showcase = {
  'timeout':null,
  'showNextFolders': function (offset, cat_id) {
    Kwo.exec('/epsycho/folder.showcase', {'offset':offset, 'cat_id':cat_id}, {'container':'epsycho-round-folder'});
  },
  'showNextPublications': function (offset, psy_id, nbpublications) {
    if ((nbpublications - 1) / 3 < offset) {
      offset = 0;
    }
    $$('div#pagination a.pagination-selected').each(function(elem) {
      elem.removeClassName('pagination-selected');
    });
    $$('div#pagination a.pagination-page').each(function(elem, index) {
      if (index == offset) {
        elem.addClassName('pagination-selected');
      }
    });
    if ($('showcase'+offset)) {
      $$('div.epsycho-folder-content').each(function(elem) {
        elem.hide();
      });
      $('showcase'+offset).show();
      window.clearTimeout(Epsycho.Showcase.timeout);
      Epsycho.Showcase.timeout = window.setTimeout("Epsycho.Showcase.showNextPublications("+(offset + 1)+", "+psy_id+", "+nbpublications+")", 10000);
    } else {
      $('epsycho-round-folder').insert({'top':'<div class="epsycho-folder-content" id="showcase'+offset+'">'});
      Kwo.exec('/epsycho/publication.showcase', {'offset':offset, 'psy_id':psy_id, 'no_pager':"no_pager"}, {'container':$('showcase'+offset)});
      $$('div.epsycho-folder-content').each(function(elem) {
        elem.hide();
      });
      $('showcase'+offset).show();
    }
  }
};

Epsycho.DatePicker = {
  'current_selection': null,
  'changeMonth': function(month, year) {
    Kwo.exec('/epsycho/date.picker', {'month':month, 'year':year}, {'container':'date-picker'});
  },
  'setSelected': function(element, date) {
    element = $(element);
    if (Epsycho.DatePicker.current_selection != null) {
      Epsycho.DatePicker.current_selection.removeClassName('selected');
    }
    Epsycho.DatePicker.current_selection = element;
    Epsycho.DatePicker.current_selection.addClassName('selected');
    $('hidden-date').value = date;
  }
};

Epsycho.CallAuth = Class.create(Kwo.Dialog, {

  initialize: function($super, opts) {
    this.name = "auth";
    this.width = 420;
    this.height = 470;
    opts = opts || {};
    if ("callback" in opts) {
      this.onCallback = function () {
        if (Object.isString()) {
          Kwo.go(opts["callback"]);
        }
        else {
          opts["callback"].call();
          this.close();
        }
      }
    }
    else {
      this.onCallback = function () {
        if ("onAuth" in Kwo) {
          Kwo.onAuth.call();
        }
        this.close();
        Kwo.warn("Vous allez recevoir un mail dans les 48h avec la suite de la procédure d'inscription.");
      }
   }
    $super("/community/signup");
  }
});

Epsycho.CallPwdRequest = Class.create(Kwo.Dialog, {

  initialize: function($super, opts) {
    this.name = "auth";
    this.width = 310;
    this.height = 110;
    opts = opts || {};
    if ("callback" in opts) {
      this.onCallback = function () {
        if (Object.isString()) {
          Kwo.go(opts["callback"]);
        }
        else {
          opts["callback"].call();
          this.close();
        }
      }
    }
    else {
      this.onCallback = function () {
        if ("onAuth" in Kwo) {
          Kwo.onAuth.call();
        }
        this.close();
      }
   }
    $super("/epsycho/password.request");
  }
});

Epsycho.CallSender = Class.create(Kwo.Dialog, {

  initialize: function($super, opts) {
    this.name = "auth";
    this.width = 370;
    this.height = 350;
    opts = opts || {};
    if ("callback" in opts) {
      this.onCallback = function () {
        if (Object.isString()) {
          Kwo.go(opts["callback"]);
        }
        else {
          opts["callback"].call();
          this.close();
        }
      }
    }
    else {
      this.onCallback = function () {
        if ("onAuth" in Kwo) {
          Kwo.onAuth.call();
        }
        this.close();
      }
   }
    $super("/epsycho/dossier.send", {'folder': $('folder-id').value});
  }
});
