// The contents of this file are subject to the Mozilla Public License Version 1.1
// (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
// WARRANTY OF ANY KIND, either express or implied. See the License for the specific
// language governing rights and limitations under the License.
// 
// The Original Code is the Venice Web Communities System.
// 
// The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
// for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
// Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
// 
// Contributor(s): 

importPackage(Packages.com.silverwrist.venice.core);
importPackage(Packages.com.silverwrist.venice.except);
importPackage(Packages.com.silverwrist.venice.ui);
importPackage(Packages.com.silverwrist.venice.ui.dlg);
importPackage(Packages.com.silverwrist.venice.ui.helpers);

// Get the request object and the target URI.
rinput = bsf.lookupBean("request");
target = rinput.getParameter("tgt");
if (target==null)
  target = "top.js.vs";

// If the user is not logged in, this is an error.
user = rinput.user;
if (!(user.isLoggedIn()))
{ // user not logged in - just bail on this
  vlib.output(new ErrorBox(null,"You must log in before you can modify the profile on your account."));
  vlib.done();

} // end if

dlg = rinput.getDialog("profile");

rc = null;
if ("GET"==rinput.verb)
{ // set up the dialog
  dlg.setValue("tgt",target);

  try
  { // pull the user data...
    ci = user.getContactInfo();   // get the main contact info
    props = user.properties;      // get the properties

    dlg.setEnabled("photo",ci.canSetPhoto());
    dlg.setValue("prefix",ci.namePrefix);
    dlg.setValue("first",ci.givenName);
    if (ci.middleInitial!=' ')
      dlg.setValue("mid",String.fromCharCode(ci.middleInitial));
    dlg.setValue("last",ci.familyName);
    dlg.setValue("suffix",ci.nameSuffix);
    dlg.setValue("company",ci.company);
    dlg.setValue("addr1",ci.addressLine1);
    dlg.setValue("addr2",ci.addressLine2);
    if (ci.privateAddress)
      dlg.setValue("pvt_addr",1);
    dlg.setValue("loc",ci.locality);
    dlg.setValue("reg",ci.region);
    dlg.setValue("pcode",ci.postalCode);
    dlg.setValue("country",ci.country);
    dlg.setValue("phone",ci.phone);
    dlg.setValue("mobile",ci.mobile);
    if (ci.privatePhone)
      dlg.setValue("pvt_phone",1);
    dlg.setValue("fax",ci.fax);
    if (ci.privateFax)
      dlg.setValue("pvt_fax",1);
    dlg.setValue("email",ci.email);
    if (ci.privateEmail)
      dlg.setValue("pvt_email",1);
    dlg.setValue("url",ci.URL);
    dlg.setValue("descr",user.description);
    dlg.setValue("photo",ci.photoURL);
    dlg.sendMessage("photo","setLinkURL","profile_photo.js.vs?tgt=" + vlib.encodeURL(target));
    if (props.displayPostPictures)
      dlg.setValue("pic_in_post",1);
    if (props.massMailOptOut)
      dlg.setValue("no_mass_mail",1);
    dlg.setValue("locale",user.locale);
    dlg.setValue("tz",user.timeZone);
    rinput.displayLogin = false;
    rc = dlg;

  } // end try
  catch (e)
  { // exception setting up the dialog
    etype = vlib.exceptionType(e) + "";
    if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error retrieving profile: " + e.message,target);
    else
      rc = e;

  } // end catch

  vlib.output(rc);
  vlib.done();

} // end if

// everything that follows is for a POST operation
op = dlg.whichButton(rinput) + "";
if (op=="cancel")
{ // user cancelled profile update - bounce back to the target
  vlib.output(new Redirect(target,LinkTypes.SERVLET));
  vlib.done();

} // end if

dlg.load(rinput);        // load the dialog parameters

if (op=="update")
{ // attempt to update the user profile
  try
  { // start by validating the dialog
    dlg.validate();   // validate the dialog

    // check the passwords
    pass1 = dlg.getValue("pass1") + "";
    pass2 = dlg.getValue("pass2") + "";

    if (vlib.emptyString(pass1))
    { // empty must match empty
      if (!(vlib.emptyString(pass2)))
	throw new ValidationException("The typed passwords do not match.");

    } // end if
    else
    { // the two passwords must match
      if (pass1!=pass2)
	throw new ValidationException("The typed passwords do not match.");

    } // end else

    ci = user.getContactInfo();   // get the main contact info
    props = user.properties;      // get the properties

    // Reset the contact info fields.
    ci.namePrefix = dlg.getValue("prefix");
    ci.givenName = dlg.getValue("first");
    blort = dlg.getValue("mid") + "";
    if (blort.length<1)
      ci.middleInitial = " ";
    else
      ci.middleInitial = blort.substring(0,1);
    ci.familyName = dlg.getValue("last");
    ci.nameSuffix = dlg.getValue("suffix");
    ci.company = dlg.getValue("company");
    ci.addressLine1 = dlg.getValue("addr1");
    ci.addressLine2 = dlg.getValue("addr2");
    ci.privateAddress = dlg.getValue("pvt_addr").booleanValue();
    ci.locality = dlg.getValue("loc");
    ci.region = dlg.getValue("reg");
    ci.postalCode = dlg.getValue("pcode");
    ci.country = dlg.getValue("country");
    ci.phone = dlg.getValue("phone");
    ci.mobile = dlg.getValue("mobile");
    ci.privatePhone = dlg.getValue("pvt_phone").booleanValue();
    ci.fax = dlg.getValue("fax");
    ci.privateFax = dlg.getValue("pvt_fax").booleanValue();
    ci.email = dlg.getValue("email");
    ci.privateEmail = dlg.getValue("pvt_email").booleanValue();
    ci.URL = dlg.getValue("url");

    // Store the completed contact info.
    need_verify = user.putContactInfo(ci);

    // Save off the properties.
    props.displayPostPictures = dlg.getValue("pic_in_post").booleanValue();
    props.massMailOptOut = dlg.getValue("no_mass_mail").booleanValue();
    user.properties = props;

    // Save off the user's description and preferences.
    user.description = dlg.getValue("descr");
    user.locale = dlg.getValue("locale");
    user.timeZone = dlg.getValue("tz");

    // Finally, change the password if applicable.
    if (!(vlib.emptyString(pass1)))
      user.setPassword(pass1,dlg.getValue("remind"));

    // Bounce back to our desired target.
    if (need_verify)
      rc = new Redirect("verify_email.js.vs?tgt=" + vlib.encodeURL(target),LinkTypes.SERVLET);
    else
      rc = new Redirect(target,LinkTypes.SERVLET);

  } // end try
  catch (e)
  { // exception changing the user profile
    etype = vlib.exceptionType(e) + "";
    if (etype.match("ValidationException"))
    { // redisplay the dialog on validation error
      dlg.setErrorMessage(e.message + " Please try again.");
      dlg.setEnabled("photo",user.canSetUserPhoto());
      dlg.setValue("pass1",null);
      dlg.setValue("pass2",null);
      rinput.displayLogin = false;
      rc = dlg;

    } // end if
    else if (etype.match("DataException"))
      rc = new ErrorBox("Database Error","Database error updating profile: " + e.message,target);
    else if (etype.match("EmailException"))
      rc = new ErrorBox("E-mail Error","E-mail error sending confirmation: " + e.message,target);
    else
      rc = e;

  } // end catch

} // end if
else
{ // unknown button pressed...
  logger.error("no known button click on POST to profile.js");
  rc = new ErrorBox("Internal Error","Unknown command button pressed",target);

} // end else

vlib.output(rc);   // all done!
