if (!Kwo) var Kwo = {};

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

  onSignUp: function(args) {
    var input = $('terms_of_use');
    if (!Object.isUndefined(input) && !input.checked) {
      return Kwo.warn(input.readAttribute("data-confirm"));
    }
    Kwo.exec("/community/user.signup", args,
             {callback: Kwo.Auth.onSignupCallback, disable: true});
  },

  onAuthCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    window["_user_id"] = res["result"]["user_id"];
    if (Kwo.getDialog("auth")) {
      var dialog = Kwo.getDialog("auth");
      dialog.onCallback();
      dialog.close();
    }
    else if ("onAuthCallback" in window) {
      window.onAuthCallback();
    }
    else if (window.location.href.indexOf("sign") != -1) {
      Kwo.home()
    }
    else {
      Kwo.reload();
    }
  },

  onSignupCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    window["_user_id"] = res["result"]["user_id"];
		if (typeof MOBILE != 'undefined' && MOBILE){
			Kwo.go('/?firstlog=1');
		}else{
    	Kwo.go('/account/hammel/profil.home?firstlog=1');
		}
  },

  onPasswordRequest: function(args) {
    Kwo.exec("/community/password.send", args,
             {callback: Kwo.Auth.onPasswordRequestCallback.bind($(args)),
              disable: true});
  },

  onPasswordRequestByCode: function(args) {
    Kwo.exec("/community/password.code.send", args,
             {callback: Kwo.Auth.onPasswordRequestCallback.bind($(args)),
              disable: true});
  },

  onPasswordRequestCallback: function(res) {
    if (Kwo.hasError(res)) return Kwo.error(res);
    $('signin-panel').show(); $('password-request').hide();
		if (res['result']['callback_msg']=='no.email'){
			//Kwo.go('/contact?motif_static=rappel');
			$('verify-user_id').setValue(res['result']['user_id']);
			$('verify-sap_code').setValue(res['result']['sap_code']);
			$('verify-organization').setValue(res['result']['organization']);
			$('verify-postal_code').setValue(res['result']['postal_code']);
			$('verify-city').setValue(res['result']['city']);
			$('verify-phone').setValue(res['result']['phone']);
			$('verify-email').setValue(res['result']['email']);
    	$('verify-panel').show(); $('password-request').hide(); $('signin-panel').hide();
			return;
		}
    Kwo.warn(res);
  },

	onVerify : function(args){
    Kwo.exec("/community/user.verify", args,
             {callback: Kwo.Auth.onVerifyCallBack, disable: true});
	},

	onVerifyCallBack : function(res){
		if (Kwo.hasError(res)) return Kwo.error(res);
		$('verify-panel').hide(); $('password-request').hide(); $('signin-panel').show();
    Kwo.warn(res);
	}

};

Kwo.Class.Auth = Class.create(Kwo.Dialog, {
 initialize: function($super, opts) {
   this.opts = opts || {};
   this.name = "auth";
   this.width = window["_auth_width"] || 720;
   this.height = window["_auth_height"] || 450;

   if ("callback" in this.opts) {
     this.onCallback = function () {
       if (Object.isString(this.opts["callback"])) {
         Kwo.go(this.opts["callback"]);
       }
       else {
         this.opts["callback"].call();
       }
     }
   }
   else {
     this.onCallback = function () {
       if ("onAuthCallback" in window) {
         window.onAuthCallback();
       }
     }
   }
   $super("/community/signup");
 }
});

Kwo.Account = {
  timeout: null,

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

  loadPage: function(page) {
    if (page == 1) {
      $('signin-panel').hide();
      $('signup-panel').show();
    }
    else if (page == 2) {
      $('signin-panel').hide();
      $('password-request').show();
    }
  },

  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("/account/community/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("/account/community/password.save", args,
             {callback: true, disable: true, reset: true});
    return true;
  },

  onProfileSubmit: function(args) {
    Kwo.exec("/account/community/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 = 350;
    $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.readAttribute("data-id")},
             {confirm: elt, callback: Kwo.Favorite.onCallback});
  }
}

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


