Imports System.Web.Security
Imports System.Data
Imports Telerik.WebControls

Partial Class create_user
    Inherits System.Web.UI.Page

    Protected _webWS As New WebWS
    Protected _commonFunctions As CommonFunctions = New CommonFunctions()
    Protected _user As MembershipUser
    Protected _userProfile As ProfileCommon
    Protected _userName As String

    Public printItInstallerService As New com.racadtech.services.PrintDriverGenerator()
    Public ticket As New com.racadtech.services.Ticket1()
    Public partnerWS As PartnetWS.Service = New PartnetWS.Service
    Public _wronglogo As Boolean = False
    Public _wrongDomain As Boolean = False
    Public _useFTP As Boolean = True

    Public _selectedLanguage As String = ""

    Private _maxMonthlyFeeJS As String = ""
    Public Property MaxMonthlyFeeJS() As String
        Get
            Return _maxMonthlyFeeJS
        End Get
        Set(ByVal value As String)
            _maxMonthlyFeeJS = value
        End Set
    End Property

    Protected Overrides Sub InitializeCulture()

        If Request.QueryString("lang") IsNot Nothing Then
            _selectedLanguage = Request.QueryString("lang").ToString
        Else
            If Session("lang") IsNot Nothing Then
                _selectedLanguage = Session("lang").ToString
            Else
                If Request.Cookies("lang") IsNot Nothing Then
                    _selectedLanguage = Request.Cookies("lang").Value.ToString
                End If
            End If
        End If

        Session("lang") = _selectedLanguage

        If String.IsNullOrEmpty(_selectedLanguage) = False Then
            Me.UICulture = _selectedLanguage
            Me.Culture = Global.Resources.Resource.ResourceManager.GetString(_selectedLanguage)

            System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo(_selectedLanguage)
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(Global.Resources.Resource.ResourceManager.GetString(_selectedLanguage))
        End If

        MyBase.InitializeCulture()
    End Sub


    Protected Function PopulateCountryDDL(ByVal ddlName As DropDownList, ByVal firstItemText As String, ByVal selectedItemText As String) As Boolean
        Try
            Dim _dataSet As New System.Data.DataSet
            _dataSet = _webWS.GetCountries()
            Dim _tableReader As System.Data.DataTableReader
            _tableReader = _dataSet.CreateDataReader()

            Dim i As Integer = 0
            Dim newListItem As ListItem = New ListItem()
            newListItem.Text = firstItemText
            newListItem.Value = "0"
            ddlName.Items.Add(newListItem)

            Dim selectedIndex As Integer = 0

            While _tableReader.Read()
                i = i + 1
                newListItem = New ListItem()
                newListItem.Text = _tableReader.GetString(0)
                newListItem.Value = _tableReader.GetValue(1)
                ddlName.Items.Add(newListItem)
                If _tableReader.GetString(0) = selectedItemText Then
                    ddlName.Items.Item(ddlName.Items.Count - 1).Selected = True
                End If
            End While
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Protected Function PopulateStateDDL(ByVal ddlName As DropDownList, ByVal firstItemText As String, ByVal selectedItemText As String, ByVal countryId As Integer) As Boolean
        Try
            Dim _dataSet As New System.Data.DataSet
            _dataSet = _webWS.GetStates(countryId)
            Dim _tableReader As System.Data.DataTableReader
            _tableReader = _dataSet.CreateDataReader()

            Dim i As Integer = 0
            Dim newListItem As ListItem = New ListItem()
            newListItem.Text = firstItemText
            newListItem.Value = "0"
            ddlName.Items.Add(newListItem)

            Dim selectedIndex As Integer = 0

            While _tableReader.Read()
                i = i + 1
                newListItem = New ListItem()
                newListItem.Text = _tableReader.GetString(0)
                newListItem.Value = _tableReader.GetValue(1)
                ddlName.Items.Add(newListItem)
                If _tableReader.GetString(0) = selectedItemText Then
                    ddlName.Items.Item(ddlName.Items.Count - 1).Selected = True
                End If
            End While
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Protected Function PopulatePackageDDL(ByVal ddlName As DropDownList) As Boolean
        Try
            Dim _dataSet As New System.Data.DataSet
            _dataSet = _webWS.GetPackageInformation()
            Dim _tableReader As System.Data.DataTableReader
            _tableReader = _dataSet.CreateDataReader()

            Dim i As Integer = 0
            Dim newListItem As ListItem
            'newListItem = New ListItem()
            'newListItem.Text = "-- Select Package --"
            'newListItem.Value = "0"
            'ddlName.Items.Add(newListItem)

            ddlName.Items.Clear()

            Dim selectedIndex As Integer = 0

            While _tableReader.Read()
                If (_userProfile.Country.Equals("United Kingdom") Or _userProfile.Country.Equals("Scotland") Or _userProfile.Country.Equals("Ireland")) Then
                    If (_tableReader.Item("PackageId") = 20 Or _tableReader.Item("PackageId") = 21) And (_tableReader.Item("PackagePrice") <> 0) Then
                        i = i + 1
                        newListItem = New ListItem()
                        newListItem.Text = _tableReader("PackageName")
                        newListItem.Value = _tableReader("PackageId")
                        If newListItem.Value = 20 Then newListItem.Selected = True
                        ddlName.Items.Add(newListItem)
                    End If
                Else
                    If (_tableReader.Item("PackageId") = 17 Or _tableReader.Item("PackageId") = 9) And (_tableReader.Item("PackagePrice") <> 0) Then
                        i = i + 1
                        newListItem = New ListItem()
                        newListItem.Text = _tableReader("PackageName")
                        newListItem.Value = _tableReader("PackageId")
                        If newListItem.Value = 17 Then newListItem.Selected = True
                        ddlName.Items.Add(newListItem)
                    End If
                End If
            End While
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Page.IsPostBack = False Then
            Me.Page.DataBind()
            'PackageDescription.Visible = False
            StateTr.Visible = False

            PopulateCountryDDL(CountryDropDownList, GetLocalResourceObject("SelectCountry"), GetLocalResourceObject("SelectCountry"))
            PopulateStateDDL(StateDropDownList, "-- Select State/Province --", "-- Select State/Province --", 0)
            PopulatePackageDDL(Me.PackageTypeDropDownList)
        End If
    End Sub

    Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
        If Wizard1.ActiveStep.ID = "CompleteRegistrationStep" Then
            _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
            FormsAuthentication.RedirectFromLoginPage(_userName, True)
            If _selectedLanguage IsNot Nothing Then
                Response.Redirect("~/settings/distribute_print_driver.aspx?lang=" & _selectedLanguage)
            Else
                Response.Redirect("~/settings/distribute_print_driver.aspx")
            End If
        End If
    End Sub

    Protected Sub TestFTPButton_Click1(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles TestFTPButton.Click
        If Page.IsValid = True Then
            Try
                Dim _password As String = PasswordSetTextBox.Text
                PasswordSetTextBox.Attributes.Add("value", _password)
                _commonFunctions.TestFTP(HostNameTextBox.Text, PortTextBox.Text, PathTextBox.Text, UserNameSetTextBox.Text, PasswordSetTextBox.Text, "sample.txt", Server.MapPath("/") & "\sample.txt")
                Dim script As String = "<SCRIPT LANGUAGE='JavaScript'>alert('Testing of FTP Settings has been successfully done!');</SCRIPT>"
                Me.Page.RegisterClientScriptBlock("ClientScript", script)
            Catch ex As Exception
                Dim script As String = "<SCRIPT LANGUAGE='JavaScript'>alert('" & ex.Message & "');</SCRIPT>"
                Me.Page.RegisterClientScriptBlock("ClientScript", script)
            End Try
        End If
    End Sub

    Protected Sub Wizard1_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.NextButtonClick

        If Wizard1.ActiveStep.ID = "UserInformationStep" Then
            Dim _stepLabel As New Label
            _stepLabel = CType(Wizard1.FindControl("Step1"), Label)
            _stepLabel.CssClass = "wizard_step_active"

            If Page.IsValid = True Then
                'Dim _resultMessage As String = ""
                Try
                    _user = Membership.CreateUser(UserNameTextBox.Text, PasswordTextBox.Text, EmailTextBox.Text)

                    ' Affiliate section
                    Dim sMemberId = Session.Item("member_id")
                    If (sMemberId = "") Then
                        Dim httpCookie As HttpCookie = Request.Cookies("PartnerCookies")
                        If (Not httpCookie Is Nothing) Then
                            sMemberId = httpCookie("MemberId")
                        End If
                    End If

                    Dim lMembId As Long = 0
                    Try
                        lMembId = Convert.ToInt64(sMemberId)
                    Catch ex As Exception
                    End Try
                    If lMembId > 0 Then
                        Dim sMemberUniqId As String = _user.ProviderUserKey.ToString() ' TODO: put real user_id here
                        partnerWS.registerPartner(lMembId, sMemberUniqId)
                    End If

                    ' / Affiliate section

                    Roles.AddUserToRole(UserNameTextBox.Text, "PrintItUsers")
                    _userProfile = ProfileCommon.Create(_user.UserName)

                    ' defining StoreId: find max value of StoreId + 1
                    'Dim _allUsers As MembershipUserCollection = Membership.GetAllUsers
                    'Dim _curUserProfile As ProfileCommon
                    'Dim _max As Integer = 0
                    'For Each _existenUser As MembershipUser In _allUsers
                    '    _curUserProfile = Profile.GetProfile(_existenUser.UserName)
                    '    If _curUserProfile.StoreId > _max And _curUserProfile.StoreId < 999999 Then _max = _curUserProfile.StoreId
                    'Next


		    _userProfile.StoreId = _webWS.GetNewStoreId()

                    _userProfile.Save()


                    '--------------------------------------
                    ' Temporary - store UserId and StoreId in PI_UsersAndStores table 
                    ' In future - create table Stores and store all information there instead of Profile
                    '--------------------------------------

                    _webWS.InsertUserIdAndStoreId(_user.ProviderUserKey, _userProfile.StoreId)




                    '--------------------------------------
                    'create expiration and start billing date
                    ''
                    _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                    _userProfile = Profile.GetProfile(_userName)
                    Dim _storeId As Integer = _userProfile.StoreId
                    ' Dim _packageId = 1
                    Dim _expirationDate As Date
                    _expirationDate = DateTime.Today.AddDays(30)
                    '_userProfile.PackageId = _packageId
                    _userProfile.ExpirationDate = _expirationDate
                    '_userProfile.StartBillingDate = New Date(2009, 1, 1) 'Format(DateTime.Today.AddDays(31), "MM/dd/yyyy")
                    _userProfile.StartBillingDate = DateTime.Today.AddDays(31)
                    _userProfile.Save()

                    'Try
                    '    Dim _userId = Membership.GetUser(_userName).ProviderUserKey
                    '    _webWS.InsertStartBillingDate(_userId, DateTime.Today.AddDays(31), False)
                    'Catch ex As Exception
                    'End Try
                    '----------------------------------------
                    'create an empty record with FTPsettings
                    Try
                        _webWS.InsertFtpSettings(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                                    PasswordSetTextBox.Text, PathTextBox.Text, True)

                    Catch ex As Exception
                        '_resultMessage = "Unable to create user due to the following reason: <br/>" & ex.Message.ToString()
                    End Try

                    '----------------------------------------

                Catch ex As Exception
                    '_resultMessage = "User hasn't been created due to the following reason: <br/>" & ex.Message.ToString()
                End Try
            End If
            Dim _ses As String = Session("lang")
            If Session("lang") = "en" Or Session("lang") = "" Then 'Change dataSource.SelectCommand to fill DownDropList for PressType

                PressTypeDateSource.SelectCommand = "Select PressTypeId,PressType From PI_PressTypes"
            Else
                PressTypeDateSource.SelectCommand = "Select PressTypeId,PressType From PI_PressTypesPerLang where Language='" & Session("lang") & "'"

            End If
        End If

        If Wizard1.ActiveStep.ID = "UserProfileStep" Then
            Try
                _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                _user = Membership.GetUser(_userName)
                _userProfile = Profile.GetProfile(_userName)
            Catch ex As Exception
                Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                Response.Redirect("~/error_page.aspx")
            End Try

            If Page.IsValid = True Then
		Dim _activationId As Guid

                Try
                    _userProfile.StoreName = StoreNameTextBox.Text
                    'If StoreTypeDropDownList.SelectedIndex = 0 Then 'StoreType temperally remove from interface
                    'Else
                    '    If StoreTypeDropDownList.SelectedValue = "Other" Then
                    '        _userProfile.StoreType = StoreTypeTextBox.Text
                    '    Else
                    '        _userProfile.StoreType = StoreTypeDropDownList.SelectedValue
                    '    End If
                    'End If
                    _userProfile.FName = FNameTextBox.Text
                    _userProfile.LName = LNameTextBox.Text
                    _userProfile.Address = AddressTextBox.Text
                    If String.IsNullOrEmpty(AddressTextBox1.Text) = False Then _userProfile.Address1 = AddressTextBox1.Text Else _userProfile.Address1 = "--"
                    _userProfile.City = CityTextBox.Text
                    If StateTr.Visible = True Then
                        _userProfile.State = StateDropDownList.SelectedItem.Text
                    Else
                        _userProfile.State = StateTextBoxAlt.Text
                    End If
                    If ZipTr.Visible = True Then
                        _userProfile.Zip = ZipTextBox.Text
                    Else
                        _userProfile.Zip = ZipTextBoxAlt.Text
                    End If
                    _userProfile.Country = CountryDropDownList.SelectedItem.Text

                    If PhoneTr.Visible = True Then
                        _userProfile.Phone = PhoneTextBox1.Text & PhoneTextBox2.Text & PhoneTextBox3.Text
                    Else
                        _userProfile.Phone = PhoneTextBoxAlt.Text
                    End If
                    If String.IsNullOrEmpty(ExtTextBox.Text) = False Then _userProfile.PhoneExt = ExtTextBox.Text Else _userProfile.PhoneExt = "--"

                    If ZipTr.Visible = True Then
                        If String.IsNullOrEmpty(FaxTextBox1.Text) = False And String.IsNullOrEmpty(FaxTextBox2.Text) = False And String.IsNullOrEmpty(FaxTextBox3.Text) = False Then
                            _userProfile.Fax = FaxTextBox1.Text & FaxTextBox2.Text & FaxTextBox3.Text
                        Else
                            _userProfile.Fax = "--"
                        End If
                    Else
                        If String.IsNullOrEmpty(FaxTextBoxAlt.Text) = False Then
                            _userProfile.Fax = FaxTextBoxAlt.Text
                        Else
                            _userProfile.Fax = "--"
                        End If
                    End If
                    _userProfile.PressTypeId = PressTypeDropDownList.SelectedItem.Value
                    '_userProfile.PressTypeId = PressTypeRadioButtonList.SelectedValue
                    _userProfile.Save()

                    Dim returnCode As String = partnerWS.registerPartnerByCountry(_userProfile.Country, _user.ProviderUserKey.ToString())

                    Dim _webWS As New WebWS
                    _activationId = Guid.NewGuid()
                    _webWS.InsertActivation(_user.ProviderUserKey, _userProfile.StoreId, _activationId.ToString(), True)

                    Session("UserName") = _userName

                    'Commented now because of a bug occured due to this piece of code:
                    'Try
                    '    If _webWS.GetJobSettingsBySettingName("Store Contact").Tables(0).Rows.Count > 0 Then
                    '        Dim _settingId = _webWS.GetJobSettingsBySettingName("Store Contact").Tables(0).Rows(0).Item("SettingId")
                    '        _webWS.InsertJobSettingsPerStore(_settingId, _userProfile.StoreId, True, False)
                    '        _webWS.InsertJobSettingValue(_userProfile.StoreId, _settingId, _userProfile.FName & " " & _userProfile.LName)
                    '    Else
                    '        'TODO: in case if there is not "Store Contact" Setting, create such Setting first, then add values
                    '    End If
                    'Catch ex As Exception

                    'End Try

                    'Membership.ValidateUser(UserNameTextBox.Text, PasswordTextBox.Text)
                    '_user.IsApproved = True
                    'Dim _formsAuthentication As New FormsAuthentication
                    '_formsAuthentication.Authenticate(UserNameTextBox.Text, PasswordTextBox.Text)

                    '_user = Membership.GetUser()

                    'FormsAuthentication.RedirectFromLoginPage(strUser, chkPersistLogin.Checked)

                    'Response.Write("UserId : " & Membership.GetUser.ProviderUserKey.ToString())
                Catch ex As Exception
Dim _body As String = "Key = " & _user.ProviderUserKey.ToString() & " sId = " &  _userProfile.StoreId.ToString() & " aId = " &  _activationId.ToString() & " Exception = " & ex.Message.ToString()
com.racadtech.Framework.Util.Mail.SMTPClient.sendMail(New String() {"amramb@gmail.com"}, "Debug", _body, True, "support@racadtech")
                    '_resultMessage = "User hasn't been created due to the following reason: <br/>" & ex.Message.ToString()
                End Try
            End If
        End If


        If Wizard1.ActiveStep.ID = "SubmissionSettingsStep" Then

            Try
                _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                _user = Membership.GetUser(_userName)
                _userProfile = Profile.GetProfile(_userName)
            Catch ex As Exception
                Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                Response.Redirect("~/error_page.aspx")
            End Try

            Dim _storeId As Integer = _userProfile.StoreId
            Dim _resultMessage As String = ""

            If Page.IsValid = True Then
                Try
                    If _webWS.GetEmailSettingsByStoreId(_storeId).Tables(0).Rows.Count > 0 Then
                        _webWS.UpdateEmailSettingsByStoreId(_storeId, SubSetEmailTextBox.Text, AttachmentTextBox.Text)
                    Else
                        _webWS.InsertEmailSettings(_storeId, SubSetEmailTextBox.Text, 5)
                    End If
                    If _webWS.GetFtpSettingsByStoreId(_storeId).Tables(0).Rows.Count > 0 Then
                        '_webWS.UpdateFtpSettingsByStoreId(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                        '            PasswordSetTextBox.Text, PathTextBox.Text, IsPASVCheckBox.Checked)

                        ' IsPASVCheckBox is commeted now. By default its value is checked (true)
                        _webWS.UpdateFtpSettingsByStoreId(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                                    PasswordSetTextBox.Text, PathTextBox.Text, True)
                    Else
                        '_webWS.InsertFtpSettings(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                        '            PasswordSetTextBox.Text, PathTextBox.Text, IsPASVCheckBox.Checked)

                        ' IsPASVCheckBox is commeted now. By default its value is checked (true)
                        _webWS.InsertFtpSettings(_storeId, HostNameTextBox.Text, PortTextBox.Text, UserNameSetTextBox.Text, _
                                    PasswordSetTextBox.Text, PathTextBox.Text, True)

                    End If
                    '_resultMessage = "Submission Settings have been updated successfully"
                Catch ex As Exception
                    '_resultMessage = "Unable to update Submission Settings due to the following reason: <br/>" & ex.Message.ToString()
                End Try

            End If
            If Session("lang") = "" Then
                Session("lang") = "en"
            End If
            Dim _ses As String = Session("lang")
            ThemeDataSource.SelectCommand = "select  t.Theme, tl.ThemeName from PrintIT.dbo.PI_ThemePerLang tl,  PrintIT.dbo.PI_Theme t " & _
            " where tl.IDTheme=t.IDTheme and Language='" & Session("lang") & "'"
        End If


        If Wizard1.ActiveStep.ID = "PrintDriverInterfaceStep" Then
            Try
                _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                _user = Membership.GetUser(_userName)
                _userProfile = Profile.GetProfile(_userName)
            Catch ex As Exception
                Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                Response.Redirect("~/error_page.aspx")
            End Try

            Dim _storeId As Integer = _userProfile.StoreId
            ResultLabel.Visible = False
            _wronglogo = False
            Dim _resultMessage As String = ""
            If Page.IsValid = True Then
                Try
                    Dim _companyLogo As String = ""
                    If RadUpload2.InvalidFiles.Count > 0 Then
                        Exit Try
                    End If
                    If RadUpload2.UploadedFiles.Count > 0 Then
                        Dim _directory As String = ConfigurationManager.AppSettings("PrintItStoreDataPath") & "\" & _userProfile.StoreId
                        If System.IO.Directory.Exists(_directory) = False Then
                            Try
                                System.IO.Directory.CreateDirectory(_directory)
                            Catch ex As Exception
                            End Try
                        End If
                        Try
                            Dim _logoFile As String
                            For Each _logoFile In System.IO.Directory.GetFiles(_directory)
                                If (_logoFile.StartsWith(_directory & "\logo")) Then
                                    'logFile.WriteLine("[Removing] " & _logoFile)
                                    Try
                                        System.IO.File.Delete(_logoFile)
                                    Catch ex As Exception
                                    End Try
                                End If
                            Next _logoFile
                        Catch ex As Exception
                            'logFile.WriteLine("[EXCEPTION] " & ex.Message)
                        Finally
                            'logFile.Close()
                            'logFile.Dispose()
                        End Try
                        Dim _file As UploadedFile

                        _file = RadUpload2.UploadedFiles.Item(0)
                        Dim _filename As String = "logo." & _commonFunctions.GetDocumentName(_file.GetName, True, "\\").ToString().Split(".")(1)
                        '_file.SaveAs(_directory & "\" & _file.GetName, True)
                        If System.IO.Directory.Exists(_directory) = True Then
                            Try
                                _file.SaveAs(_directory & "\" & _filename, True)
                                RadUpload2.UploadedFiles.Clear()
                                _companyLogo = Request.Url.ToString().Split("//")(0) & "/" & _
                                                Request.Url.ToString().Split("//")(1) & "/" & _
                                                (Request.Url.ToString().Split("//")(2).ToString()).Split(":")(0) & "/" & _
                                                ConfigurationManager.AppSettings("PrintItStoreDataVirtualDirectory") & "/" & _
                                                _userProfile.StoreId & "/" & _
                                                _filename
                                _file = Nothing
                                ' Now Head Office user can not upload image as a Company Logo
                                ' The following condition added for future using
                            Catch ex As Exception
                                'Session.Remove("CompanyLogoTemp")
                            End Try
                        Else
                            ' Session.Remove("CompanyLogoTemp")
                        End If
                    Else
                        If _webWS.GetPrintDriverInterfaceByStoreId(_userProfile.StoreId).Tables(0).Rows.Count > 0 Then


                            _companyLogo = _webWS.GetPrintDriverInterfaceByStoreId(_userProfile.StoreId).Tables(0).Rows(0).Item("CompanyLogo").ToString()
                        End If
                    End If

                    If _webWS.GetPrintDriverInterfaceByStoreId(_userProfile.StoreId).Tables(0).Rows.Count > 0 Then
                        _webWS.UpdatePrintDriverInterfaceByStoreId(_userProfile.StoreId, FrameTitleTextBox.Text, ThankYouMessageTextBox.Text, _
                                    CompanyNameTextBox.Text, CompanyAddressTextBox.Text, CompanyPhoneTextBox.Text, CompanyEmailTextBox.Text, _
                                    _companyLogo, ThemeDropDownList.SelectedValue.ToString().ToLower())
                    Else
                        _webWS.InsertPrintDriverInterface(_userProfile.StoreId, FrameTitleTextBox.Text, ThankYouMessageTextBox.Text, _
                                    CompanyNameTextBox.Text, CompanyAddressTextBox.Text, CompanyPhoneTextBox.Text, CompanyEmailTextBox.Text, _
                                    _companyLogo, ThemeDropDownList.SelectedValue.ToString().ToLower())
                    End If
                    ' _resultMessage = "Print Driver Interface have been updated successfully"
                Catch ex As Exception
                    '_resultMessage = "Unable to update Print Driver Interface due to the following reason: <br/>" & ex.Message.ToString()

                Finally
                    If RadUpload2.InvalidFiles.Count > 0 Then
                        '  ResultLabel.Visible = True
                        ' ResultLabel.Text = GetLocalResourceObject("ResultLabel").ToString()
                        _wronglogo = True
                        'Wizard1.MoveTo(Me.PrintDriverInterfaceStep)
                        ' Wizard1.ActiveStepIndex = 4

                        'Wizard1.ActiveStep.ID = "PrintDriverInterfaceStep"
                    Else
                    End If
                End Try
            End If

        End If

        If Wizard1.ActiveStep.ID = "BillingPackageStep" Then

            Try
                _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                _user = Membership.GetUser(_userName)
                _userProfile = Profile.GetProfile(_userName)
            Catch ex As Exception
                Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                Response.Redirect("~/error_page.aspx")
            End Try

            Dim _storeId As Integer = _userProfile.StoreId

            ' --------------------  '
            ' Commentted temporary  '
            ' --------------------  '

            'If Page.IsValid = True Then

            '    Dim _packageId = CType(Wizard1.FindControl("PackageNameDropDownList"), DropDownList).SelectedValue
            '    Dim _expirationDate As Date

            '    If _packageId = 1 Then ' Package Type is Free
            '        _expirationDate = DateTime.Today.AddDays(30)
            '    ElseIf _packageId = 2 Then
            '        _expirationDate = DateTime.Today.AddDays(90)
            '    Else
            '        _expirationDate = CType("12/31/2999", DateTime)
            '    End If

            '    _userProfile.PackageId = _packageId
            '    _userProfile.ExpirationDate = _expirationDate
            '    _userProfile.Save()

            '    If _packageId <> 1 Then
            '        Dim _userId = Membership.GetUser(_userName).ProviderUserKey
            '        Dim _cardType = CType(Wizard1.FindControl("CardTypeDropDownList"), DropDownList).SelectedValue
            '        Dim _cardNumber = _commonFunctions.Enciper(CType(Wizard1.FindControl("CardNumberTextBox"), TextBox).Text, "qwerty")
            '        Dim _cardHolderName = CType(Wizard1.FindControl("CardHolderNameTextBox"), TextBox).Text
            '        Dim _expMonth = CType(Wizard1.FindControl("MonthDropDownList"), DropDownList).SelectedValue
            '        Dim _expYear = CType(Wizard1.FindControl("YearDropDownList"), DropDownList).SelectedValue
            '        Dim _cvd = CType(Wizard1.FindControl("CVDTextBox"), TextBox).Text
            '        Try
            '            If _webWS.GetCreditCardInformationByUserId(_userId).Tables(0).Rows.Count > 0 Then 'there is credit card record
            '                _webWS.UpdateCreditCardInformation(_userId, _cardType, _cardNumber, _cardHolderName, _expMonth, _expYear, _cvd)
            '            Else ' there is not credit card record
            '                _webWS.InsertCreditCardInformation(_userId, _cardType, _cardNumber, _cardHolderName, _expMonth, _expYear, _cvd)
            '            End If

            '        Catch ex As Exception
            '        End Try
            '    End If

            'End If
            ' -------------------------------------------------------------  '


            ' -------------------------------------------------------------- '
            ' The following is temporal code                                 '
            ' Should be removed after final decision about types of packages '
            ' will be made
            ' -------------------------------------------------------------- '

            ' -------------------------------------------------------------- '
            'Move this part of code to first step

            'If store has domain name delete this Domain name
            Dim _DataSetStoreDomain As New System.Data.DataSet
            _DataSetStoreDomain = _webWS.GetDomainName(_userProfile.StoreId)
            ' if there is a record in the database
            If _DataSetStoreDomain.Tables(0).Rows.Count > 0 Then
                _webWS.DeleteDomainNameByStoreId(_userProfile.StoreId)
            End If
            'If store has Packages delete them and insert new one
            Dim _DataSetStorePackages As New System.Data.DataSet
            _DataSetStorePackages = _webWS.GetStorePackagesByStoreId(_userProfile.StoreId)
            ' if there is a record in the database
            If _DataSetStorePackages.Tables(0).Rows.Count > 0 Then
                _webWS.DeleteStorePackagesByStoreId(_userProfile.StoreId)
            End If

            ' Check Store Domain.
            '
            Dim _isDomainValid As Boolean = True
            If (CustomWebPageModule4CheckBox.Checked) Then
                'Temproraly add checked CheckBoxes for webModule
                TempFTPModule6CheckBox1.Checked = True
                WebPDFModule5CheckBox.Checked = True
                ''
                If (_webWS.IsDomainNameAvailable(DomainNameTextBox.Text.ToLower())) Then
                    Dim _cmsAdapter As CmsAdapter = New CmsAdapter()
                    If DefaultWebContentCheckBox.Checked Then
                        Dim _pageDetails As New PageDetails
                        Dim i As Integer
                        For i = 1 To 3
                            _pageDetails.StoreId = _userProfile.StoreId
                            If i = 1 Then
                                _pageDetails.PageName = Me.GetLocalResourceObject("WebPageName_" & i) & " " & _userProfile.StoreName
                            Else
                                _pageDetails.PageName = Me.GetLocalResourceObject("WebPageName_" & i)
                            End If
                            _pageDetails.PageTitle = Me.GetLocalResourceObject("WebPageTitle_" & i)
                            _pageDetails.PageContent = Me.GetLocalResourceObject("WebPageContent_" & i)
                            If i = 3 Then
                                _pageDetails.PageContent = _pageDetails.PageContent & _
                                    "<p><b>" & Me.GetLocalResourceObject("AddressLabel.Text") & ":</b> " & _
                                    _userProfile.Address & " " & _userProfile.Address1 & _
                                    "<br/>" & _userProfile.City & " " & _userProfile.State & " " & _userProfile.Zip & _
                                    "<br/><b>" & Me.GetLocalResourceObject("PhoneLabel.Text") & ":</b> " & _userProfile.Phone & _
                                    "<br/><b>" & Me.GetLocalResourceObject("FaxLabel.Text") & ":</b> " & _userProfile.Fax & _
                                    "<br/><b>" & Me.GetLocalResourceObject("EmailLabel.Text") & ":</b> " & _user.Email & _
                                    "<br/>" & Me.GetLocalResourceObject("BusinessHours") & "</p>"
                            End If
                            _pageDetails.PageOrder = i
                            _cmsAdapter.InsertPage(_pageDetails)
                        Next
                    End If
                    ' Insert Domain Name to DB.
                    Dim _activationKey As String = (New RandomKeyGenerator()).Generate("abcdefghijklmnopqrstuvwxyz", "0123456789", 15)
                    _webWS.InsertDomainName(_userProfile.StoreId, DomainNameTextBox.Text.ToLower(), DefaultWebContentCheckBox.Checked, False, _activationKey, True, True)
                    
					'Dim _amazingPrintAdapter As New com.racadtech.Framework.Modules.AmazingPrint.AmazingPrintAdapter()
                    'Dim _sitename As String = DomainNameTextBox.Text.ToLower() & ".ecardbuilder.com"
                    'Dim _email As String = _user.Email
                    'Dim _password As String = (New RandomKeyGenerator()).Generate("abcdefghijklmnopqrstuvwxyz", "0123456789", 8)
                    'Dim _firstName As String = _userProfile.FName
                    'Dim _lastName As String = _userProfile.LName
                    'Dim _address As String = _userProfile.Address & " " & _userProfile.Address1
                    'Dim _city As String = _userProfile.City
                    'Dim _state As String = _userProfile.State
                    'Dim _zip As String = _userProfile.Zip
                    'Dim _country As String = _userProfile.Country
                    'Dim _fax As String = _userProfile.Fax
                    'Dim _phone As String = _userProfile.Phone
                    'Dim _siteId As Integer = _amazingPrintAdapter.CreateWebSite(_sitename, _email, _password, _firstName, _lastName, _address, _city, _state, _zip, _country, _fax, _phone)
                    'If _siteId > 0 Then
                    '    _cmsAdapter.InsertECardBuilder(_userProfile.StoreId, _siteId, True, "http://" & _sitename, _password, _siteId)
                    '    Dim _result As Integer = _amazingPrintAdapter.SetHomePageUrl(_siteId, "http://" & _sitename)
                        ' TODO : Store  _result in database
                   '     _result = _amazingPrintAdapter.SetReturnUrl(_siteId, "http://" & _sitename)
                        ' TODO : Store  _result in database
                    '    _result = _amazingPrintAdapter.SetHeaderVisibility(_siteId, 0)
                        ' TODO : Store  _result in database
                    'Else
                    '    If _siteId = -2 Then _cmsAdapter.InsertECardBuilder(_userProfile.StoreId, _siteId, True, "http://" & _sitename, _password, "Result: " & _siteId & " - Website name is not available.")
                    '    If _siteId = -3 Then _cmsAdapter.InsertECardBuilder(_userProfile.StoreId, _siteId, True, "http://" & _sitename, _password, "Result: " & _siteId & " - Create website failed.")
                    '    If _siteId = -4 Then _cmsAdapter.InsertECardBuilder(_userProfile.StoreId, _siteId, True, "http://" & _sitename, _password, "Result: " & _siteId & " - Set contact Information failed.")
                    '    If _siteId = -5 Then _cmsAdapter.InsertECardBuilder(_userProfile.StoreId, _siteId, True, "http://" & _sitename, _password, "Result: " & _siteId & " - Set website status failed.")
                    'End If
                Else
                    Me._wrongDomain = True
                End If
            End If

            ' Define Session Variable ( UseFTP = False , If Temporary or Permanent FTP where selected. )
            If TempFTPModule6CheckBox1.Checked Then
                Me._useFTP = False
            Else
                Me._useFTP = True
            End If

            If Me._wrongDomain = False Then
                ' Insert Store Packages to DB ( If CheckBox.Checked = true ) .
                Dim _endPackageDate As Date = New Date(2099, 12, 31)
                _webWS.InsertStorePackages(_userProfile.StoreId, GetBasePackageId(), 1, _user.CreationDate, _endPackageDate)
                InsertStorePackages(2, 5, DesktopDragDropModule2CheckBox)
                InsertStorePackages(4, 6, CustomWebPageModule4CheckBox)
                InsertStorePackages(5, 7, WebPDFModule5CheckBox)
                InsertStorePackages(6, 8, TempFTPModule6CheckBox1)

                Dim _expirationDate As Date
                '_expirationDate = DateTime.Today.AddDays(30)
                '_userProfile.PackageId = _packageId
                '_expirationDate = New Date(2009, 3, 31)
                _expirationDate = DateTime.Today.AddDays(30)
                _userProfile.ExpirationDate = _expirationDate
                '_userProfile.StartBillingDate = New Date(2009, 4, 1) 'Format(DateTime.Today.AddDays(31), "MM/dd/yyyy")
                _userProfile.StartBillingDate = DateTime.Today.AddDays(31)
                _userProfile.PaymentTypeId = 1
                _userProfile.Save()

            End If


            Try
                Dim _userId As Guid = _user.ProviderUserKey
                _webWS.InsertStartBillingDate(_userId, DateTime.Today.AddDays(31), False)
            Catch ex As Exception
            End Try
            ' -------------------------------------------------------------- '
        End If

        If Wizard1.ActiveStep.ID = "GeneratePrintDriver" Then

            Try
                _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                _user = Membership.GetUser(_userName)
                _userProfile = Profile.GetProfile(_userName)
            Catch ex As Exception
                Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                Response.Redirect("~/error_page.aspx")
            End Try

            ' Company Name = Print Driver Name

            ticket = printItInstallerService.CreateTicket(CType(Wizard1.WizardSteps(6).FindControl("StoreIdHiddenField"), HiddenField).Value, _
                                            CType(Wizard1.WizardSteps(6).FindControl("ActivationIdHiddenField"), HiddenField).Value, _
                                            CType(Wizard1.WizardSteps(6).FindControl("PrintDriverNameTextField"), TextBox).Text, _
                                            CType(Wizard1.WizardSteps(6).FindControl("PrintDriverNameTextField"), TextBox).Text, _
                                            "PrintIt", _
                                            "f")

            Session("PrintItInstaller_TicketId") = ticket.TicketId
            Session("PrintItInstaller_StoreId") = ticket.StoreId
            Session("PrintItInstaller_ActivationId") = ticket.ActivationId
            Session("PrintItInstaller_PrinterName") = ticket.PrinterName
            Session("PrintItInstaller_CompanyName") = ticket.CompanyName
            Session("PrintItInstaller_CompanyNameShort") = ticket.CompanyNameShort
            Session("PrintItInstaller_IsSDCIntegrated") = ticket.IsSDCIntegrated
            Session("PrintItInstaller_WindowsDriverLocation") = ticket.WindowsDriverLocation
            Session("PrintItInstaller_MacDriverLocation") = ticket.MacDriverLocation
            Session("PrintItInstaller_QueuePosition") = ticket.QueuePosition
            Session("PrintItInstaller_IsComplete") = ticket.IsComplete

            ' Response.Redirect("~/generate_print_driver_step2.aspx")
            '----

            ' Send User email about successful registration and Print Driver creating

            Dim _from As String = "support@goprint2.com"
            Dim _to As String = Membership.GetUser(_userName).Email
            Dim _toProduction As String = CType(Wizard1.WizardSteps(5).FindControl("SubSetEmailTextBox"), TextBox).Text
            Dim _toHeadOffice As String = "bizdev@goepower.com"
            Dim _toSupport As String = "ney@racadtech.com"
            Dim _UKOffice As String = "neilb@transeomedia.com"
            Dim _sendUKOfficeEmail As Boolean = False
            If (_userProfile.Country.Equals("United Kingdom") Or _userProfile.Country.Equals("Scotland") Or _userProfile.Country.Equals("Ireland")) Then
                _sendUKOfficeEmail = True
            End If

            '_to = "maria@edeninteractive.com"
            Dim _subject As String = GetLocalResourceObject("RegistrationEmailSubject")
            Dim _body As String
            _body = GetLocalResourceObject("RegistrationEmailBody_Par_1") & _userProfile.FName & ", <br/><br/>" & _
            GetLocalResourceObject("RegistrationEmailBody_Par_4") & "<br/><br/>"
            'List of the Stores Module
            Dim _datasetModules As System.Data.DataSet
            Dim _boolModules As Boolean = False
            _datasetModules = _webWS.GetStorePackagesByStoreId(_userProfile.StoreId)
            If _datasetModules.Tables(0).Rows.Count > 0 Then
                _boolModules = True

                For i As Integer = 0 To _datasetModules.Tables(0).Rows.Count - 1
                    'add list of the Module for current Store according language
                    _body = _body & _datasetModules.Tables(0).Rows(i).Item("ModuleName").ToString() & "<br/>"
                Next i
                _body = _body & "<br/>"
            End If
            _body = _body & GetLocalResourceObject("RegistrationEmailBody_Par_2") & "<br/><br/>" & _
                   "<table border='0' cellspacing='10' cellpadding='10'><tr>" & _
                   "<td><a href='http://www.goprint2.com/downloadPD.aspx?s=" & _userProfile.StoreId & "&p=w'>" & _
                   GetLocalResourceObject("RegistrationEmailBody_WinPD_Download") & "</a></td>" & _
                   "<td><a href='http://www.goprint2.com/downloadPD.aspx?s=" & _userProfile.StoreId & "&p=m'>" & _
                   GetLocalResourceObject("RegistrationEmailBody_MacPD_Download") & "</a></td>" & _
                   "</tr></table>"
            'create register e-mail according current packages
            If _boolModules = True Then
                Dim _ModuleAvailable As Boolean
                For i As Integer = 2 To 6
                    If i = 3 Then i = 4
                    _ModuleAvailable = _webWS.IsPackageAvailableByStoreId(_userProfile.StoreId, i)
                    If _ModuleAvailable = True Then
                        Dim j As Integer = i + 2
                        If i = 2 Then j = j + 1
                        _body = _body & GetLocalResourceObject("RegistrationEmailBody_Par_" & j) & "<br/><br/>"
                        'if current module should have domain name, so check and create link
                        If i = 4 Then
                            Dim _dataSetDomain As System.Data.DataSet
                            _dataSetDomain = _webWS.GetDomainName(_userProfile.StoreId)
                            If _dataSetDomain.Tables(0).Rows.Count > 0 Then
                                _body = _body & _
                                "<a href='http://" & _dataSetDomain.Tables(0).Rows(0).Item("DomainName").ToString() & ".goprint2.com'>" & _
                                _dataSetDomain.Tables(0).Rows(0).Item("DomainName").ToString() & ".goprint2.com</a><br/><br/>" & _
                                GetLocalResourceObject("ActivationEmailBody") & "<a href='http://www.goprint2.com/domain_activation.aspx?key=" & _webWS.GetDomainName(_userProfile.StoreId).Tables(0).Rows(0).Item("ActivationKey") & "'>http://www.goprint2.com/domain_activation.aspx?key=" & _webWS.GetDomainName(_userProfile.StoreId).Tables(0).Rows(0).Item("ActivationKey") & "</a><br/><br/>"
                            End If
                        End If
                    End If
                Next i
            End If
            _body = _body & GetLocalResourceObject("RegistrationEmailBody_Par_9") & " " & _
                        Format(Now.AddDays(30), "dd/MMM/yyyy") & _
                        " " & GetLocalResourceObject("RegistrationEmailBody_Par_10") & "<br/><br/>" & _
                    GetLocalResourceObject("RegistrationEmailBody_Par_3")
            Try
                com.racadtech.Framework.Util.Mail.SMTPClient.sendMail(New String() {_to, _toProduction, _toHeadOffice, _toSupport}, _
                                                                      _subject, _body, True, _from)
                If (_sendUKOfficeEmail) Then
                    com.racadtech.Framework.Util.Mail.SMTPClient.sendMail(New String() {_UKOffice}, _subject, _body, True, _from)
                End If

            Catch ex As Exception
            End Try



            '_to = "bizdev@goepower.com"

            'Try
            '    com.racadtech.Framework.Util.Mail.SMTPClient.sendMail(New String() {_to}, _
            '                                                                          _subject, _body, True, _from)
            'Catch ex As Exception
            'End Try



        End If
    End Sub


    Protected Sub Wizard1_ActiveStepChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Wizard1.ActiveStepChanged
        If _wronglogo = True Then
            'Wizard1.ActiveStep.ID = "PrintDriverInterfaceStep"
            'Wizard1.ActiveStepIndex = 4
            Wizard1.MoveTo(Me.PrintDriverInterfaceStep)
        End If

        If _wrongDomain = True Then
            DomainErrorLabel.Visible = True
            Wizard1.MoveTo(Me.BillingPackageStep)
        End If

        If _useFTP = False Then
            Me.FtpSettingsPanel.Visible = False
        Else
            Me.FtpSettingsPanel.Visible = True
        End If

        If Wizard1.ActiveStep.ID = "BillingPackageStep" Then
            Try
                _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                _user = Membership.GetUser(_userName)
                _userProfile = Profile.GetProfile(_userName)
            Catch ex As Exception
                Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                Response.Redirect("~/error_page.aspx")
            End Try

            Dim _packageId As Integer = 0

            _packageId = GetBasePackageId()

            PopulatePackageDDL(Me.PackageTypeDropDownList)

            Dim i As Integer = 1
            Select Case _userProfile.Country ' curruncy should be change according the Country not language
                Case "Argentina", "Uruguay"
                    GenerateMoneyLabel("u$s")
                Case "Canada"
                    GenerateMoneyLabel("CAD")
                Case "United Kingdom", "Scotland", "Ireland"
                    GenerateMoneyLabel("GBP")
                Case Else
                    GenerateMoneyLabel("USD")
            End Select

            Dim _ModuleId As Integer = 0
            Try
                Dim _dataSet As New System.Data.DataSet
                _dataSet = _webWS.GetPackageInformationByPackageId(_packageId, Session("lang"))
                'PackageIdHiddenField.Value = _packageId

                _ModuleId = _dataSet.Tables(0).Rows(0).Item("ModuleId")
                Dim _dataSetModule As New System.Data.DataSet
                _dataSetModule = _webWS.GetModuleInformationByModuleId(_ModuleId, Session("lang"))
                PrintDriverModule1Label.Text = _dataSetModule.Tables(0).Rows(0).Item("ModuleName")
                'PackageTypeValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("PackageName")
                PackageDescriptionValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("PackageDescription")
                'Dim _maxClicks As Integer = _dataSet.Tables(0).Rows(0).Item("MaxClicksPerMonth")
                'If _maxClicks = 0 Then
                '    MaxClicksValueLabel.Text = "Unlimitted"
                'Else
                '    MaxClicksValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("MaxClicksPerMonth")
                'End If
                SetupFeeValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("PackagePrice")) 'change SetUp Fee on Monthly Price                
                SupportFeeValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("YearlyPrice"))
                If _dataSet.Tables(0).Rows(0).Item("PrePaidClicks") = 0 Then
                    FreeJobsSubmissionsValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("FreeJobDescription")
                Else
                    FreeJobsSubmissionsValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("PrePaidClicks")
                End If
                PricePerSubmissionValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("PricePerClick"))
                MaxMonthlyFeeValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("MaxMonthlyFee"))
                MaxMonthlyFeeJS = MaxMonthlyFeeValueLabel.Text

                ' Update Lower Total Payments Panel.
                TotalMonthlyFeeValueLabel.Text = SetupFeeValueLabel.Text
                TotalPricePerSubmissionValueLabel.Text = PricePerSubmissionValueLabel.Text
                If (MaxMonthlyFeeValueLabel.Text.Equals("0.00")) Then
                    MaximumMonthlyFeeUpdateLabel.Visible = False
                    MaximumMonthlyFeeValueLabel.Visible = False
                Else
                    MaximumMonthlyFeeValueLabel.Text = MaxMonthlyFeeValueLabel.Text
                End If
                HiddenTotalMonthlyLabel.InnerHtml = "<script type='text/javascript'>window.onload = CustomWebPageModule('','')</script>"
            Catch ex As Exception
                Response.Write(ex.Message)
            End Try
            GenerateModuleLabel(2, 5, DesktopDragDropModule2Label, Module2MonthlyFeeValueLabel)
            GenerateModuleLabel(4, 6, CustomWebPageModule4Label, Module4MonthlyFeeValueLabel)
            GenerateModuleLabel(5, 7, WebPDFModule5Label, Module5MonthlyFeeValueLabel)
            GenerateModuleLabel(6, 8, TempFTPModule6Label, Module6MonthlyFeeValueLabel)
        End If

        If Wizard1.ActiveStep.ID = "PrintDriverInterfaceStep" Then

            If _wronglogo Then
                ResultLabel.Text = GetLocalResourceObject("ResultLabel").ToString()
                ResultLabel.Visible = True
            Else
                ResultLabel.Visible = False
                _wronglogo = False

                Try
                    _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                    _user = Membership.GetUser(_userName)
                    _userProfile = Profile.GetProfile(_userName)
                Catch ex As Exception
                    Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                    Response.Redirect("~/error_page.aspx")
                End Try

                FrameTitleTextBox.Text = _userProfile.StoreName & " " & "Job Submission"
                'FrameTitleTextBox.Text = CType(Wizard1.WizardSteps(1).FindControl("StoreNameTextBox"), TextBox).Text & " " & "Job Submission"

                CompanyNameTextBox.Text = _userProfile.StoreName
                'CompanyNameTextBox.Text = CType(Wizard1.WizardSteps(1).FindControl("StoreNameTextBox"), TextBox).Text

                If _userProfile.Address1 <> "--" Then
                    CompanyAddressTextBox.Text = _userProfile.Address & ", " & _userProfile.Address1
                Else
                    CompanyAddressTextBox.Text = _userProfile.Address
                End If
                'If CType(Wizard1.WizardSteps(1).FindControl("AddressTextBox1"), TextBox).Text <> "" Then
                '    CompanyAddressTextBox.Text = CType(Wizard1.WizardSteps(1).FindControl("AddressTextBox"), TextBox).Text & ", " & _
                '                                 CType(Wizard1.WizardSteps(1).FindControl("AddressTextBox1"), TextBox).Text
                'Else
                '    CompanyAddressTextBox.Text = CType(Wizard1.WizardSteps(1).FindControl("AddressTextBox"), TextBox).Text
                'End If
                CompanyPhoneTextBox.Text = _userProfile.Phone
                'If PhoneTr.Visible = True Then
                '    CompanyPhoneTextBox.Text = CType(Wizard1.WizardSteps(1).FindControl("PhoneTextBox1"), TextBox).Text & CType(Wizard1.WizardSteps(1).FindControl("PhoneTextBox2"), TextBox).Text & CType(Wizard1.WizardSteps(1).FindControl("PhoneTextBox3"), TextBox).Text
                'Else
                '    CompanyPhoneTextBox.Text = CType(Wizard1.WizardSteps(1).FindControl("PhoneTextBoxAlt"), TextBox).Text
                'End If
                CompanyEmailTextBox.Text = CType(Wizard1.WizardSteps(0).FindControl("EmailTextBox"), TextBox).Text
            End If
        End If

        If Wizard1.ActiveStep.ID = "GeneratePrintDriver" Then
            If _wronglogo = True Then
                Wizard1.ActiveStep.ID = "PrintDriverInterfaceStep"
            Else
                Try
                    _userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
                    _user = Membership.GetUser(_userName)
                    _userProfile = Profile.GetProfile(_userName)
                Catch ex As Exception
                    Session("ErrorMessage") = GetLocalResourceObject("ErrSessionExpired")
                    Response.Redirect("~/error_page.aspx")
                End Try

                Me.StoreIdHiddenField.Value = _userProfile.StoreId
                Me.ActivationIdHiddenField.Value = _webWS.GetActivationDataSetByUserId(_user.ProviderUserKey).Tables(0).Rows(0).Item("ActivationId").ToString()
            End If
        End If

        If Wizard1.ActiveStep.ID = "PrintDriverInterface" Then

            '_userName = CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text
            '_user = Membership.GetUser(_userName)
            '_userProfile = Profile.GetProfile(_user.UserName)

            ''commented just for testing purposes
            ''Dim _directory = ConfigurationManager.AppSettings("PrintItStoreDataPath") & "\" & _userProfile.StoreId

            'Dim _directory = "c:\temp\" & _userProfile.StoreId

            'Dim _imageSource As String = ""

            'If System.IO.Directory.Exists(_directory) = True Then
            '    'find file with name "logo" and any extension
            '    Try
            '        Dim _logoFile As String
            '        For Each _logoFile In System.IO.Directory.GetFiles(_directory)
            '            If (_logoFile.StartsWith(_directory & "\logo")) Then
            '                'logFile.WriteLine("[Removing] " & _logoFile)
            '                _imageSource = _commonFunctions.GetDocumentName(_logoFile, True, "\\")
            '            End If
            '        Next _logoFile
            '    Catch ex As Exception
            '        'logFile.WriteLine("[EXCEPTION] " & ex.Message)
            '    Finally
            '        'logFile.Close()
            '        'logFile.Dispose()
            '    End Try

            'End If

            'If _imageSource <> "" Then
            '    LogoImage.ImageUrl = _imageSource
            'End If

        End If


        'Block WizardStep when user creates PrintDriver
        If Wizard1.ActiveStep.ID = "CompleteRegistrationStep" Then

            Dim i As Integer
            For i = 0 To Wizard1.ActiveStepIndex - 1
                Wizard1.WizardSteps(i).AllowReturn = False
            Next
        End If

    End Sub

    'Protected Sub UploadLogoLinkButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UploadLogoLinkButton.Click
    '    Session("FrameTitleTemp") = FrameTitleTextBox.Text
    '    Session("ThankYouMessageTemp") = ThankYouMessageTextBox.Text
    '    Session("CompanyNameTemp") = CompanyNameTextBox.Text
    '    Session("CompanyAddressTemp") = CompanyAddressTextBox.Text
    '    Session("CompanyPhoneTemp") = CompanyPhoneTextBox.Text
    '    Session("CompanyEmailTemp") = CompanyEmailTextBox.Text
    '    Session("ThemeTemp") = ThemeDropDownList.SelectedValue

    '    Session("FromWizard") = True
    '    Session("UserFromWizard") = Membership.GetUser(CType(Wizard1.WizardSteps(0).FindControl("UserNameTextBox"), TextBox).Text)

    '    '        InitiatorLabel.Text = "<script language='javascript'> window.onload = function(){window.radopen('includes/upload_logo.aspx', 'UploadLogoWindow');}</script>"
    '    InitiatorLabel.Text = "<script language='javascript'> window.onload = function(){window.open('includes/upload_logo.aspx', 'MyWindow', 'location=1,status=0,scrollbars=0, width=400,height=150');}</script>"

    'End Sub

    'Protected Sub CountryRadComboBox_SelectedIndexChanged(ByVal o As Object, ByVal e As Telerik.WebControls.RadComboBoxSelectedIndexChangedEventArgs) Handles CountryRadComboBox.SelectedIndexChanged
    '    Dim _state As RadComboBox = CType(Wizard1.FindControl("StateRadComboBox"), RadComboBox)
    '    Dim _zip As TextBox = CType(Wizard1.FindControl("ZipTextBox"), TextBox)

    '    If CountryRadComboBox.SelectedValue = "3" Then
    '        StateTr.Visible = False
    '        ZipTr.Visible = False
    '        _zip.Text = Nothing
    '        '_state.Enabled = False
    '        '_zip.Enabled = False
    '    Else
    '        StateTr.Visible = True
    '        ZipTr.Visible = True

    '        '_state.Enabled = True
    '        '_zip.Enabled = True
    '    End If


    '    If CountryRadComboBox.SelectedValue = "1" Then
    '        ZipRegularExpressionValidator.ValidationExpression = "^[\w\d\s]{7}$"
    '        _zip.MaxLength = 7
    '    End If
    '    If CountryRadComboBox.SelectedValue = "2" Then
    '        ZipRegularExpressionValidator.ValidationExpression = "^[\d]{5}$"
    '        _zip.MaxLength = 5
    '    End If
    'End Sub

    Protected Sub CountryDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CountryDropDownList.SelectedIndexChanged
        Dim _state As DropDownList = CType(Wizard1.FindControl("StateDropDownList"), DropDownList)
        Dim _zip As TextBox


        If CountryDropDownList.Items.Item(0).Selected = True Then
            _zip = CType(Wizard1.FindControl("ZipTextBox"), TextBox)

            StateTr.Visible = False
            ZipTr.Visible = False
            StateTrAlt.Visible = False
            ZipTrAlt.Visible = False
            _zip.Text = Nothing

        ElseIf CountryDropDownList.SelectedItem.Text = "Canada" Or CountryDropDownList.SelectedItem.Text = "USA" Then

            StateDropDownList.Items.Clear()
            PopulateStateDDL(StateDropDownList, GetLocalResourceObject("SelectState"), GetLocalResourceObject("SelectState"), CountryDropDownList.SelectedValue)

            _zip = CType(Wizard1.FindControl("ZipTextBox"), TextBox)

            StateTr.Visible = True
            ZipTr.Visible = True
            PhoneTr.Visible = True
            FaxTr.Visible = True

            StateTrAlt.Visible = False
            ZipTrAlt.Visible = False
            PhoneTrAlt.Visible = False
            FaxTrAlt.Visible = False

            If CountryDropDownList.SelectedValue = "1" Then
                ZipRegularExpressionValidator.ValidationExpression = "^[\w\d\s]{6,7}$"
                _zip.MaxLength = 7
            End If
            If CountryDropDownList.SelectedValue = "2" Then
                ZipRegularExpressionValidator.ValidationExpression = "^[\d]{5}$"
                _zip.MaxLength = 5
            End If

        Else

            StateTr.Visible = False
            ZipTr.Visible = False
            PhoneTr.Visible = False
            FaxTr.Visible = False

            StateTrAlt.Visible = True
            ZipTrAlt.Visible = True
            PhoneTrAlt.Visible = True
            FaxTrAlt.Visible = True

        End If

    End Sub

    Protected Sub PackageTypeDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles PackageTypeDropDownList.SelectedIndexChanged

        Dim _ModuleId As Integer = 0
        Try
            Dim _packageId As Integer = PackageTypeDropDownList.SelectedValue
            Dim _dataSet As New System.Data.DataSet
            _dataSet = _webWS.GetPackageInformationByPackageId(_packageId, Session("lang"))
            'PackageIdHiddenField.Value = _packageId

            _ModuleId = _dataSet.Tables(0).Rows(0).Item("ModuleId")
            Dim _dataSetModule As New System.Data.DataSet
            _dataSetModule = _webWS.GetModuleInformationByModuleId(_ModuleId, Session("lang"))
            PrintDriverModule1Label.Text = _dataSetModule.Tables(0).Rows(0).Item("ModuleName")
            'PackageTypeValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("PackageName")
            PackageDescriptionValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("PackageDescription")
            'Dim _maxClicks As Integer = _dataSet.Tables(0).Rows(0).Item("MaxClicksPerMonth")
            'If _maxClicks = 0 Then
            '    MaxClicksValueLabel.Text = "Unlimited"
            'Else
            '    MaxClicksValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("MaxClicksPerMonth")
            'End If
            SetupFeeValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("PackagePrice")) 'change SetUp Fee on Monthly Price                
            SupportFeeValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("YearlyPrice"))
            If _dataSet.Tables(0).Rows(0).Item("PrePaidClicks") = 0 Then
                FreeJobsSubmissionsValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("FreeJobDescription")
            Else
                FreeJobsSubmissionsValueLabel.Text = _dataSet.Tables(0).Rows(0).Item("PrePaidClicks")
            End If
            PricePerSubmissionValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("PricePerClick"))
            MaxMonthlyFeeValueLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("MaxMonthlyFee"))
            MaxMonthlyFeeJS = MaxMonthlyFeeValueLabel.Text

            ' Update Lower Total Payments Panel.
            TotalMonthlyFeeValueLabel.Text = SetupFeeValueLabel.Text
            TotalPricePerSubmissionValueLabel.Text = PricePerSubmissionValueLabel.Text
            If (MaxMonthlyFeeValueLabel.Text.Equals("0.00")) Then
                MaximumMonthlyFeeUpdateLabel.Visible = False
                MaximumMonthlyFeeValueLabel.Visible = False
            Else
                MaximumMonthlyFeeValueLabel.Text = MaxMonthlyFeeValueLabel.Text
            End If
            HiddenTotalMonthlyLabel.InnerHtml = "<script type='text/javascript'>window.onload = CustomWebPageModule('','')</script>"
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
        GenerateModuleLabel(2, 5, DesktopDragDropModule2Label, Module2MonthlyFeeValueLabel)
        GenerateModuleLabel(4, 6, CustomWebPageModule4Label, Module4MonthlyFeeValueLabel)
        GenerateModuleLabel(5, 7, WebPDFModule5Label, Module5MonthlyFeeValueLabel)
        GenerateModuleLabel(6, 8, TempFTPModule6Label, Module6MonthlyFeeValueLabel)

    End Sub




    Private Sub GenerateMoneyLabel(ByVal currency As String)
        Dim i As Integer = 1
        For i = 1 To 8
            Dim lbl As Label = Wizard1.FindControl("MoneySignLabel_" & i)
            lbl.Text = currency
        Next
    End Sub

    Private Sub GenerateModuleLabel(ByVal moduleId As Integer, ByVal packageId As Integer, ByVal moduleLabel As Label, ByVal monthlyLabel As Label)
        Dim _dataSet As New System.Data.DataSet
        _dataSet = _webWS.GetModuleInformationByModuleId(moduleId, Session("lang"))
        moduleLabel.Text = _dataSet.Tables(0).Rows(0).Item("ModuleName")

        _dataSet = _webWS.GetPackageInformationByPackageId(packageId, Session("lang"))
        monthlyLabel.Text = String.Format("{0:n}", _dataSet.Tables(0).Rows(0).Item("PackagePrice")) 'change SetUp Fee on Monthly Price
    End Sub

    Private Sub InsertStorePackages(ByVal moduleId As Integer, ByVal packageId As Integer, ByVal checkBox As CheckBox)
        If (checkBox.Checked) Then
            Dim _endPackageDate As Date = New Date(2099, 12, 31)
            _webWS.InsertStorePackages(_userProfile.StoreId, packageId, moduleId, _user.CreationDate, _endPackageDate)
        End If
    End Sub

    Private Function GetBasePackageId() As Integer
        Dim _packageId As Integer = 1
        If PackageTypeDropDownList.SelectedValue.ToString <> "" Then
            _packageId = PackageTypeDropDownList.SelectedValue
        Else
            If _userProfile.Country = "Argentina" Or _userProfile.Country = "Uruguay" Then
                MonthlyFee.Visible = True
                If _userProfile.PressTypeId = 1 Then
                    _packageId = 2
                ElseIf _userProfile.PressTypeId = 2 Then
                    _packageId = 3
                Else ' PressTypeId=3
                    _packageId = 4
                End If
            End If

            If (_userProfile.Country.Equals("United Kingdom") Or _userProfile.Country.Equals("Scotland") Or _userProfile.Country.Equals("Ireland")) Then
                _packageId = 20
            Else
                _packageId = 17
            End If
        End If

        Return _packageId
    End Function

    'Protected Sub StoreTypeDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles StoreTypeDropDownList.SelectedIndexChanged
    '    If StoreTypeDropDownList.SelectedValue = "Other" Then
    '        StoreTypeTextBox.Visible = True
    '    Else
    '        StoreTypeTextBox.Visible = False
    '    End If
    'End Sub
 

   
    Protected Sub CustomWebPageModule4CheckBox_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CustomWebPageModule4CheckBox.CheckedChanged
        If CustomWebPageModule4CheckBox.Checked = True Then
            WebPDFModule5CheckBox.Checked = True
            TempFTPModule6CheckBox1.Checked = True
        Else
            WebPDFModule5CheckBox.Checked = False
            TempFTPModule6CheckBox1.Checked = False
        End If
    End Sub

    Public Function GetModuleDescription(ByVal moduleId As String) As String
        Return _webWS.GetModuleDescription(moduleId, Session("lang").ToString())
    End Function

    Public Function GetDefaultWebContentDescription() As String
        Return Me.GetLocalResourceObject("GetDefaultWebContentDescription")
    End Function

    Public Function GetEmailTextBox() As String
        Return Me.GetLocalResourceObject("EmailTextBox")
    End Function


End Class
