
if (!Kwo) var Kwo = {};

Kwo.Auth = {
  "referer" : null,
  "is_signup": false,

  onSignIn: function(args) {
    Kwo.Auth.referer = 0;
      
    Kwo.exec("/community/user.signin", args,
             {callback: Kwo.Auth.onAuthCallback, disable: true});
  },

  onSignUp: function(args) {
    var input = $('cgu');
    var bool = 1;    
    
    if (!Object.isUndefined(input) && !input.checked) {
       if($('kwo_error_signup_top')) {
        $('blabla_error_signup_top').update("Veuillez accepter les conditions générales d'utilisation");
        $('blabla_error_signup_bottom').update("Veuillez accepter les conditions générales d'utilisation");
        $('kwo_error_signup_top').show();
        $('kwo_error_signup_bottom').show();
      }
      bool = 0;
    }

    $("kwo-signup").select('input[class=text]').each(function(elt){
        if(elt.readAttribute('filtre')=="yes" && $F(elt).length < 2) {
          if($('kwo_error_signup_top')) {
            $('blabla_error_signup_top').update("Les informations requises nécessitent au moins 2 caractères");
            $('blabla_error_signup_bottom').update("Les informations requises nécessitent au moins 2 caractères");
            $('kwo_error_signup_top').show();
            $('kwo_error_signup_bottom').show();
          }
          bool = 0;
        }
    });

    if(bool == 1) {
      Kwo.Auth.referer = 1;
      Kwo.Auth.is_signup = true;
      Kwo.exec("/community/user.signup", args,
               {callback: Kwo.Auth.onAuthCallback, disable: true});
    }
  },

  onAuthCallback: function(res) {
    if (Kwo.hasError(res)){
      Kwo.error(res);
      return false;
    }
    
    if($('default_connecte')){
  	  $('default_connecte').show(); 
  	  $('default_nonconnecte').hide(); 
  	  $('default_btn_connecte_template').show();
  	}
    
    window["_user_id"] = res["result"]["user_id"];
    if (Kwo.getDialog("auth")) {
      var dialog = Kwo.getDialog("auth");
      dialog.onCallback();
      dialog.close();
      Kwo.exec('/skeleton.sign', null, {container:'logo-signup'});
    }
    else if ("onAuthCallback" in window) {
      if (Kwo.Auth.is_signup == true) {
        Kwo.go('/signup.redirector', {"referer": window._callback_url});
      }
      else {
        window.onAuthCallback();
        Kwo.exec('/skeleton.sign', null, {container:'logo-signup'});
      }
    }
    else if (window.location.href.indexOf("sign") != -1) {
      Kwo.go('/btapie/signup.confirm');
    }
    else {
      if (Kwo.Auth.is_signup == true) {
        Kwo.go('/signup.redirector', {"referer": res["result"]["referer"]});
      }
      else {
        Kwo.reload();
      }
    }
  },

  onPasswordRequestCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    this.up('div').hide().previous().show();
    Kwo.warn(res);
  },

  onPasswordRequest: function(args) {
    if ($(args).tagName.toUpperCase() != "FORM") args = $(args).up('form');
    Kwo.exec("/community/password.send", args,
             {callback: Kwo.Auth.onPasswordRequestCallback.bind(args),
              disable: true});
  }

};

Kwo.Class.Auth = Class.create(Kwo.Dialog, {

 initialize: function($super, opts) {
   this.name = "auth";
   this.width = 520;
   this.height = 300;
   this.opts = opts || {};
   if ("callback" in this.opts) {
     this.onCallback = function () {
       if (Object.isString(this.opts["callback"])) {
         Kwo.go(this.opts["callback"]);
       }
       else {
         this.opts["callback"].call();
//         this.close();
       }
     }
   }
   else {
     this.onCallback = function () {
       if ("onAuthCallback" in window) {
         window.onAuthCallback();
       }
//       this.close();
     }
   }
   $super("/community/signup" , {'display':'login'});
 }

});

Kwo.Account = {

  timeout: null,

  onEnter: function(page) {
    if (!Kwo.isAuth()) {
      new Kwo.Class.Auth({callback: function() { Kwo.reload(); }});
      return ;
    }
    Kwo.go("/community/account");
  },

  onLeave: function(elt) {
    Kwo.exec("/community/user.signout", null,
             {callback: Kwo.home/*,
              confirm: elt*/});
  },

  refresh: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    if ("result" in res && "callback_url" in res["result"]) {
      return Kwo.go(res["result"]["callback_url"]);
    }
    Kwo.reload();
  },

  setMessage: function(msg, error) {
    error = false;
    if (typeof msg == "object" && "error" in msg) {
      if (msg["error"] >= 1) {
        error = "Oops! " + msg["result"]["msg"].join(",");
      }
      else {
        msg = msg["result"]["callback_msg"];
      }
    }
    else {
      error = error || false;
    }
    var pix = "ok.png";
    if (error != false) {
      pix = "ko.png";
      msg = error;
    }
    else {
      msg = Object.isUndefined(msg) ||  msg.empty() ? "ok" : msg;
    }
    if (!$("account-notice")) return ;
    var notice = $("account-notice");
    notice.show();
    notice.update(msg.ucfirst() + '<img src="/app/sys/pix/bullets/' + pix + '" />'
                                   +'<div style="clear:both;"></div>');
    window.clearTimeout(Kwo.Account.timeout);
    Kwo.Account.timeout = window.setTimeout(notice.hide.bind(notice), 5000);
  },

  initAuthBox: function() {
    Kwo.exec("/community/widget.auth", null,
             {container: "kwo-auth-box"});
  }

};

Kwo.User = {

  onAvatarSet: function(file) {
    Kwo.exec("/account/community/avatar.save", {"image": file},
             {callback: Kwo.User.onAvatarCallback});
  },

  onAvatarCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.exec("/account/community/avatar.edit", null,
             {container: $("avatar-box")});
  },

  onEmailSubmit: function(args) {
    Kwo.exec("email.save", args,
             {callback: true, disable: true});
  },

  onEmailConfirm: function(elt) {
    Kwo.exec("/community/email.confirm.request", null,
             {callback: $(elt).up("div")});
  },

  onPasswordSubmit: function(args) {
    Kwo.exec("password.save", args,
             {disable: true, callback: function(res) {
               Kwo.go('/account');
             }});
  },

  onProfileSubmit: function(args) {
    Kwo.exec("profile.save", args,
             {callback: true, disable: true});
  }

};

Kwo.Composer.Message = Class.create(Kwo.Dialog, {

  initialize: function($super, elt) {
    this.name = "abuse";
    this.layout = "hbox";
    this.width = 600;
    this.height = 400;
    this.args = {item_key: $(elt).readAttribute("data-item-key")};
    $super("/community/message.compose");
  },

  onSubmit: function(elt) {
    elt = $(elt);
    Kwo.exec("/community/message.send", [this.args, elt],
             {callback: elt, disable: elt});
  }

});

Kwo.Composer.Favorite = Class.create(Kwo.Dialog, {

  initialize: function($super, elt) {
    this.name = "favorite";
    this.layout = "hbox";
    this.args = {item_key: $(elt).readAttribute("data-item-key"),
                 url: $(elt).readAttribute("data-url")};
    this.width = 400;
    this.height = 320;
    $super("/community/favorite.prompt");
  },

  onSave: function(elt) {
    if (!Kwo.isAuth()) {
      var auth = new Kwo.Class.Auth();
      auth.onCallback = this.onSave.bind(this).curry(elt);
      return ;
    }
    elt = $(elt);
    Kwo.exec("/community/favorite.save", [this.args, elt],
             {callback: elt.down("UL"), disable: elt});
  }

});

Kwo.Favorite = {

  onAlertUnset: function(elt) {
    elt = $(elt);
    Kwo.exec("/community/favorite.alert.unset",
             {id: elt.up("TR").readAttribute("data-id")},
             {confirm: elt, callback: Kwo.Favorite.onCallback});
  },

  onCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    Kwo.reload();
  },

  onDelete: function(elt) {
    elt = $(elt);
    Kwo.exec("/community/favorite.delete",
             {id: elt.up("TR").readAttribute("data-id")},
             {confirm: elt, callback: Kwo.Favorite.onCallback});
  }

}

Kwo.Notice = {

  onSubmit: function(args) {
    Kwo.exec("notice.save", args,
             {callback: true, disable: true});
  }

};

