<!--
 -
 -  $Id$
 -
 -  This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
 -  project.
 -
 -  Copyright (C) 1998-2018 OpenLink Software
 -
 -  This project is free software; you can redistribute it and/or modify it
 -  under the terms of the GNU General Public License as published by the
 -  Free Software Foundation; only version 2 of the License, dated June 1991.
 -
 -  This program is distributed in the hope that it will be useful, but
 -  WITHOUT ANY WARRANTY; without even the implied warranty of
 -  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 -  General Public License for more details.
 -
 -  You should have received a copy of the GNU General Public License along
 -  with this program; if not, write to the Free Software Foundation, Inc.,
 -  51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 -
-->
<v:page name="blog-home-page"
        xmlns:vm="http://www.openlinksw.com/vspx/ods/"
        xmlns:v="http://www.openlinksw.com/vspx/"
        style="index.xsl"
        doctype="-//W3C//DTD XHTML 1.0 Transitional//EN"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  <vm:page>
    <vm:header>
      <vm:title>Create New <?V self.instance_descr?></vm:title>
    </vm:header>
    <v:on-init>
      <![CDATA[
        if (self.instance_descr is null)
          self.instance_descr := WA_GET_APP_NAME (coalesce(get_keyword('wa_name', self.vc_event.ve_params), (select WAI_TYPE_NAME from WA_INSTANCE where WAI_ID = get_keyword('wai_id', self.vc_event.ve_params)), ''));
        self.wa_type := self.wa_name;

        if (self.wa_type in ('oDrive', 'oMail', 'IM'))
        {
          self.is_visible := 0;
        }
        self.domains := '<domains/>';
        if ((self.wa_type = 'oMail') or (self.wa_type = 'IM'))
        {
          declare pos integer;
          self.domains := '';
          for (select WD_DOMAIN from DB.DBA.WA_DOMAINS) do
          {
            pos := strstr(concat(WD_DOMAIN, ':'), ':');
            self.domains := concat(self.domains, sprintf('<domain>%s</domain>', substring(WD_DOMAIN, 1, pos)));
          }
          if (self.domains = '')
            signal('22024', 'No domains available.');
          self.domains := concat('<domains>', self.domains, '</domains>');
        }
        self.domains := xml_tree_doc(self.domains);
      ]]>
    </v:on-init>

    <v:method name="create_new_app" arglist="inout control vspx_button, inout e vspx_event">
    <![CDATA[
      declare _len any;
      declare ihome varchar;
      ihome := self.ihome1.ufl_value;
      ihome := replace(ihome, '\\', '/');

      if (self.wa_type in ('WEBLOG2','Community','oGallery'))
      {
        while (strstr(ihome, '//') is not null)
        {
          ihome := replace(ihome, '//', '/');
        }
        ihome := trim(ihome, '/');
        ihome := concat('/', ihome);
        _len := length(coalesce(ihome, ''));
        if (self.main_domain.ufl_value = '{Default Domain}')
        {
          if (_len < 2)
          {
            self.vc_error_message := 'Application home path should not be empty';
            self.vc_is_valid := 0;
            self.ihome1.ufl_failed := 1;
            return;
          }
          if (exists(select 1 from DB.DBA.HTTP_PATH where HP_LPATH = ihome))
          {
            self.vc_error_message := 'Application home path already exists';
            self.vc_is_valid := 0;
            self.ihome1.ufl_failed := 1;
            return;
          }
          if (exists(select 1 from DB.DBA.HTTP_PATH where left(HP_LPATH, _len+1) = concat(ihome, '/')))
          {
            self.vc_error_message := 'Application home path shadows other already existing path';
            self.vc_is_valid := 0;
            self.ihome1.ufl_failed := 1;
            return;
          }
	        if (self.wa_type = 'WEBLOG2')
	        {
            connection_set('blog2_home', ihome);
          }
	        else if (self.wa_type = 'Community')
	        {
            connection_set('community_customendpoint', ihome);
          }
	        else if (self.wa_type = 'oGallery')
	        {
             connection_set('ogallery_customendpoint', ihome);
          }
        } else {
	        if (self.wa_type = 'WEBLOG2')
	        {
            connection_set('blog2_home', null);
          }
	        else if (self.wa_type = 'Community')
	        {
            connection_set('community_customendpoint', null);
          }
	        else if (self.wa_type = 'oGallery')
	        {
            connection_set('ogallery_customendpoint', ihome);
          }
        }
      }
      else if (self.wa_type = 'oWiki')
      {
        declare _instance_name varchar;
        _instance_name := coalesce(self.iname1.ufl_value, '');
        if (regexp_match ('[A-Za-z0-9_]+', _instance_name) <> _instance_name)
        {
          self.vc_error_message := 'Wiki instance must be single word without special characters';
          self.vc_is_valid := 0;
          self.iname1.ufl_failed := 1;
          return;
        }
        connection_set('wiki_home', ihome);
      }
      else if (self.wa_type = 'IM')
      {
        declare _instance_name varchar;
        self.iname2.ufl_value := trim (self.iname2.ufl_value);
        _instance_name := coalesce(self.iname2.ufl_value, '');
        if (isnull (regexp_match ('^[A-Za-z0-9_]+\$', _instance_name)))
        {
          self.vc_error_message := 'IM instance must be single word without special characters';
          self.vc_is_valid := 0;
          self.iname2.ufl_failed := 1;
          return;
        }
      }
      _len := length(coalesce(self.iname1.ufl_value, ''));
      if (self.wa_type = 'IM')
        _len := length(coalesce(self.iname2.ufl_value, ''));
      if (_len < 1 or _len > 55)
      {
        self.vc_error_message := 'Application name should not be empty and not longer 55 characters';
        self.vc_is_valid := 0;
        self.iname1.ufl_failed := 1;
        return;
      }

      if (self.switch_adv=0)
      {
        self.idesc1.ufl_value := self.idesc;
        self.imodel1.ufl_value := cast(self.imodel as varchar);
        _len := length(coalesce(self.idesc, ''));
      } else {
        _len := length(coalesce(self.idesc1.ufl_value, ''));
      }

      if (_len < 1 or _len > 250)
      {
        self.vc_error_message := 'Application description should not be empty and not longer 250 characters';
        self.vc_is_valid := 0;
        self.idesc1.ufl_failed := 1;;
        return;
      }
      -- check if instance with the same name already exists
      if (self.wa_type = 'oMail')
      {
        declare tmp any;
        tmp := concat(self.iname1.ufl_value, '@', self.idomain1.ufl_value);
        if (exists(select 1 from WA_INSTANCE where WAI_NAME = tmp))
        {
          self.vc_error_message := 'Application ''' || tmp || ''' already exists.';
          self.vc_is_valid := 0;
          return;
        }
        -- update instance
        self.inst := self.inst.wa_name := tmp;
        self.inst := self.inst.wa_domain_set(self.idomain1.ufl_value);
      }
      else if (self.wa_type = 'IM')
      {
        declare tmp any;
        tmp := concat(self.u_name, '@', self.idomain2.ufl_value, '/', self.iname2.ufl_value);
        if (exists(select 1 from WA_INSTANCE where WAI_NAME = tmp))
        {
          self.vc_error_message := 'Application ''' || tmp || ''' already exists.';
          self.vc_is_valid := 0;
          return;
        }
        -- update instance
        self.inst := self.inst.wa_name := tmp;
      } else {
        if (exists(select 1 from WA_INSTANCE where WAI_NAME = self.iname1.ufl_value))
        {
          self.vc_error_message := 'Application ''' || self.iname1.ufl_value || ''' already exists.';
          self.vc_is_valid := 0;
          return;
        }
        self.inst := self.inst.wa_name := self.iname1.ufl_value;
      }
      self.inst := self.inst.wa_member_model := atoi(self.imodel1.ufl_value);



      declare logo_ext, welcome_ext varchar;

      logo_ext := '';
      welcome_ext := '';

      if (self.wa_type='Community' and cast(self.switch_adv as integer))
      {
        if (self.logo_group.ufl_value='logo_use_combo')
        {
          logo_ext := subseq(self.ilogo_c1.ufl_Value,strrchr(self.ilogo_c1.ufl_Value,'.'));
        } else {
          if (self.ilogo_isdav_cb.ufl_selected)
          {
            if (self.t_ilogopath_dav.ufl_value is null or length(self.t_ilogopath_dav.ufl_value)<1)
            {
              self.vc_error_message := 'The path to resource that you have selected for you community logo is invalid.';
              self.vc_is_valid := 0;
              return;
            } else {
              logo_ext := subseq(self.t_ilogopath_dav.ufl_value,strrchr(self.t_ilogopath_dav.ufl_value,'.'));
            }
            if (lower(logo_ext) not in ('.jpg','.gif','.png'))
            {
              self.vc_error_message := 'The type of resource that you have selected for your community logo is invalid. Please use JPG,GIF or PNG';
              self.vc_is_valid := 0;
              return;
            }
          } else {
            if (self.t_ilogopath_fs.ufl_value is null or length(self.t_ilogopath_fs.ufl_value)<1)
            {
              self.vc_error_message := 'The path to resource that you have selected for your community logo is invalid.';
              self.vc_is_valid := 0;
              return;
            } else {
              declare _filename varchar;

              _filename:=get_keyword('filename',get_keyword('attr-t_ilogopath_fs',self.vc_event.ve_params,''),'');
              logo_ext := subseq(_filename,strrchr(_filename,'.'));
            }
            if (lower(logo_ext) not in ('.jpg','.gif','.png'))
            {
              self.vc_error_message := 'The type of resource that you have selected for your community logo is invalid. Please use JPG,GIF or PNG';
              self.vc_is_valid := 0;
              return;
            }
          }
        }

        if (self.welcome_group.ufl_value='welcome_use_combo')
        {
          welcome_ext := subseq(self.iwelcome_c1.ufl_value,strrchr(self.iwelcome_c1.ufl_value,'.'));
        } else {
          if (self.iwelcome_isdav_cb.ufl_selected)
          {
            if (self.t_iwelcomepath_dav.ufl_value is null or length(self.t_iwelcomepath_dav.ufl_value)<1)
            {
              self.vc_error_message := 'The path to resource that you have selected for your community welcome image is invalid.';
              self.vc_is_valid := 0;
              return;
            } else {
              welcome_ext := subseq(self.t_iwelcomepath_dav.ufl_value,strrchr(self.t_iwelcomepath_dav.ufl_value,'.'));
            }
            if (lower(welcome_ext) not in ('.jpg','.gif','.png'))
            {
              self.vc_error_message := 'The type of resource that you have selected for you community welcome image is invalid. Please use JPG,GIF or PNG';
              self.vc_is_valid := 0;
              return;
            }
          } else {
            if (self.t_iwelcomepath_fs.ufl_value is null or length(self.t_iwelcomepath_fs.ufl_value)<1)
            {
              self.vc_error_message := 'The path to resource that you have selected for your community welcome image is invalid.';
              self.vc_is_valid := 0;
              return;
            } else {
              declare _filename varchar;

              _filename:=get_keyword('filename',get_keyword('attr-t_iwelcomepath_fs',self.vc_event.ve_params,''),'');
              welcome_ext := subseq(_filename,strrchr(_filename,'.'));
            }
            if (lower(welcome_ext) not in ('.jpg','.gif','.png'))
            {
              self.vc_error_message := 'The type of resource that you have selected for your community welcome image is invalid. Please use JPG,GIF or PNG';
              self.vc_is_valid := 0;
              return;
            }
          }

        }



      }


      declare h, id any;

      -- create new instance
      h := udt_implements_method (self.inst, 'wa_new_inst');
      declare exit handler for sqlstate '*'
      {
        self.vc_error_message := WA_RETRIEVE_MESSAGE (concat (__SQL_STATE, ' ', __SQL_MESSAGE));
        self.vc_is_valid := 0;
        rollback work;
        return;
      };
      id := call (h) (self.inst, connection_get ('vspx_user'));
      if (self.wa_type not in ('oMail', 'IM') and self.switch_adv = 1)
      {
        self.is_public := self.is_public1.ufl_selected;
      }
      if (self.wa_type not in ('oDrive', 'oMail', 'IM') and self.switch_adv = 1)
      {
        self.is_visible := self.is_visible1.ufl_selected;
      }
      self.ilic := self.ilic1.ufl_value;
      update WA_INSTANCE
         set WAI_MEMBER_MODEL = atoi(self.imodel1.ufl_value),
             WAI_IS_PUBLIC = self.is_public,
             WAI_MEMBERS_VISIBLE = self.is_visible,
             WAI_NAME = cast (self.inst.wa_name as varchar),
	           WAI_DESCRIPTION = cast (self.idesc1.ufl_value as varchar),
	           WAI_LICENSE = cast (self.ilic1.ufl_value as varchar)
             where WAI_ID = id;
      -- VD creation
      {
	      declare silent int;
        declare lpath, default_lpath varchar;
	      silent := 1;
	      if (self.main_domain.ufl_value <> '{Default Domain}')
	        silent := 0;
        declare exit handler for sqlstate '*'
        {
          rollback work;
          self.vc_is_valid := 0;
          self.vc_error_message := __SQL_MESSAGE;
          return;
    	  };
        default_lpath := self.ihome;
    	  lpath := self.ihome1.ufl_value;

    	  -- these two cases currently needs instance id in the URL
    	  if (lpath is null)
        {
      		if (self.wa_type = 'eNews2')
      		{
      		  lpath := sprintf('/enews2/%d', id);
      		}
      		else if (self.wa_type = 'Bookmark')
      		{
      		  lpath := sprintf('/bookmark/%d', id);
      		}
      		else if (self.wa_type = 'oMail')
      		{
      		  lpath := sprintf('/oMail');
      		}
      		else if (self.wa_type = 'oDrive')
      		{
      		  lpath := sprintf('/odrive/%d', id);
      		}
      		else if (self.wa_type = 'Calendar')
      		{
      		  lpath := sprintf('/calendar/%d', id);
      		}
      		else if (self.wa_type = 'Polls')
      		{
      		  lpath := sprintf('/polls/%d', id);
      		}
      		else if (self.wa_type = 'AddressBook')
      		{
      		  lpath := sprintf('/addressbook/%d', id);
      		}
        }
    	  if (default_lpath is null)
          default_lpath := lpath;

    	  if (lpath is not null)
    	    WA_SET_APP_URL (id, lpath, self.sub_domain.ufl_value, self.main_domain.ufl_value, null, null, null, silent);
          if (default_lpath is not null)
            {
    	    WA_SET_APP_URL (id, default_lpath, null, wa_default_domain (), null, null, null, 1);
	      WA_SET_APP_URL (id, default_lpath, null, '{Default HTTPS}', null, null, null, 1);
	    }
      }
      commit work;

      if (self.wa_type='Community' and cast(self.switch_adv as integer))
      {
        declare new_inst_upload_path varchar;
        declare logo_res_type,welcome_res_type varchar;

        logo_res_type := '';
        welcome_res_type := '';

        new_inst_upload_path:=self.inst.wa_home_url ();
        new_inst_upload_path:=sprintf('/DAV/home/%s%stemplates/custom/',self.u_name,new_inst_upload_path);


        DB.DBA.DAV_DELETE (new_inst_upload_path||'community_logo_img'||logo_ext, 0, 'dav', 'dav');
        DB.DBA.DAV_DELETE (new_inst_upload_path||'community_welcome_img'||logo_ext, 0, 'dav', 'dav');

        if (self.logo_group.ufl_value='logo_use_combo')
        {
          YACUTIA_DAV_COPY(self.ilogo_c1.ufl_value, new_inst_upload_path||'community_logo_img'||logo_ext, 1, '110100100R','dav','dav');
        } else {
          if (self.ilogo_isdav_cb.ufl_selected)
          {
            YACUTIA_DAV_COPY(self.t_ilogopath_dav.ufl_value, new_inst_upload_path||'community_logo_img'||logo_ext, 1, '110100100R','dav','dav');
          } else {
            logo_res_type := get_keyword('Content-Type',get_keyword('attr-t_ilogopath_fs',self.vc_event.ve_params));
            YACUTIA_DAV_RES_UPLOAD(new_inst_upload_path||'community_logo_img'||logo_ext,self.t_ilogopath_fs.ufl_value,logo_res_type,'110100100R','dav','dav');
          }
        }

        if (self.welcome_group.ufl_value='welcome_use_combo')
        {
           YACUTIA_DAV_COPY(self.iwelcome_c1.ufl_Value, new_inst_upload_path||'community_welcome_img'||welcome_ext, 1, '110100100R','dav','dav');
        } else {
          if (self.iwelcome_isdav_cb.ufl_selected)
          {
             YACUTIA_DAV_COPY(self.t_iwelcomepath_dav.ufl_value, new_inst_upload_path||'community_welcome_img'||welcome_ext, 1, '110100100R','dav','dav');
          } else {
            welcome_res_type := get_keyword('Content-Type',get_keyword('attr-t_iwelcomepath_fs',self.vc_event.ve_params));
            YACUTIA_DAV_RES_UPLOAD (new_inst_upload_path||'community_welcome_img'||welcome_ext,self.t_iwelcomepath_fs.ufl_value,welcome_res_type,'110100100R','dav','dav');
          }
        }

        if (udt_implements_method (self.inst, 'apply_custom_settings') <> 0)
        {
           declare h_comm any;

           -- create new instance
           h_comm := udt_implements_method (self.inst, 'apply_custom_settings');
           declare exit handler for sqlstate '*'
           {
             self.vc_error_message := WA_RETRIEVE_MESSAGE (concat (__SQL_STATE, ' ', __SQL_MESSAGE));
             self.vc_is_valid := 0;
             rollback work;
             return;
           };
           call (h_comm) (self.inst, self.itempl_c1.ufl_value,new_inst_upload_path||'community_logo_img'||logo_ext,new_inst_upload_path||'community_welcome_img'||welcome_ext);
        }
      }

      return self.inst.wa_home_url ();
    ]]>
    </v:method>
    <vm:pagewrapper>
      <vm:variable name="inst" type="db.dba.web_app" default="null" persist="0" />
      <vm:variable name="wa_name" type="varchar" default="null" persist="0" param-name="wa_name"/>
      <vm:variable name="wa_type" type="varchar" default="null" persist="0"/>
      <vm:variable name="imodel" type="int" default="1" persist="0"/>
      <vm:variable name="is_public" type="int" default="0" persist="0"/>
      <vm:variable name="is_visible" type="int" default="1" persist="0"/>
      <vm:variable name="iid" type="int" default="null" persist="0"/>
      <vm:variable name="iname" type="varchar" default="null" persist="0"/>
      <vm:variable name="ihome" type="varchar" default="null" persist="0"/>
      <vm:variable name="idesc" type="varchar" default="null" persist="0"/>
      <vm:variable name="ilic" type="varchar" default="null" persist="0"/>
      <vm:variable name="instance_descr" type="varchar" default="null" persist="0" />
      <vm:variable name="wa_domain" type="varchar" default="null" persist="0"/>
      <vm:variable name="domains" type="varchar" default="null" persist="0"/>
      <vm:variable name="switch_adv" type="int" default="0" persist="0"/>
      <vm:variable name="page_type" type="varchar" default="'new'" persist="0"/>
      <vm:variable name="wa_desc" type="varchar" default="null" persist="0"/>
      <vm:variable name="wa_cnt" type="int" default="0" persist="0"/>
      <vm:variable name="maxinstexceeded" type="int" default="0" persist="0"/>
      <vm:variable name="itemplate" type="varchar" default="null" persist="0"/>

      <vm:navigation on="settings"/>
      <vm:subnavigation-new on="site"/>

      <vm:navigation1 on="admin"/>
      <vm:navigation2 on="application"/>
      <vm:rawheader caption="Create New <?V self.instance_descr?>"/>
      <vm:body>
        <vm:login redirect="index.vspx"/>
        <div id="container">
          <div id="main">
	          <div class="box">
      	      <v:local-variable name="dummy">
           		  <v:before-data-bind><![CDATA[
                  if ((exists (select 1  from WA_TYPES  where WAT_NAME =self.wa_name
                      and ( WAT_MAXINST=0 or WAT_MAXINST <= (select WMIC_INSTCOUNT from WA_MEMBER_INSTCOUNT where WMIC_TYPE_NAME=WAT_NAME  and WMIC_UID =self.u_id))))
                      or  self.wa_name='Discussion'
                     )
                  {
                    self.maxinstexceeded:=1;
                  } else {
                    self.maxinstexceeded:=0;
                  }

            		  if (self.promo = 'promo')
           		    {
           		      self.wa_cnt := (select count(1)
           		                        from WA_MEMBER
           		                       where WAM_APP_TYPE = self.wa_name and WAM_USER = self.u_id and WAM_MEMBER_TYPE = 1);
           		      self.wa_desc := case self.wa_type
                            		 		  when 'WEBLOG2' then 'Weblog'
                          		 		    when 'eNews2' then 'Feed Manager'
                          		 		    when 'oDrive' then 'Briefcase'
                          		 		    when 'Bookmark' then 'Bookmarks'
                          		 		    when 'IM' then 'Instant Messenger'
                          				    else self.wa_type
                          				  end;
            		    if (self.wa_cnt = 0)
            		      self.promo := '';
            		  }
      		      ]]></v:before-data-bind>
      	      </v:local-variable>
	            <v:form type="simple" method="POST" name="aform1">
	              <v:template name="maxinst_exceed" type="simple" condition="self.maxinstexceeded = 1 and self.wa_name<>'Discussion'">
	                <div style="padding:10px">You have reached the maximum number of <?V WA_GET_MFORM_APP_NAME(self.wa_name) ?> per user. You are not allowed to create new instance of <?V WA_GET_APP_NAME(self.wa_name) ?>. Go to <a href="<?Vself.odsbar_ods_gpath ||wa_expand_url('services.vspx',self.odsbar_loginparams)?>">My Applications</a> .</div>
	              </v:template>
	              <v:template type="simple" condition="self.maxinstexceeded = 1 and self.wa_name='Discussion'">
	                <div style="padding:10px">You are not allowed to perform this operation. Go to <a href="<?Vself.odsbar_ods_gpath ||wa_expand_url('services.vspx',self.odsbar_loginparams)?>">My Applications</a> .</div>
	              </v:template>

          	    <v:template name="maxinst_notexceed" type="simple" condition="self.maxinstexceeded = 0">
          	      <v:template name="app_cr" type="simple" condition="self.promo = ''">
                    <v:before-data-bind>
                      <![CDATA[
                       if (not e.ve_is_post)
          		         {
                         declare _cnt, _iname, _ihome, _cnt2, _domain, app_suff any;
                         _cnt := (select count(*)
                                    from WA_INSTANCE, WA_MEMBER, SYS_USERS
                                   where WAI_TYPE_NAME = self.wa_name
                                     and WAM_INST = WAI_NAME
                                     and WAM_MEMBER_TYPE = 1
                                     and WAM_USER = U_ID
                                     and U_NAME = self.u_name);

		                     app_suff := WA_GET_APP_NAME (self.wa_type);

                         if (self.wa_type = 'oMail')
                         {
                           _domain := xpath_eval ('/domains/domain', self.domains, 0);
                           _iname := sprintf('%s@%s', self.u_name, cast(_domain[0] as varchar));
                           while (exists(select 1 from WA_INSTANCE where WAI_NAME = _iname))
                           {
                             _iname := sprintf('%s_%d@%s', self.u_name, _cnt, cast(_domain[0] as varchar));
                             _cnt := _cnt + 1;
                           }
                           self.iname := substring(_iname,1,strchr(_iname,'@'));
                           self.idesc := concat(coalesce(self.u_full_name, self.u_name), '\'s ', self.instance_descr);
                         }
                         else if (self.wa_type = 'IM')
                         {
                           app_suff := 'im';
                           _domain := xpath_eval ('/domains/domain', self.domains, 0);
                           _iname := sprintf('%s@%s/%s', self.u_name, cast(_domain[0] as varchar), app_suff);
                           while (exists(select 1 from WA_INSTANCE where WAI_NAME = _iname))
                           {
                             _iname := sprintf('%s@%s/%s%d', self.u_name, cast(_domain[0] as varchar), app_suff, _cnt);
                             _cnt := _cnt + 1;
                           }
                           self.iname := subseq(_iname, strstr(_iname, '/')+1);
                           self.idesc := concat(coalesce(self.u_full_name, self.u_name), '\'s ', self.instance_descr);
                         } else {
                           if (self.wa_type = 'oWiki')
                             _iname := sprintf ('%s%s', self.u_first_name, app_suff);
                           else
                             _iname := sprintf ('%s\'s %s', self.u_first_name, app_suff);
                           while (exists(select 1 from WA_INSTANCE where WAI_NAME = _iname))
                           {
                             _cnt := _cnt + 1;
                             if (self.wa_type = 'oWiki')
                             {
                               _iname := sprintf ('%s%s%d', self.u_first_name, app_suff, _cnt);
                             }
                             else if (self.wa_type = 'IM')
                             {
                               _iname := sprintf ('%s%d', self.u_first_name, _cnt);
                             } else {
                               _iname := sprintf ('%s\'s %s (%d)', self.u_first_name, app_suff, _cnt);
                             }
                           }
                           self.iname := _iname;
                           self.idesc := concat(coalesce(self.u_full_name, self.u_name), '\'s ', self.instance_descr);
                           if (self.wa_type = 'WEBLOG2')
                           {
                             _cnt2 := 0;
                             _ihome := sprintf('%s%s', '/weblog/', self.u_name);
                             while (exists(select 1 from DB.DBA.HTTP_PATH where HP_LPATH = _ihome))
                             {
                               _cnt2 := _cnt2 + 1;
                               _ihome := sprintf('%s%s%d', '/weblog/', self.u_name, _cnt2);
                             }
                             self.ihome := _ihome;
                           }
                           else if (self.wa_type = 'oGallery')
                           {
                             _cnt2 := 0;
                             _ihome := sprintf('%s%s', '/photos/', self.u_name);
                             while (exists(select 1 from DB.DBA.HTTP_PATH where HP_LPATH = _ihome))
                             {
                               _cnt2 := _cnt2 + 1;
                               _ihome := sprintf('%s%s%d', '/photos/', self.u_name, _cnt2);
                             }
                             self.ihome := _ihome;
                           }
                           else if (self.wa_type = 'Community')
                           {
                             declare state, message, meta, result any;
                             declare sql_q varchar;

                             _cnt2 := 0;
                             state := '00000';

                             sql_q := sprintf ('select count(1) from ODS.COMMUNITY.SYS_COMMUNITY_INFO, DB..SYS_USERS  where CI_OWNER=U_ID and U_NAME = ''%s''',self.u_name);
                             exec(sql_q, state, message, vector(), 0, meta, result);

                             if (state <> '00000' )
                               signal (state, 'Community module integrity error '||message);

                             _cnt2 := coalesce(result[0][0],0);
                             _ihome := sprintf('/community/%s_community_%d', self.u_name, _cnt2);
                             self.ihome := _ihome;
                           }
                           else if (self.wa_type = 'oWiki')
                           {
                             _cnt2 := 0;
                             _ihome := sprintf('/%U/%U', self.u_name, 'wiki');
                             while (exists(select 1 from DB.DBA.HTTP_PATH where HP_LPATH = _ihome))
                             {
                               _cnt2 := _cnt2 + 1;
  		 	                      _ihome := sprintf('/%U/wiki/%d', self.u_name, _cnt2);
                             }
                             self.ihome := _ihome;
                           }
                         }
  		                 }
                    ]]>
		                </v:before-data-bind>
		                <table  class="ctl_grp" >
                    <vm:instance-settings />
                    <v:after-data-bind>
                      <![CDATA[
                        if (self.inst is null)
                        {
                          declare ty varchar;
                          declare ins any;
                          whenever not found goto ef;
                          select WAT_TYPE into ty from WA_TYPES where WAT_NAME = self.wa_name;
                          self.inst := __udt_instantiate_class (fix_identifier_case (ty), 0);
                          return;
                          ef:
                          signal ('22023', 'No application type supplied.');
                        }
                      ]]>
    		            </v:after-data-bind>
                  		<tr>
                  		  <td colspan="3">
                  		    <span class="fm_ctl_btn">
                <v:button action="simple" name="cancel1" value="Cancel" >
                  <v:on-post>
                    <![CDATA[
                      http_request_status ('HTTP/1.1 302 Found');
                      http_header (sprintf ('Location: services.vspx?sid=%s&realm=%s&l=1\r\n', self.sid, self.realm));
                    ]]>
                  </v:on-post>
                </v:button>
                <v:button action="simple" name="save_new_launch" value="Create and Launch Application" >
		  <v:on-post>
		    declare url varchar;
		    url := self.create_new_app (control, e);
		    if (self.vc_is_valid)
		      self.vc_redirect (url);
                  </v:on-post>
		</v:button>
                <v:button action="simple" name="save_new" value="Create and Return to My Applications" >
		  <v:on-post>
		    self.create_new_app (control, e);
		    if (self.vc_is_valid)
		      self.vc_redirect ('services.vspx');
                  </v:on-post>
                </v:button>
                  	      </span>
                  	    </td>
                	    </tr>
	                  </table>
	    </v:template>
	    <v:template name="tmpl_inst_ck" type="simple" condition="self.promo = 'promo'">
	      <h2>
		You have already <v:label name="lcnt1" value="--self.wa_cnt" format="%d"/>
		<v:label name="lcls1" value="--self.wa_desc" />
		instance(s). Do you want new one?
	      </h2>

	      <table class="listing">
		<tr class="listing_header_row">
		  <th>Your own <?V self.wa_desc ?></th>
		</tr>
		<?vsp
                    		declare inx integer;
		inx := 0;
                    		for (select WAM_INST, WAM_HOME_PAGE from WA_MEMBER where WAM_APP_TYPE = self.wa_name and WAM_USER = self.u_id and WAM_MEMBER_TYPE = 1) do
		   {
		?>
		<tr class="<?V case when mod(inx,2) then 'listing_row_even' else 'listing_row_odd' end ?>">
		  <td><a href="<?V WAM_HOME_PAGE ?>?<?V self.login_pars ?>"><?V wa_utf8_to_wide (WAM_INST) ?></a></td>
		</tr>
		<?vsp
		     inx := inx + 1;
		   }
		?>
	      </table>

	      <div class="">
                <v:button action="simple" name="yes_bt1" value="Yes" >
                  <v:on-post>
		    <![CDATA[
		    self.promo := '';
                    ]]>
                  </v:on-post>
                </v:button>
                <v:button action="simple" name="no_bt1" value="No" >
                  <v:on-post>
                    <![CDATA[
                      self.vc_redirect ('sfront.vspx');
                    ]]>
                  </v:on-post>
                </v:button>

	      </div>

	    </v:template>
     </v:template>
	  </v:form>
            </div>
          </div>
        </div>
      </vm:body>
    </vm:pagewrapper>
  </vm:page>
</v:page>
