************************************************************************
*PROCEDURE wwDevelopers
****************************
***  Function: Processes incoming Web Requests for wwDevelopers
***            requests. This function is called from the wwServer 
***            process.
***      Pass: loServer -   wwServer object reference
*************************************************************************
LPARAMETER loServer
LOCAL loProcess

*** Set these for Demo or West Wind Site deployment
#DEFINE WCDEMOVERSION .F.
#DEFINE WWDEV_USE_SQL_TABLES .T.


*** Class used for customer - switches between demo
*** and West Wind Web site which uses wwStore customer objects
#IF WCDEMOVERSION
   #INCLUDE WCONNECT.H
   #DEFINE WWC_CUSTOMERCLASS   wwDevCustomer
#ELSE
   #INCLUDE WWSTORE.h
   #DEFINE WWC_CUSTOMERCLASS   cCustomer
#ENDIF   

loProcess=CREATE("wwDevelopers",loServer)
loProcess.lShowRequestData = loServer.lShowRequestData

IF VARTYPE(loProcess)#"O"
   *** All we can do is return...
   WAIT WINDOW NOWAIT "Unable to create Process object..."
   RETURN .F.
ENDIF

*** Call the Process Method that handles the request
loProcess.Process()

RETURN

***********************************************************
DEFINE CLASS wwDevelopers AS WWC_PROCESS
*************************************************************
cNextMethod = ""


*********************************************************************
* Function wwDevelopers :: Process
************************************
*** If you need to hook up generic functionality that occurs on
*** every hit, implement this method then call DoDefault() to
*** get the default Request Processing functionality. See docs
*** for more info on how to customize wwProcess::Process behavior.
*********************************************************************
FUNCTION Process

Request = THIS.oRequest
Response = THIS.oResponse

*** NOTE: Create PRIVATE CONFIG object for easy access to config
***       vars stored in the app INI file.
PRIVATE CONFIG 
Config = THIS.oServer.oConfig.owwDevRegistry

IF wwVFPVersion < 7
   THIS.ErrorMsg("The Developer Registry requires VFP 7",;
                 "Check out the online version at:<p>" +;
                 [<a href="http://www.west-wind.com/wwDevRegistry">http://www.west-wind.com/wwDevRegistry</a>])
   RETURN                 
ENDIF


THIS.InitSession(Config.cCookiename,3600,.t.)

DODEFAULT()

RETURN .T.
ENDFUNC

************************************************************************
* wwDevelopers :: Default
****************************************
***  Function: Default page shows the Developer listing and search
***			   This view handles both display and searching. The
***			   search functionality is provided via the SearchDeveloper
***			   method provided below.
************************************************************************
FUNCTION Default
LOCAL loSc as wwShowCursor, loDev as wwDevRegistry
PRIVATE pcDeveloperList as String

oCustomer = CREATE([WWC_CUSTOMERCLASS])
#IF WWDEV_USE_SQL_TABLES
oCustomer.SetSQLObject(Server.owwStoreSQL)
#ENDIF

*** See if we can reattach to our profile/customer
IF oCustomer.FindByUserID(Session.cSessionId)
   Session.SetSessionVar("CustomerPK",TRANS(oCustomer.oData.pk))
   pcWelcome = "<b>Welcome back, " + TRIM(oCustomer.oData.FirstName) + ".</b>"	   
ELSE
   pcWelcome = ""
   oCustomer.GetBlankRecord()
   Session.TimeoutSessions()
ENDIF   
Session.SetSessionVar("CookiesOn","True")


*** Object that'll hold the search vars as properties
*** PRIVATE so it's visible to the external template
PRIVATE poQuery
poQuery = CREATEOBJECT("Relation")
poQuery.AddProperty("DevName","")
poQuery.AddProperty("Company","")
poQuery.AddProperty("City","")
poQuery.AddProperty("State","")
poQuery.AddProperty("Zip","")
poQuery.AddProperty("Zip2","")
poQuery.AddProperty("Country","United States")
poQuery.AddProperty("Sortby",1)
poQuery.AddProperty("Dev",0)
poQuery.AddProperty("Training",0)
poQuery.AddProperty("Support",0)

*** Collect all the form vars into this object
Request.FormVarsToObject(poQuery,"txt")


IF poQuery.SortBy = 1
   lcOrder = "Company"
ELSE
   lcOrder = "Country,State,City"
ENDIF

loDev = CREATEOBJECT("wwDevRegistry")

loXML = CREATEOBJECT("wwXML")
IF EMPTY(Request.Form("btnSubmit"))
   lcXML = Session.GetSessionVar("poQuery")

   IF !EMPTY(lcXML)
      *** Load poQuery from the stored data of the last query
      loXML.XMLToObject(lcXML,poQuery)
   ENDIF
ELSE
   Session.SetSessionVar("poQuery",loXML.ObjectToXML(poQuery))
ENDIF

IF Request.QueryString("Type") = "YourEntries"
   loDev.cSQLcursor = "TDevelopers"
   loDev.Query("select pk,company,name,state,city,country From " + loDev.cFileName +;
               " where CustPK=" + TRANSFORM(oCustomer.oData.pk) )

   *** Post process for links
   SELECT [<a href="Editdeveloper.wwr?Id=] + TRANSFORM(pk) + [">] + Company  + [</a>] as Company, ;
          Name as Contact, State, City, Country ;
          FROM TDevelopers ;
      INTO CURSOR TQuery
ELSE
   loDev.DeveloperListQuery(poQuery.Company,poQuery.DevName,;
                                     poQuery.City,poQuery.State,;
                                     poQuery.Zip,poQuery.Zip2,;
                                     poQuery.Country,;
                                     poQuery.Dev,poQuery.Support,poQuery.Training,;
                                     lcOrder)
   *** Post process for links
   SELECT [<a href="Showdeveloper.wwr?Id=] + TRANSFORM(pk) + [">] + Company  + [</a>] as Company, ;
          Name as Contact, State, City, Country ;
          FROM TDevelopers ;
      INTO CURSOR TQuery

ENDIF
                                  

loSC = CREATEOBJECT("wwShowCursor")
loSC.lAlternateRows = .T.
loSC.cExtraTableTags = " style='font:normal normal 8pt tahoma'"

loSC.nPage_itemsPerpage = 15
loSc.cPage_PageUrl = "Default.wwr?"

loSC.ShowCursor()
pcDeveloperList = loSC.GetOutput()

IF RECCOUNT() = 0
  pcDeveloperList = pcDeveloperList + ;
    "<p><center><b style='color:darkred'>No entries matched your search</b></center></p>"
ENDIF

Response.ExpandTemplate( Server.oConfig.owwDevRegistry.cHTMLPagePath + "default.wwr" )
RETURN

*** Parses the query parameters, runs the query and returns a cursor
THIS.SearchDevelopers(oCustomer)

loSC = CREATEOBJECT("wwShowCursor")
loSC.lAlterNATEROWS = .T.
loSC.cExtraTableTags = " style='font:normal normal 8pt tahoma'"
loSC.ShowCursor()
pcDeveloperList = loSC.GetOutput()

IF RECCOUNT() = 0
  pcDeveloperList = pcDeveloperList + "<p><center><b style='color:darkred'>No entries matched your search</b></center></p>"
ENDIF

Response.ExpandTemplate( Request.GetPhysicalPath() )

ENDFUNC

************************************************************************
* wwDevelopers :: SearchDevelopers
****************************************
***  Function: Protected method that performs the search operation
***			   Uses the form variables to get its query information
************************************************************************
PROTECTED FUNCTION SearchDevelopers(loCustomer)

lcType = Request.QueryString("Type")
IF LOWER(lcType) = "yourentries"
  llYourEntries = .T.
ELSE
  llYourEntries = .F.
ENDIF

poQuery.AddProperty("DevName","")
poQuery.AddProperty("Company","")
poQuery.AddProperty("City","")
poQuery.AddProperty("State","")
poQuery.AddProperty("Zip","")
poQuery.AddProperty("Zip2","")
poQuery.AddProperty("Country","United States")
poQuery.AddProperty("Sortby",1)
poQuery.AddProperty("Dev",0)
poQuery.AddProperty("Training",0)
poQuery.AddProperty("Support",0)
 
Request.FormVarsToObject(poQuery,"txt")

lcWhere = ""
IF !EMPTY(poQuery.Name)
  lcWhere = lcWhere + " AND LOWER(Name) like '" + LOWER(poQuery.DevName) + "%'"
ENDIF
IF !EMPTY(poQuery.Company)
  lcWhere = lcWhere + " AND LOWER(Company) like '" + LOWER(poQuery.Company) + "%'"
ENDIF
IF !EMPTY(poQuery.City)
  lcWhere = lcWhere + " AND LOWER(City) LIKE '" + LOWER(poQuery.City) + "%'"
ENDIF
IF !EMPTY(poQuery.State)
  lcWhere = lcWhere + " AND LOWER(state) LIKE '" + LOWER(poQuery.State) + "%'"
ENDIF
IF !EMPTY(poQuery.Zip) AND EMPTY(poQuery.Zip2)
  lcWhere = lcWhere + " AND Zip like '" + poQuery.Zip + "%'"
ENDIF
IF !EMPTY(poQuery.Zip) AND !EMPTY(poQuery.Zip2)
  lcWhere = lcWhere + " AND Zip>='" + poQuery.Zip + "' and Zip<='" + poQuery.Zip2 +"'"
ENDIF
IF !EMPTY(poQuery.Country)
  lcWhere = lcWhere + " AND LOWER(Country) like '" + LOWER(poQuery.Country) + "%'"
ENDIF

IF NOT (poQuery.Dev=0 and poQuery.Training=0 and poQuery.Support=0)
  IF poQuery.Dev = 1
     lcWhere = lcWhere + " AND dev=" + TRANSFORM(poQuery.Dev) 
  ENDIF
  IF poQuery.Support = 1
     lcWhere = lcWhere + " AND support=" + TRANSFORM(poQuery.Support) 
  ENDIF  
  IF poQuery.Training = 1
     lcWhere = lcWhere + " AND training=" + TRANSFORM(poQuery.Training)
  ENDIF
ENDIF

IF poQuery.SortBy = 2
   lcOrder = " ORDER BY Country, State, Zip"
ELSE
   lcOrder = " ORDER BY Company,Name"
ENDIF
                      
IF llYourEntries
  lcWhere = " AND custpk=" + TRANSFORM(loCustomer.oData.Pk) + lcWhere 
ENDIF

IF !llYourEntries
   *** Show only approved entries
   lcWhere = "Approved=1 " + lcWhere
ELSE
   *** Strip of leading AND
   lcWhere = SUBSTR(lcWhere,6)
ENDIF   

loDev = CREATEOBJECT("wwDevRegistry")

loDev.cSQLcursor = "Tquery"
loDev.cSQL = "select company,pk,state,city,zip,country from " + loDev.cAlias + ;
               " WHERE " + lcWhere + " " + lcOrder
loDev.Query(loDev.cSQL)
              
IF !llYourEntries
   SELECT [<a href="ShowDeveloper.wwr?id=]+TRANSFORM(pk) + [">] + company + [</a>] as company,city +", " +state as City_and_State, zip,country from TQuery into cursor Tquery2
ELSE
   SELECT [<a href="EditDeveloper.wwr?id=]+TRANSFORM(pk) + [">] + company + [</a>] as company,city+", " +state as City_and_State, zip,country from TQuery into cursor Tquery2
ENDIF

ENDFUNC
*  wwDevelopers :: SearchDevelopers

************************************************************************
* wwDevelopers :: ShowDeveloper
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION ShowDeveloper(lnPK as Integer)

IF EMPTY(lnPK)
   lnPK = VAL( Request.QueryString("ID") )
ENDIF

loDev = CREATEOBJECT("wwDevRegistry")
IF !loDev.Load(lnPK)
   THIS.ErrorMsg("Developer info failed to load",loDev.cErrorMsg)
   RETURN
ENDIF

SET CENTURY ON
SET DATE TO AMERICAN

poDev = loDev.oData
Response.ExpandTemplate( JUSTPATH( Request.GetPhysicalPath() ) + "\ShowDeveloper.wwr"  )

ENDFUNC
*  wwDevelopers :: ShowDeveloper

************************************************************************
* wwDevelopers :: AddDeveloper
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION AddDeveloper
LOCAL loDev as wwDevRegistry

lcCustPk = Session.GetSessionVar("CustomerPK")

loCust = CREATEOBJECT([WWC_CUSTOMERCLASS])
#IF WWDEV_USE_SQL_TABLES
loCust.SetSQLObject(Server.owwStoreSQL)
#ENDIF

IF !loCust.Load( VAL(lcCustPK) )
    THIS.StandardPage("You don't have a West Wind Profile",;
                      "In order to use this feature you need to set up a West Wind Profile <br>" +;
                      "entry with your contact information.<p>" + ;
                      "We're re-directing you now to the <a href='Profile.wwr?=next=ADDDEVELOPER.WWR'>Profile entry page</a>...",;
                      ,5,"Profile.wwr?next=ADDDEVELOPER.WWR")
	RETURN
ENDIF

loDev = CREATEOBJECT("wwDevRegistry")

IF !loDev.New()     
  THIS.ErrorMsg("Couldn't save developer entry",loDev.cErrorMsg)
  RETURN
ENDIF

*** Empty record
poDev = loDev.oData

IF !EMPTY(lcCustPk)
   IF loCust.Load( VAL(lcCustPK) )
      loCData = loCust.oData
      poDev.Company = loCData.Company
      poDev.Name = TRIM(loCData.FirstName) + " " + loCData.LastName
      poDev.Address = TRIM(loCData.Address)
      poDev.City = loCData.City
      poDev.State = loCData.State
      poDev.Zip = loCData.Zip
      poDev.email = loCData.email
      poDev.Phone = loCData.Phone
   ENDIF
ENDIF

*** Mark this record as a new record
poDev.PK = 0

pcErrorMsg = ""
Response.ExpandTemplate( Config.cHTMLPagePath + "editDeveloper.wwr" )

ENDFUNC
*  wwDevelopers :: AddCustomer

************************************************************************
* wwDevelopers :: EditDeveloper
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION EditDeveloper
LPARAMETERS loDev, lcErrorMsg
LOCAL loDev as wwDevRegistry

*** Load object if not passed (normally)
IF VARTYPE(loDev) # "O"
	lcID = VAL( Request.QueryString("ID") )
	lcCustPk = Session.GetSessionVar("CustomerPK")
	llAdmin = !EMPTY(Session.GetSessionVar("AdminUser"))

	loCust = CREATEOBJECT([WWC_CUSTOMERCLASS])
   #IF WWDEV_USE_SQL_TABLES
   loCust.SetSQLObject(Server.owwStoreSQL)
   #ENDIF

	IF !loCust.Load( VAL(lcCustPK) )
	    THIS.StandardPage("You don't have a West Wind Profile",;
	                      "In order to use this feature you need to set up a West Wind Profile <br>" +;
	                      "entry with your contact information.<p>" + ;
	                      "We're re-directing you now to the <a href='Profile.wwr?=next=ADDDEVELOPER.WWR'>Profile entry page</a>...",;
	                      ,5,"Profile.wwr?next=EditDeveloper.wwr?id=" + TRANSFORM(lcID))
		RETURN
	ENDIF
	 
	loDev = CREATEOBJECT("wwDevRegistry")

	IF !loDev.Load(lcID)
	   THIS.ErrorMsg("Developer info failed to load",loDev.cErrorMsg)
	   RETURN
	ENDIF

	IF !llAdmin AND loDev.oData.CustPK # VAL( lcCustPk)
	   THIS.ErrorMsg("Access Denied","Sorry, this is not your entry and you can't edit it!<p>" + ;
	                 "<a href='default.wwr'>Click here</a> to return to the main developer list.",,3,"default.wwr")
	   RETURN
	ENDIF
	pcErrorMsg = ""
ELSE
    pcErrorMsg = lcErrorMsg
ENDIF

*** Don't allow going back to this page without completely reloading
loHeader = CREATEOBJECT("wwHTTPHeader")
loHeader.DefaultHeader()
loHeader.AddForceReload()
   
poDev = loDev.oData
Response.ExpandTemplate( Config.cHTMLPagePath + "EditDeveloper.wwr", loHeader)

ENDFUNC
*  wwDevelopers :: EditDeveloper

************************************************************************
* wwDevelopers :: SaveDeveloper
*******************************
***  Function: Saves the developer information displayed from the
*** 		   edit form. Returns back to the Show form on success
***            or displays a 'preview' form on new entries.
************************************************************************
FUNCTION SaveDeveloper
LOCAL lcID as String, llNew as Boolean, loDev as wwDevRegistry

lnPK = VAL( Request.QueryString("ID") )

loDev = CREATEOBJECT("wwDevRegistry")
 
IF EMPTY(lnPK)
  IF !loDev.New()     
	 THIS.ErrorMsg("Couldn't save developer entry",loDev.cErrorMsg)
     RETURN
  ENDIF
  llNew = .T.
ELSE
  IF !loDev.Load( lnPK )
	 THIS.ErrorMsg("Couldn't save developer entry",loDev.cErrorMsg)
     RETURN
  ENDIF
  llNew = .F.
ENDIF 

Request.FormVarsToObject( loDev.oData,"txt" )

*** Now fix up checkboxes
lcVal = Request.Form("txtDev")
IF !EMPTY(lcVal)
   loDev.oData.Dev = 1
ELSE
   loDev.oData.Dev = 0
ENDIF
lcVal = Request.Form("txtTraining")
IF !EMPTY(lcVal)
   loDev.oData.Training = 1
ELSE
   loDev.oData.Training = 0
ENDIF
lcVal = Request.Form("txtSupport")
IF !EMPTY(lcVal)
   loDev.oData.Support = 1
ELSE
   loDev.oData.Support = 0
ENDIF

*** Validate Business Object
pcErrorMsg = ""
IF !loDev.Validate()
   pcErrormsg = STRTRAN(loDev.cErrorMsg,CHR(13),"<BR>")
ENDIF

IF !EMPTY(pcErrorMsg)
   IF llNew
	  *** We re-edit	
      loDev.oData.Pk = 0
   ENDIF
   THIS.EditDeveloper(loDev,pcErrorMsg)
   RETURN
ENDIF

IF llNew
  *** Allow only this customer to edit the entry
  loDev.oData.CustPk = VAL( Session.GetSessionVar("CustomerPk") )
ENDIF

*** Fix up Service field to disallow malicious code
loDev.oData.Services = STRTRAN(loDev.oData.Services,"<%","&lt;%")
loDev.oData.Services = STRTRAN(loDev.oData.Services,"%>","%&gt;")

*** Save the actual entry
IF !loDev.Save()
   THIS.ErrorMsg("Save Operation failed...",loDev.cErrorMsg + "<p>Click the back button to return...")
   RETURN
ENDIF

IF llNew
  *** Confirmation to user
  THIS.SendEmail(loDev.oData.Email,"West Wind Developer Registry: " + loDev.oData.Company,;
                "Thank you for your developer entry!" +CRLF + CRLF +;
                "West Wind Developer Registry: " + loDev.oData.Company +CRLF + CRLF + ;
                "To see or edit your entry:" + CRLF + CRLF +;
                CONFIG.cWebHome + "ShowDeveloper.wwr?id=" + TRANSFORM(loDev.oData.PK) + CRLF + ;
                Config.cWebHome + "EditDeveloper.wwr?Id=" + TRANSFORM(loDev.oData.PK) +CRLF +CRLF + ;
                "+++ The West Wind Team ---")
                
  *** Send Email to admin
  THIS.SendEmail(Config.cMailcc,"West Wind Developer Registry: " + loDev.oData.Company,;
                "West Wind Developer Registry: " + loDev.oData.Company +CRLF + CRLF + ;
                Config.cWebHome + "admin/MaintApprovalList.wwr" + CRLF + CRLF +  ;
                PropertyDump(loDev.oData) + CRLF +CRLF + " --- The West Wind Team +++")

   *** Show Confirmation Page with Preview
   THIS.StandardPage("Developer Entry saved","The entry has been saved and will be reviewed for approval shortly.<p>" +;
   										     "Approval involves checking for a West Wind registration, so if you need to provide " +;
   										     "additional info please email the <a href='mailto:sales@west-wind.com'>West Wind team</a>." + ;	
                                             "<ul><li> <a href='default.wwr'>Back to the main registry</a>" +;
                                             "<li> <a href='editDeveloper.wwr?id=" + TRANSFORM(loDev.oData.Pk) + "'>Edit entry some more</a></ul><p>" +;
                                             "Preview: <iframe src='showDeveloper.wwr?id=" +TRANSFORM(loDev.oData.Pk) + "' height=600 width=800></iframe>")                                             
ELSE
   *** Just show the updated entry
   THIS.ShowDeveloper( loDev.oData.PK)
ENDIF

ENDFUNC
*  wwDevelopers :: SaveDeveloper

************************************************************************
* wwDeveloper :: DeleteDeveloper
****************************************
***  Function: Deletes a developer entry. Checks to make sure only
***            an admin developer or the creator can kill the entry
************************************************************************
FUNCTION DeleteDeveloper()

*** Load object if not passed (normally)
lnId = VAL( Request.QueryString("ID") )
lcCustPk = Session.GetSessionVar("CustomerPK")
llAdmin = !EMPTY(Session.GetSessionVar("AdminUser"))

loCust = CREATEOBJECT([WWC_CUSTOMERCLASS])
#IF WWDEV_USE_SQL_TABLES
loCust.SetSQLObject(Server.owwStoreSQL)
#ENDIF 

IF !loCust.Load( VAL(lcCustPK) )
    THIS.StandardPage("You don't have a West Wind Profile",;
                      "In order to use this feature you need to set up a West Wind Profile <br>" +;
                      "entry with your contact information.<p>" + ;
                      "We're re-directing you now to the <a href='Profile.wwr?=next=ADDDEVELOPER.WWR'>Profile entry page</a>...",;
                      ,5,"Profile.wwr?next=EditDeveloper.wwr?id=" + TRANSFORM(lnId))
	RETURN
ENDIF
 
loDev = CREATEOBJECT("wwDevRegistry")

IF !loDev.Load(lnID)
   THIS.StandardPage("Invalid Entry","This entry doesn't exist...",,5,"default.wwr")
   RETURN
ENDIF

IF !llAdmin AND loDev.oData.CustPK # VAL( lcCustPk)
   THIS.ErrorMsg("Access Denied","Sorry, this is not your entry and you can't edit it!<p>" + ;
                 "<a href='default.wwr'>Click here</a> to return to the main developer list.",,3,"default.wwr")
   RETURN
ENDIF

loDev.Delete(lnId)

THIS.StandardPage("Entry Deleted","The entry for " + loDev.oData.Company + " has been deleted.")

ENDFUNC
*  wwDeveloper :: DeleteDeveloper


************************************************************************
* wwStore :: Profile
*********************************
***  Function: Handles display of the profile. This is a dual function
***            method that handles either the standalone profile page
***            or the Order Profile page.
************************************************************************
FUNCTION Profile
PARAMETER pcErrorMsg
LOCAL lnCustPk, llSubmit
PRIVATE plNew, oCustomer, oLookups, oCust

lnCustPk = VAL(Session.GetSessionVar("CustomerPK"))
llSubmit = !EMPTY(Request.Form("btnSubmit") )

IF EMPTY(THIS.cNextMethod)
   THIS.cNextMethod = Request.QueryString("Next")
   IF EMPTY(THIS.cNextMethod)
      THIS.cNextMethod = "DEFAULT.WWR"
   Endif
ENDIF

plNew = .F.
oCustomer = CREATE([WWC_CUSTOMERCLASS])
#IF WWDEV_USE_SQL_TABLES
oCustomer.SetSQLObject(Server.owwStoreSQL)
#ENDIF

IF EMPTY(lnCustPK)
   oCustomer.New()
   plNew = .T.
   Session.SetSessionVar("CustomerPk",oCustomer.oData.Pk)
ELSE
   IF !oCustomer.Load(lnCustPK)
   	  oCustomer.New()
   	  plNew = .T.
   ENDIF
ENDIF   

*** Error Message if any to display
IF VARTYPE(pcErrorMsg) # "C"
   pcErrorMsg = ""
ENDIF	

*** For easier display create a data reference
oCust = oCustomer.oData

IF llSubmit
    oCust.Userid = Session.cSessionId

    *** Read Form vars into the Object
    Request.FormVarsToObject(oCust)
	
	*** Fix up the country to display
	oLookups = oCustomer.CreateChildObject([WWS_CLASS_LOOKUPS])
*!*       #IF WWDEV_USE_SQL_TABLES
*!*       oLookups.SetSQLObject(Server.owwStoreSQL)
*!*       #ENDIF

	oCust.Country = oLookups.CountryIdToCountry(oCust.CountryId)

	IF oCust.State = "**"
	   oCust.State = ""
	ENDIF

	IF oCust.Country = "**"
    	oCust.CountryID = ""
 	ENDIF

	oCust.Email = lower(oCust.Email)
	oCust.Password = lower(oCust.Password)

	IF EMPTY(oCust.Password)
	  *** This is specific to the Web app - we don't enforce this
      *** this in the GUI app, hence Validate doesn't handle this
	  pcErrorMsg = "Your Profile Password may not be left blank." + CHR(13)
	ENDIF

	*** Error checking here
	IF !oCustomer.Validate()
	   pcErrorMsg = pcErrorMsg + oCustomer.cErrorMsg
	ENDIF

	*** If we have no error we can go on
	IF EMPTY(pcErrorMsg)
	   oCustomer.Save()  && Save to Disk
	   Session.SetSessionVar("CustomerPK",TRANS(oCust.PK))	
       IF !EMPTY(THIS.cNextMethod) AND ; 
          !INLIST(UPPER(THIS.cNextmethod),"PROFILE.WWR")
		   Response.Redirect( THIS.cNextMethod )
		   RETURN
	   ENDIF   
	ENDIF
ENDIF

*** Just redisplay the current page
Response.ExpandTemplate( Request.GetPhysicalPath() )

ENDFUNC
* wwStore :: Profile 


************************************************************************
* wwStore :: LogonProfile
*********************************
***  Function:
***    Assume:
************************************************************************
FUNCTION LogonProfile
LOCAL lcPassword, lcAction, llEmailPassword
PRIVATE pcEmail, pcErrorMsg

pcEmail = lower(Request.Form("Email"))
lcPassWord = lower(Request.Form("Password"))

*** Pointer so we know which request to run if we're OK
pcNextMethod = Request.QueryString("Next")
IF EMPTY(pcNextMethod)
   pcNextMethod = "PROFILE.WWR"
ENDIF   
THIS.cNextMethod=pcNextMethod

lcAction = UPPER( Request.QueryString("Action") )
llEmailPassword = !EMPTY( Request.Form("EmailPassword") ) && Checkbox

*** Error Message to display if not blank
pcErrorMsg = ""

*** Create Customer object to do our dirty work
loCustomer = CREATE([WWS_CLASS_CUSTOMER])
#IF WWDEV_USE_SQL_TABLES
loCustomer.SetSQLObject(Server.owwStoreSQL)
#ENDIF

SET STEP on

DO CASE
  CASE EMPTY(pcEmail) and EMPTY(lcPassword)
      *** Just show the form
      pcErrorMsg = "Please fill in an email address and password."
      Response.ExpandTemplate( Request.GetPhysicalPath() )

  CASE llEmailPassword
      IF !loCustomer.Find("trim(email) == [" + pcEmail + "]" )

         pcErrorMsg = "The specified email address does not exist. Please sign up for a brand new account profile."

         *** Go to the profile page and display an error message
         THIS.Profile(pcErrorMsg)
      ELSE  
         IF EMPTY(loCustomer.oData.Password)
            loCustomer.oData.Password = LOWER(SUBSTR(SYS(2015),2))
            loCustomer.Save()
         ENDIF
	     THIS.SendEmail(pcEmail,"West Wind Profile Password.",;
	                    "Your logon info for your online account is: "  +CRLF + CRLF +;
	                    "Username: " + pcEmail + CRLF +;
	                    "Password: " + loCustomer.oData.Password + CRLF + CRLF +;
	                    "The West Wind Team" + CRLF,,,.T.)
	                    
	     pcErrorMsg = "Check your email and then re-enter your password on this form."               
      ENDIF 	                    
  
      *** Just redisplay this form
      Response.ExpandTemplate( Request.GetPhysicalPath())


  CASE EMPTY(lcAction)
	  *** Logon to the email profile 	
      IF loCustomer.nDataMode = 2
         llResult = loCustomer.Find("email like '" + pcEmail + "' and password='" + lcPassword + "'")
      ELSE
         llResult = loCustomer.Find("trim(email) == [" + pcEmail + "] and password = padr([" + lcPassword + "],10)")
      ENDIF
      
      IF !llResult
         *** Redisplay this form
         pcErrorMsg = "Invalid Password.<br>If you forgot your password check the <i>Forgot your Password?</i> checkbox."
         Response.ExpandTemplate( Request.GetPhysicalPath() ) 
         RETURN
      ENDIF   
      
      *** Ok - logged in
     
      *** Now fix the current session by updating the CookieId with the User ID
      lcSessionId = loCustomer.oData.UserId
      IF EMPTY(loCustomer.oData.UserId)
         lcSessionId = SYS(2015)
         loCustomer.oData.UserId = lcSessionID
         loCustomer.Save()
      ENDIF
      
      *** Kill any existing sessions 
      Session.DeleteSession(lcSessionId)
      
      *** Find the current session and update the current SessionID
      *** Note this might be different than user's session ID in some cases
      *** where they are not logged on yet or running a new browser
      IF !Session.LocateSession(Session.cSessionID)
         Session.NewSession()
      ENDIF
       
      *** Update the new session
      Session.SetSessionId(lcSessionID) && Force the current session to our new sessionid
      Session.SetSessionVar("CookiesOn","True")
      Session.SetSessionVar("CustomerPK",TRANS(loCustomer.oData.Pk))
            
      *** Force a new Cookie to be written with that value when page is built
      Response.cAutoSessionCookieName = Config.cCookieName
      Response.cAutoSessionCookie = loCustomer.oData.UserID
      Response.lAutoSessionCookiePersist = .T.

      *** Write out Meta Refresh page to force the cookie before redirecting
      THIS.StandardPage("Attaching to your profile",[<a href="profile.wwr?next=] + THIS.cNextMethod + [">Click here</a> if your browser isn't navigating to the profile form automatically.],,1,"profile.wwr?next=" + THIS.cNextMethod)
ENDCASE

ENDFUNC
* wwStore :: LogonProfile

************************************************************************
* wwStore :: ClearSession
*********************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION ClearProfile

pcNextMethod = Request.QueryString("next")

*** Clear the cookie
loHeader = CREATE("wwHTTPHeader")
loHeader.DefaultHeader()
loHeader.AddCookie(Config.cCookieName,"")


pcNextMethod = "profile.wwr?next=" + pcNextMethod

THIS.ErrorMsg("Profile link cleared","The profile has been reset. Hang on returning to profile page...",loHeader,2,pcNextMethod)

RETURN

************************************************************************
* wwStore :: SendEmail
*********************************
***  Function:
***    Assume:
************************************************************************
PROTECTED FUNCTION SendEmail
LPARAMETER lcRecipient, lcSubject, lcBody, lcContentType, lcAttachment,llnocc

lcContentType=IIF(EMPTY(lcContentType),"text/plain",lcContentType)

loIP = CREATE("wwIPStuff")
loIP.cMailServer=Config.cMailServer
loIP.cSenderEmail=Config.cMailFromEmail
loIP.cSenderName=Config.cMailFrom

IF !llNoCC
   loIP.cCCList = Config.cMailCC
ENDIF

loIP.cRecipient = lcRecipient
	
loIP.cSubject = lcSubject
loIP.cMessage = lcBody
	
loIP.cContentType = lcContentType

loIP.SendMailAsync()

ENDFUNC
* wwStore :: SendEmail


************************************************************************
* wwStore :: MaintApprovalList
*********************************
FUNCTION MaintApprovalList

IF !THIS.Login()
   RETURN
ENDIF   

lcAction = Request.QueryString("Action")
lcSku = Request.QueryString("Sku")
lcID = Request.QueryString("ID")

pcMessage = ""

oReg = CREATEOBJECT("wwDevRegistry")

IF lcACTION = "ShowAll"
   oReg.Query("select * from " + oReg.cFileName + " Order by Company")
ELSE
   oReg.Query("select * from " + oReg.cFileName + " where approved=0 Order by Company")
ENDIF   


Response.ContentTypeHeader()
Response.Write([<html><head><link rel="stylesheet" type="text/css" href="..\wwRegistry.css"></head><body>] + ;
               [<h1>Entry List</h1><hr>] )

loSC = CREATE("wwShowCursor")
*!*   #IF WWDEV_USE_SQL_TABLES
*!*   loSC.oSQL = SERVER.oSQL
*!*   #ENDIF

loSC.cBaseUrl = "MaintApprovalList.wwr?"
loSC.cKeyField = "pk"
loSC.cKeyType = "N"
loSC.cTableFieldList = "company,name,City,State,Country"
loSC.cTableEditFieldList = "Approved,Company,Name,Services,logo"
loSC.cExtraTableTags = [class="body"]

*loSC.lAllowDelete = .F.
*loSC.lAllowEdit = .F.

DO CASE
CASE lcAction = "EDIT"
      loSc.EditTable()
      Response.Write( loSc.GetOutput() )

	  Response.Write("<p>Preview (prior to editing):<br><IFRAME width='820' height='700' SRC='..\ShowDeveloper.wwr?ID=" +lcID +"'></IFRAME>")
	  Response.HTMLFooter()	
      RETURN
*** Have to manually handle the SQL Update and Inserts
*** Since wwShowCursor uses 'LOCATE/REPLACE/APPEND BLANK'
CASE lcAction == "Save"       
      IF !oReg.Load(VAL(lcId))
         THIS.ErrorMsg("Invalid Entry","Can't save this item...")
         RETURN
      ENDIF

      Request.FormVarsToObject(oReg.oData)

      IF !oReg.Save()
         THIS.ErrorMsg("Update failed",oReg.cErrorMsg)
         RETURN
      ENDIF

	  *** Send Email to admin
	  THIS.SendEMail(oReg.oData.Email,"West Wind Developer Registry: " + oReg.oData.Company,;
                "West Wind Developer Registry: " + oReg.oData.Company + CRLF + CRLF +;
                "Your developer entry has been approved. You can review it at:" + CRLF + crlf + ;
                 Config.cWebHome + [showDeveloper.wwr?id=] + ;
                TRANSFORM(oReg.oData.PK) + CRLF + CRLF + "+++ The West Wind Team ---")
      

      *** Just redisplay the list page
      Response.Redirect("MaintApprovalList.wwr")
      RETURN
CASE lcAction == "SaveNew"
      oReg.New()     
      
      *** We need to save our PK
      lnPk = oReg.oData.Pk
      
      Request.FormVarsToObject(oItem.oData)
      
      *** Now write saved PK over possible PK from data
      oReg.oData.Pk = lnPK
      
      IF !oReg.Save()
         THIS.ErrorMsg("Update failed",oItem.cErrorMsg)
         RETURN
      ENDIF
      
      *** Just redisplay the list page
      Response.Redirect("MaintApprovalList.wwr")
CASE lcAction == "DELETE"
     oReg.Delete(VAL(lcId))
	 Response.Redirect("MaintApprovalList.wwr")
	 RETURN	
OTHERWISE
   *** With DBF tables everything this automatic
   loSC.EditTable()
ENDCASE  

Response.Write( loSC.GetOutput() )

Response.HTMLFooter([<hr><a href="MaintApprovalList.wwr">Approval List</a> | <a href="default.htm">Admin Page</a>])
RETURN
ENDFUNC
* wwStore :: MaintEditItems

************************************************************************
* wwDeveloper :: MaintCreateTables
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION MaintCreateTables()

IF !THIS.Login()
   RETURN .F.
ENDIF

oReg = CREATEOBJECT("wwDevRegistry")
IF !oReg.CreateTable() or !oReg.Reindex()
   THIS.ErrorMsg("Table Creation failed",oReg.cErrorMsg)
   RETURN
ENDIF

THIS.StandardPage("Table Created","")

ENDFUNC
*  wwDeveloper :: MaintCreateTables

************************************************************************
* wwDeveloper :: MaintReindex
****************************************
***  Function:
************************************************************************
FUNCTION MaintReindex()

IF !THIS.Login()
   RETURN .F.
ENDIF

oReg = CREATEOBJECT("wwDevRegistry")
IF !oReg.Reindex()
   THIS.ErrorMsg("Reindexing failed",oReg.cErrorMsg)
   RETURN
ENDIF

THIS.StandardPage("Tables Reindexed","")

ENDFUNC
*  wwDeveloper :: Reindex

************************************************************************
* wwDeveloper :: AdminLogin
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION MaintAdminLogin()

IF !THIS.Login(Config.cAdminUser)
   RETURN .F.
ENDIF

THIS.StandardPage("Login Successful","You're now logged in as an Admin user and can wreak havoc on the site.<p><a href='..\default.wwr'>Back to entries</a>.")

RETURN .T.
ENDFUNC
*  wwDeveloper :: AdminLogin

************************************************************************
* wwDeveloper :: Login
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
PROTECTED FUNCTION Login(lcValidUserName, lcErrorMsg)

IF DODEFAULT(Config.cAdminUser,lcErrorMsg)
   Session.SetSessionVar("AdminUser","Yes")
   RETURN .T.
ENDIF

RETURN .F.
ENDFUNC
*  wwDeveloper :: Login


************************************************************************
* wwDeveloper :: ErrorMsg
****************************************
***  Function:
***    Assume:
***      Pass:
***    Return:
************************************************************************
FUNCTION ErrorMsg
PARAMETER lcHeader, lcBody, lvHeader, lnRefresh, lcRefreshUrl
 
lcHeader=IIF(!EMPTY(lcHeader),lcHeader,"FORCE RELOAD")
lcBody=IIF(!EMPTY(lcBody),lcBody,"")
lnRefresh = IIF(EMPTY(lnRefresh),0,lnRefresh)
IF lnRefresh > 0
   lcRefreshUrl=IIF(EMPTY(lcRefreshUrl),"",lcRefreshUrl)
ENDIF



*** Make sure we have a valid object since we might be in a fatal error condition
*** If not we can't spit out a message - the DLL must handle the empty output
IF TYPE("THIS.oResponse")="O" AND !ISNULL(THIS.oResponse)
   THIS.oResponse.Rewind()

   Response.ExpandTemplate( Config.cHTMLPagePath + "ErrorMsg.wwr", lvHeader ) 

   *** Close down the doc and shut off further output
   THIS.oResponse.NoOutput(.T.)
ENDIF

ENDFUNC
* EOF wwProcess::ErrorMsg



ENDDEFINE