ned a unique 
	code that must be entered in order to qualify for the discount. 
	In addition, order discounts can be given a date range and 
	can be configured so that they're only used once.
	
	<p>There is also a special discount code, StoreWide, that may be used to 
	apply a store wide discount for all orders. The store-wide discount 
	supersedes all other order discounts and will be applied if active.<br><br>
	
	Order discounts are calculated based upon the total value of an 
	order, BEFORE taxes and shipping and AFTER product discounts 
	have been applied (if any). You specify what order total 
	will qualify for the order discount by entering a "From" and "To" 
	amount. You also have to enter what percentage or amount of the 
	order total to discount. If the customer then creates an order, 
	and enter a valid discount code, the system will check the order 
	total to see if it qualifies for the selected discount code. 
	If it does, the appropriate amount will be deducted from the 
	order total. In the list of discounts above, the following columns 
	are displayed :<br><br>
	
	<b>Code - </b>Discount code that must be entered by customer.<br>
	<b>From - </b>Minimum order amount to qualify for discount.<br>
	<b>To - </b>Maximum order amount to qualify for discount.<br>
	<b>Perc. - </b>Percentage that will be subtracted from order.<br>
	<b>Amt. - </b>Amount that will be subtracted from order.<br>
	<b>Stat - </b>Discount Status. (A)ctive, (I)inactive, (U)sed.<br>
	<b>Once - </b>Use once only? (Y)es, (N)o. If set to Yes, the discount 
	can only be used once.<br>
	<b>Date Valid - </b>Date range for which discount is valid.<br><br>
	
	<b>Add Discount</b> - Click on the "Add Discount" button, and 
	complete the form as indicated to add a new discount record.<br><br>
	
	<b>Find Discount(s)</b> - You can limit the list of Discounts  
	on this page by selecting one of several discount options, or 
	combination of discount options by using the "Find" functions.<br><br>
	
	<b>Edit Discount</b> - Click on "edit" to change discount 
	information.<br><br>
	
	<b>Delete Discount</b> - Check the box next to the discount you 
	want to delete and click the button at the bottom of the page.<br><br>
	
	<b>Search Orders</b> - Click the "orders" link to search for orders 
	using that discount code.<br><br>
	
</td></tr>
</table>

<%
call closeDB()

%><!--#include file="_INCfooter_.asp"--><%
'*********************************************************************
'Make QueryString for Paging
'*********************************************************************
function navQueryStr(pageNum)

	navQueryStr = "?curPage="		& server.URLEncode(pageNum) _
	            & "&showStatus="	& server.URLEncode(showStatus) _
	            & "&showOnceOnly="	& server.URLEncode(showOnceOnly) _
	            & "&showPhrase="	& server.URLEncode(showPhrase)
end function
'*********************************************************************
'Make Cookie Value for Paging
'*********************************************************************
function navCookie(pageNum)

	navCookie = pageNum		  & "*|*" _
	          & showStatus	  & "*|*" _
	          & showOnceOnly  & "*|*" _
	          & showPhrase
end function
'*********************************************************************
'Format the internal integer date
'*********************************************************************
function formatIntDate(str1)
	
	if len(trim(str1)) >= 8 and isnumeric(str1) then
		formatIntDate = "" _
			& mid(str1,7,2) & "/" _
			& mid(str1,5,2) & "/" _
			& mid(str1,1,4)
	else
		formatIntDate = str1
	end if

end function
'*********************************************************************
'Display page navigation
'*********************************************************************
sub pageNavigation(formFieldName)
	Response.Write "Page "
	Response.Write "<select onChange=""location.href=this.options[selectedIndex].value"" name=" & trim(formFieldName) & ">"
	for I = 1 to TotalPages
		Response.Write "<option value=""SA_disc.asp" & navQueryStr(I) & "&sortField=" & server.URLEncode(sortField) & """ " & checkMatch(curPage,I) & ">" & I & "</option>" & vbCrlf
	next
	Response.Write "</select>&nbsp;of&nbsp;" & TotalPages & "&nbsp;&nbsp;"
	Response.Write "[&nbsp;"
	if curPage > 1 then
		Response.Write "<a href=""SA_disc.asp" & navQueryStr(curPage-1) & "&sortField=" & server.URLEncode(sortField) & """>Back</a>"
	else
		Response.Write "Back"
	end if
	Response.Write "&nbsp;|&nbsp;"
	if curPage < TotalPages then
		Response.Write "<a href=""SA_disc.asp" & navQueryStr(curPage+1) & "&sortField=" & server.URLEncode(sortField) & """>Next</a>"
	else
		Response.Write "Next"
	end if
	Response.Write "&nbsp;]"
end sub
%>                                                                                                                                                                                                                                                                                           <%@ Language=VBScript %>
<%
'*************************************************************************
' DO NOT MODIFY THIS SCRIPT IF YOU WANT UPDATES TO WORK!
' Function : Order Discount Maintenance
' Product  : CandyPress Store Administration
' Version  : 4.1

' Modified : May 2007
' Copyright: Copyright (C) 2004 Webs Unlimited, Inc. 
'            See "license.txt" for this product for details regarding 
'            licensing, usage, disclaimers, distribution and general 
'            copyright requirements. If you don't have a copy of this 
'            file, you may request one at http://www.candypress.com
'*************************************************************************
Option explicit
Response.Buffer = true
const adminLevel = 0
%>
<!--#include file="_INCappDBConn_.asp"-->
<!--#include file="../Scripts/_INCconfig_.asp"-->
<!--#include file="_INCsecurity_.asp"-->
<!--#include file="../Scripts/_INCappFunctions_.asp"-->
<%
'Database
dim mySQL, rs


'DiscOrder
dim idDiscOrder
dim discCode
dim discPerc
dim discAmt
dim discFromAmt
dim discToAmt
dim discStatus
dim discOnceOnly
dim discValidFrom
dim discValidTo

'Work Fields
dim I
dim action
dim errMsg 

'*************************************************************************

'Open Database Connection
call openDB()

'Store Configuration
if loadConfig() = false then
	errMsg = "Could not load Store Configuration settings." 
call closeDB()

Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)

end if

%>

<!--#include file="_INCheader_.asp"-->

<P align=left>
	<b><font size=3>Order Discount Maintenance</font></b>
	<br><br>
</P>

<%
'Get action
action = trim(Request.QueryString("action"))
if len(action) = 0 then
	action = trim(Request.Form("action"))
end if
action = lCase(action)
if action <> "edit" and action <> "add" then
	errMsg = "Invalid Action Indicator."
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Get idDiscOrder
if action = "edit" then
	idDiscOrder = trim(Request.QueryString("recId"))
	if len(idDiscOrder) = 0 then
		idDiscOrder = trim(Request.Form("recId"))
	end if
	if idDiscOrder = "" or not isNumeric(idDiscOrder) then
		errMsg = "Invalid Record ID."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
end if

'Get Order Discount Record
if action = "edit" then
	mySQL="SELECT idDiscOrder,discCode,discPerc,discAmt," _
		& "       discFromAmt,discToAmt,discStatus," _
	    & "       discOnceOnly,discValidFrom,discValidTo " _
	    & "FROM   DiscOrder " _
	    & "WHERE  idDiscOrder = " & idDiscOrder
	set rs = openRSexecute(mySQL)
	if rs.eof then
		errMsg = "Invalid Record ID."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	else
		discCode		= rs("discCode")
		discPerc		= rs("discPerc")
		discAmt			= rs("discAmt")
		discFromAmt		= rs("discFromAmt")
		discToAmt		= rs("discToAmt")
		discStatus		= rs("discStatus")
		discOnceOnly	= rs("discOnceOnly")
		discValidFrom	= rs("discValidFrom")
		discValidTo		= rs("discValidTo")
	end if
	call closeRS(rs)
end if

'Edit
if action = "edit" then
	if len(trim(Request.QueryString("msg"))) > 0 then
%>
		<font color=red><%=Request.QueryString("msg")%></font>
		<br><br>
<%
	end if
%>
	<span class="textBlockHead">Edit Order Discount</span>
	&nbsp;<%call maintNavLinks()%><br><br>
	
	<table border=0 cellspacing=0 cellpadding=5 class="textBlock">
		<form method="post" action="SA_disc_exec.asp" name="form1">
		<tr>
			<td align=right nowrap><b>Discount Code</b></td>
			<td align=left>
				<input type=text name=discCode id=discCode size=20 maxlength=20 value="<%=discCode%>">
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Order Amount From</b></td>
			<td align=left>
				<input type=text name=discFromAmt id=discFromAmt size=10 maxlength=10 value="<%=moneyD(discFromAmt)%>">
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Order Amount To</b></td>
			<td align=left>
				<input type=text name=discToAmt id=discToAmt size=10 maxlength=10 value="<%=moneyD(discToAmt)%>">
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Discount Percentage</b></td>
			<td align=left nowrap>
				<input type=text name=discPerc id=discPerc size=10 maxlength=10 value="<%=discPerc%>"> %
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Discount Amount</b></td>
			<td align=left nowrap>
				<input type=text name=discAmt id=discAmt size=10 maxlength=10 value="<%=moneyD(discAmt)%>">
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Status</b></td>
			<td align=left>
				<select name=discStatus id=discStatus size=1>
					<option value="">-- Select --</option>
					<option value="A" <%=checkMatch(discStatus,"A")%>>Active</option>
					<option value="I" <%=checkMatch(discStatus,"I")%>>InActive</option>
					<option value="U" <%=checkMatch(discStatus,"U")%>>Used</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Use Once Only?</b></td>
			<td align=left>
				<select name=discOnceOnly id=discOnceOnly size=1>
					<option value="">-- Select --</option>
					<option value="Y" <%=checkMatch(discOnceOnly,"Y")%>>Yes</option>
					<option value="N" <%=checkMatch(discOnceOnly,"N")%>>No</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Date Valid From</b></td>
			<td align=left nowrap>
				<%call dateSelect("F",discValidFrom)%>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Date Valid To</b></td>
			<td align=left nowrap>
				<%call dateSelect("T",discValidTo)%>
			</td>
		</tr>
		<tr>
			<td colspan=2 align=center valign=middle>
				<br>
				<input type=hidden name=idDiscOrder id=idDiscOrder value="<%=idDiscOrder%>">
				<input type=hidden name=action      id=action      value="edit">
				<input type=submit name=submit1     id=submit1     value="Update Discount">
				<br><br>
			</td>
		</tr>
		</form>
	</table>
<%
end if

'Add
if action = "add" then
%>
	<span class="textBlockHead">Add Order Discount</span>
	&nbsp;<%call maintNavLinks()%><br><br>
	
	<table border=0 cellspacing=0 cellpadding=5 class="textBlock">
		<form method="post" action="SA_disc_exec.asp" name="form1">
		<tr>
			<td align=right nowrap><b>Discount Code</b></td>
			<td align=left>
				<input type=text name=discCode id=discCode size=20 maxlength=20>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Order Amount From</b></td>
			<td align=left>
				<input type=text name=discFromAmt id=discFromAmt size=10 maxlength=10>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Order Amount To</b></td>
			<td align=left>
				<input type=text name=discToAmt id=discToAmt size=10 maxlength=10>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Discount Percentage</b></td>
			<td align=left nowrap>
				<input type=text name=discPerc id=discPerc size=10 maxlength=10> %
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Discount Amount</b></td>
			<td align=left nowrap>
				<input type=text name=discAmt id=discAmt size=10 maxlength=10>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Status</b></td>
			<td align=left>
				<select name=discStatus id=discStatus size=1>
					<option value="A">Active</option>
					<option value="I">InActive</option>
					<option value="U">Used</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Use Once Only?</b></td>
			<td align=left>
				<select name=discOnceOnly id=discOnceOnly size=1>
					<option value="Y">Yes</option>
					<option value="N">No</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Date Valid From</b></td>
			<td align=left nowrap>
				<%call dateSelect("F","")%>
			</td>
		</tr>
		<tr>
			<td align=right nowrap><b>Date Valid To</b></td>
			<td align=left nowrap>
				<%call dateSelect("T","")%>
			</td>
		</tr>
		<tr>
			<td colspan=2 align=center valign=middle>
				<br>
				<input type=hidden name=action  id=action  value="add">
				<input type=submit name=submit1 id=submit1 value="Add Discount">
				<br><br>
			</td>
		</tr>
		</form>
	</table>
<%
end if

if action = "edit" or action = "add" then
%>
	<br>
	<span class="textBlockHead">Help and Instructions :</span><br>
	<table border=0 cellspacing=0 cellpadding=5 width="100%" class="textBlock">
	<tr><td>

		<b>Discount Code</b> - Mandatory. Unique 
		alpha-numeric code that will be entered by the customer 
		to qualify for a discount. Don't use any special characters 
		or spaces.<br><br>
	
		<b>Order Amount From</b> - Mandatory. The minimum total order 
		amount (excluding taxes and shipping) required to qualify for 
		the discount.<br><br>
	
		<b>Order Amount To</b> - Mandatory. The maximum total order 
		amount (excluding taxes and shipping) required to qualify for 
		the discount.<br><br>
	
		<b>Discount Percentage</b> - Optional if Discount Amount is 
		entered. The percentage of the the total order amount 
		(excluding taxes and shipping) that will be deducted from the 
		order total.<br><br>
		
		<b>Discount Amount</b> - Optional if Discount Percentage is 
		entered. The amount of the total order amount 
		(excluding taxes and shipping) that will be deducted from 
		the order total.<br><br>
	
		<b>Status</b> - Mandatory. A discount has to be "Active" to be 
		available for use. To prevent a discount from being used, set 
		this to "InActive" or "Used". Discounts that can only be used 
		once (see below), will automatically be set to "Used".<br><br>
	
		<b>Use Once Only?</b> - Mandatory. If set to "Yes", the system 
		will automatically update the status to "Used" after the first 
		time the discount has been applied by any customer.<br><br>
	
		<b>Date Valid From</b> - Mandatory. The date from which the discount 
		will be valid (DD/MM/YYYY).<br><br>
	
		<b>Date Valid To</b> - Mandatory. The date from which the discount 
		will no longer be valid (DD/MM/YYYY).<br><br>
	
	</td></tr>
	</table>
<%
end if

call closeDB()

%>

<!--#include file="_INCfooter_.asp"-->

<%
'*********************************************************************
'Create Navigation Links
'*********************************************************************
sub maintNavLinks()
%>
	[ 
	<a href=SA_disc.asp?recallCookie=1>List Discounts</a> 
	]
<%
end sub
'*********************************************************************
'Create Date Drop Down boxes
'*********************************************************************
sub dateSelect(FromOrTo,strDate)

	'Declare some variables local to this subroutine
	dim strY, strM, strD

	'Validate From / To indicator
	FromOrTo = UCase(trim(FromOrTo))
	if FromOrTo <> "F" and FromOrTo <> "T" then
		errMsg = "Invalid From/To Indicator passed to date routine."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	if FromOrTo = "T" then
		FromOrTo = "To"
	else
		FromOrTo = "From"
	end if
	
	'Get date parameter and extract Y, M and D.
	'Default to today's date if invalid or empty.
	if len(strDate) = 8 and isNumeric(strDate) then
		strY = mid(strDate,1,4)
		strM = mid(strDate,5,2)
		strD = mid(strDate,7,2)
	else
		strY = year(now())
		strM = left("00",2-len(datePart("m",now()))) & datePart("m",now())
		strD = left("00",2-len(datePart("d",now()))) & datePart("d",now())
	end if
%>
	<select name="discValid<%=FromOrTo%>DD">
<%
		for I = 1 to 31
			if I < 10 then
%>
				<option value="0<%=I%>" <%=checkMatch(strD,"0" & I)%>>0<%=I%></option>
<%
			else
%>
				<option value="<%=I%>" <%=checkMatch(strD,I)%>><%=I%></option>
<%
			end if
		next
%>
	</select>
	/ 
	<select name="discValid<%=FromOrTo%>MM">
<%
		for I = 1 to 12
			if I < 10 then
%>
				<option value="0<%=I%>" <%=checkMatch(strM,"0" & I)%>>0<%=I%></option>
<%
			else
%>
				<option value="<%=I%>" <%=checkMatch(strM,I)%>><%=I%></option>
<%
			end if
		next
%>
	</select>
	/ 
	<select name="discValid<%=FromOrTo%>YYYY">
<%
		for I = 2002 to 2030
%>
			<option value="<%=I%>" <%=checkMatch(strY,I)%>><%=I%></option>
<%
		next
%>
	</select>
<%
end sub
%>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       <%@ Language=VBScript %>
<%
'*************************************************************************
' DO NOT MODIFY THIS SCRIPT IF YOU WANT UPDATES TO WORK!
' Function : Order Discount Maintenance
' Product  : CandyPress Store Administration
' Version  : 4.1

' Modified : May 2007
' Copyright: Copyright (C) 2004 Webs Unlimited, Inc. 
'            See "license.txt" for this product for details regarding 
'            licensing, usage, disclaimers, distribution and general 
'            copyright requirements. If you don't have a copy of this 
'            file, you may request one at http://www.candypress.com
'*************************************************************************
Option explicit
Response.Buffer = true
const adminLevel = 0
%>
<!--#include file="_INCappDBConn_.asp"-->
<!--#include file="../Scripts/_INCconfig_.asp"-->
<!--#include file="_INCsecurity_.asp"-->
<!--#include file="../Scripts/_INCappFunctions_.asp"-->
<%
'Database
dim mySQL, rs


'DiscOrder
dim idDiscOrder
dim discCode
dim discPerc
dim discAmt
dim discFromAmt
dim discToAmt
dim discStatus
dim discOnceOnly
dim discValidFrom
dim discValidTo

'Work Fields
dim action
dim discValidFromDD
dim discValidFromMM
dim discValidFromYYYY
dim discValidToDD
dim discValidToMM
dim discValidToYYYY
dim errMsg

'*************************************************************************
'Are we in test mode?
if demoMode = "Y" then
	errMsg = "DEMO MODE. Sorry, this feature is NOT available in Demo Mode."
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Open Database Connection
call openDB()

'Store Configuration
if loadConfig() = false then
	errMsg = "Could not load Store Configuration settings." 
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Get action
action = trim(lCase(Request.Form("action")))
if len(action) = 0 then
	action = trim(lCase(Request.QueryString("action")))
end if
if action <> "edit" and action <> "add" and action <> "bulkdel" then
	errMsg = "Invalid Action Indicator."
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Get idDiscOrder
if action = "edit" then

	idDiscOrder = trim(Request.Form("idDiscOrder"))
	if len(idDiscOrder) = 0 then
		idDiscOrder = trim(Request.QueryString("idDiscOrder"))
	end if
	if idDiscOrder = "" or not isNumeric(idDiscOrder) then
		errMsg = "Invalid Order Discount ID."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	else
		idDiscOrder = CLng(idDiscOrder)
	end if
	
end if

if action = "edit" or action = "add" then

	'Get discCode
	discCode = trim(Request.Form("discCode"))
	if len(discCode) = 0 then
		errMsg = "Invalid Discount Code."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	if inStr(discCode," ")  > 0 _
	or inStr(discCode,"'")  > 0 _
	or inStr(discCode,"""") > 0 then
		errMsg = "Invalid characters in the Discount Code."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Check discCode not a duplicate
	mySQL = "SELECT discCode " _
	      & "FROM   DiscOrder " _
	      & "WHERE  discCode = '" & discCode & "' "
	if action = "edit" then
		mySQL = mySQL & "AND idDiscOrder <> " & idDiscOrder
	end if
	set rs = openRSexecute(mySQL)
	if not rs.eof then
		errMsg = "Discount Code already exists."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	call closeRS(rs)
	
	'Get discFromAmt
	discFromAmt = trim(Request.Form("discFromAmt"))
	if len(discFromAmt) = 0 or not Isnumeric(discFromAmt) then
		errMsg = "Invalid Order Amount FROM value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	discFromAmt = CDbl(discFromAmt)
	if discFromAmt < 0 then
		errMsg = "Invalid Order Amount FROM value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get discToAmt
	discToAmt = trim(Request.Form("discToAmt"))
	if len(discToAmt) = 0 or not Isnumeric(discToAmt) then
		errMsg = "Invalid Order Amount TO value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	discToAmt = CDbl(discToAmt)
	if discToAmt < 0 then
		errMsg = "Invalid Order Amount TO value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Check TO is greater than FROM
	if discToAmt < discFromAmt then
		errMsg = "Order Amount TO value must be greater that Order Amount FROM value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get discPerc and/or discAmt
	discPerc = trim(Request.Form("discPerc"))
	discAmt  = trim(Request.Form("discAmt"))
	if (len(discPerc) = 0 and len(discAmt) = 0) _
	or (len(discPerc) > 0 and len(discAmt) > 0) then
		errMsg = "Invalid Discount Percentage and/or Discount Amount."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	'Discount Percentage
	elseif len(discPerc) > 0 then
		if not Isnumeric(discPerc) then
			errMsg = "Invalid Discount Percentage."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
		discPerc = CDbl(discPerc)
		discAmt  = null
		if discPerc <= 0 or discPerc > 100 then
			errMsg = "Invalid Discount Percentage."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
	'Discount Amount
	else
		if not Isnumeric(discAmt) then
			errMsg = "Invalid Discount Amount."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
		discAmt	 = CDbl(discAmt)
		discPerc = null
		if discAmt <= 0 then
			errMsg = "Invalid Discount Amount."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
		if discAmt > discToAmt then
			errMsg = "Discount Amount can not be greater than To amount."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
	end if
	
	'Get discStatus
	discStatus = UCase(trim(Request.Form("discStatus")))
	if discStatus <> "A" and discStatus <> "I" and discStatus <> "U" then
		errMsg = "Invalid Status."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get discOnceOnly
	discOnceOnly = UCase(trim(Request.Form("discOnceOnly")))
	if discOnceOnly <> "Y" and discOnceOnly <> "N" then
		errMsg = "Invalid Once Only value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get discValidFrom
	discValidFromDD   = trim(Request.Form("discValidFromDD"))
	discValidFromMM   = trim(Request.Form("discValidFromMM"))
	discValidFromYYYY = trim(Request.Form("discValidFromYYYY"))
	if not (len(discValidFromDD)=2 and len(discValidFromMM)=2 and len(discValidFromYYYY)=4) then "SELECT idCategory " _
	      & "FROM   categories " _
	      & "WHERE  idParentCategory = 0"
	set rs = openRSexecute(mySQL)
	if not rs.eof then
		errMsg = "Root Category already exists."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	call closeRS(rs)

	'Create Root Record
	mySQL = "INSERT INTO categories (" _
	      & "categoryDesc, idParentCategory, " _
	      & "categoryFeatured, categoryHTML, " _
	      & "sortOrder,categoryHTMLLong" _
	      & ") VALUES (" _
	      & "'Root',0,'N','',null,''" _
	      & ")"
	set rs = openRSexecute(mySQL)
	errMsg = "Root Category was created."
	call closeDB()

	Response.Redirect "SA_cat.asp?msg=" & server.URLEncode(errMsg)

end if

'Just in case we ever get this far...
call closeDB()

Response.Redirect "SA_cat.asp"

'***********************************************************************
'Check that the Category being edited is not being linked to another 
'Category which is currently acting as one of it's Sub-Categories.
'***********************************************************************
function expandCategory(pIdCategory)

	dim mySQL, rs
	
	mySQL = "SELECT idCategory, idParentCategory " _
		  & "FROM   categories " _
		  & "WHERE  idParentcategory = " & pIdCategory
	set rs = openRSexecute(mySQL)
	do while not rs.eof
		if Clng(idParentCategory) = Clng(rs("idCategory")) then
			errMsg = "Category can not be linked to one of it's own Sub-Categories."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
		call expandCategory(rs("idCategory"))
		rs.movenext
	loop
	call closeRS(rs)
	
end function
%>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           ﻿<%@ Language=VBScript %>
<%
'*************************************************************************
' DO NOT MODIFY THIS SCRIPT IF YOU WANT UPDATES TO WORK!
' Function : Category Maintenance
' Product  : CandyPress Store Administration
' Version  : 4.1

' Modified : May 2007
' Copyright: Copyright (C) 2004 Webs Unlimited, Inc. 
'            See "license.txt" for this product for details regarding 
'            licensing, usage, disclaimers, distribution and general 
'            copyright requirements. If you don't have a copy of this 
'            file, you may request one at http://www.candypress.com
'*************************************************************************
'	Date					Description
' 01/26/06	3 ending row tags </tr> were written as <tr>
' 01/26/06	Add check for validSQL of sub categories
' 06/07/06  Paging was not returning to the last opened page corrected
' 
'*************************************************************************
Option explicit
Response.Buffer = true
const adminLevel = 0
%>
<!--#include file="_INCappDBConn_.asp"-->
<!--#include file="../Scripts/_INCconfig_.asp"-->
<!--#include file="_INCadminFunctions_.asp"-->
<!--#include file="../Scripts/_INCappFunctions_.asp"-->
<!--#include file="_INCsecurity_.asp"-->
<%
'Database
dim mySQL, rs, rsTemp


'Categories
dim idCategory
dim categoryDesc
dim idParentCategory
dim categoryFeatured
dim categoryHTML
dim categoryHTMLLong
dim sortOrder
dim breadCrumb
dim breadCrumbLinked

'Work Fields
dim action
dim curPage
dim oldCatDesc
dim errMsg

'*************************************************************************
'Are we in test mode?
if demoMode = "Y" then
	errMsg = "DEMO MODE. Sorry, this featured is NOT available in Demo Mode."
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Open Database Connection
call openDB()

'Store Configuration
if loadConfig() = false then
	errMsg = "Could not load Store Configuration settings." 
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Get Current Page
curPage = trim(Request.QueryString("curPage"))
if len(curPage) = 0 then
	curPage = trim(Request.Form("curPage"))
end if

'Get action
action = trim(lCase(Request.Form("action")))
if len(action) = 0 then
	action = trim(lCase(Request.QueryString("action")))
end if
if  action <> "edit" _
and action <> "del" _
and action <> "bulkdel" _
and action <> "add" _
and action <> "root" then
	errMsg = "Invalid Action Indicator."
	call closeDB()

	Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
end if

'Get idCategory
if action = "edit" or action = "del" then

	idCategory = Request.Form("idCategory")
	if idCategory = "" or not isNumeric(idCategory) then
		errMsg = "Invalid Record ID."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
end if

if action = "edit" or action = "add" then

	'Get Category Description
	categoryDesc = trim(Request.Form("categoryDesc"))
	categoryDesc = replace(categoryDesc,"""","") 'To prevent HTML field terminations
	if len(categoryDesc) = 0 then
		errMsg = "Invalid Category Description."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get idParentCategory
	idParentCategory = Request.Form("idParentCategory")
	if idParentCategory = "" or not isNumeric(idParentCategory) then
		errMsg = "Invalid Parent Category."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Check idParentCategory exists on DB
	'Exclude Root category from this test
	if idParentCategory <> 0 then
		mySQL = "SELECT idCategory " _
		      & "FROM   categories " _
		      & "WHERE  idCategory = " & idParentCategory
		set rs = openRSexecute(mySQL)
		if rs.eof then
			errMsg = "Invalid Parent Category."
			call closeDB()

			Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
		end if
		call closeRS(rs)
	end if
	
	'Check idParentCategory not linked to products
	mySQL = "SELECT idCategory " _
	      & "FROM   categories_products " _
	      & "WHERE  idCategory = " & idParentCategory
	set rs = openRSexecute(mySQL)
	if not rs.eof then
		errMsg = "The Parent Category can not have products directly linked to it."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	call closeRS(rs)
	
	'Get categoryFeatured
	categoryFeatured = UCase(trim(Request.Form("categoryFeatured")))
	if categoryFeatured <> "Y" and categoryFeatured <> "N" then
		errMsg = "Invalid Featured value."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get sortOrder
	sortOrder = Request.Form("sortOrder")
	if sortOrder = "" or not isNumeric(sortOrder) then
		sortOrder = "null"
	end if
	
	'Get Category HTML (Short)
	categoryHTML = trim(Request.Form("categoryHTML"))
	if len(categoryHTML) > 255 then
		errMsg = "Category HTML can not exceed 255 characters."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Get Category HTML (Long)
	categoryHTMLLong = trim(Request.Form("categoryHTMLLong"))
	
end if

'ADD
if action = "add" then

	'Add Record
	mySQL = "INSERT INTO categories (" _
	      & "categoryDesc, idParentCategory, " _
	      & "categoryFeatured, categoryHTML, " _
	      & "sortOrder,categoryHTMLLong,breadCrumb,breadCrumbLinked" _
	      & ") VALUES (" _
	      & "'" & replace(categoryDesc,"'","''") & "'," _
	      &       idParentCategory				 & "," _
	      & "'" & categoryFeatured				 & "'," _
	      & "'" & replace(categoryHTML,"'","''") & "'," _
	      &       sortOrder						 & "," _
	      & "'" & replace(categoryHTMLLong,"'","''") & "'," _
	      & "'" & validSQL(getCategoryPos(idParentCategory,"","n"),"A") & "'," _
	      & "'" & validSQL(getCategoryPos(idParentCategory,"","y"),"A") & "'" _
	      & ")"
	set rs = openRSexecute(mySQL)
	errMsg = "Category was added." 
	call closeDB()
	Response.Redirect "SA_cat.asp?curPage=" & curPage & "&msg=" & server.URLEncode(errMsg)
	
end if

'DELETE or BULK DELETE
if action = "del" or action = "bulkdel" then

	'Declare additional variables
	dim delI		'Array index
	dim delArray	'List of idCategories that will be deleted
	
	'If just one delete is being performed, we populate just the 
	'first position in the delete array, else we populate the array
	'with a list of all the records that were selected for deletion.
	if action = "del" then
		delArray = split(idCategory)
	else
		delArray = split(Request.Form("idCategory"),",")
	end if
	
	'Set CursorLocation of the Connection Object to Client
	cn.CursorLocation = adUseClient
	
	'Loop through list of records and delete one by one
	for delI = LBound(delArray) to UBound(delArray)
	
		'BEGIN Transaction
		cn.BeginTrans
		
		'Delete Record
		mySQL = "DELETE FROM Categories_Products " _
		      & "WHERE  idCategory = " &  trim(delArray(delI))
		set rs = openRSexecute(mySQL)
		
		'Delete from langauge file
		mySQL = "DELETE from language_categories " _
			  & "WHERE idLang LIKE '%" & trim(delArray(delI)) & "'"
		set rs = openRSexecute(mySQL)
		

		'Delete Category
		mySQL = "DELETE FROM categories " _
		      & "WHERE  idCategory = " &  trim(delArray(delI))
		set rs = openRSexecute(mySQL)

		'END Transaction
		cn.CommitTrans
		
	next
	errMsg = "Category(s) were deleted."
	call closeDB()

	Response.Redirect "SA_cat.asp?msg=" & server.URLEncode(errMsg)

end if

'EDIT
if action = "edit" then

	'Check idCategory <> idParentCategory
	if idCategory = idParentCategory then
		errMsg = "Category can not be linked to itself."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	
	'Check that edited Category is not being linked to one of it's 
	'own sub-categories
	call expandCategory(idCategory)
	'
	' get current category description in case it was changed
	'
	mySQL = "SELECT categoryDesc FROM categories WHERE idCategory = " & idCategory
	set rs = openRSexecute(mySQL)
	oldCatDesc = rs("categoryDesc")
	'
	' Update current category record	
	'
	mySQL = "UPDATE categories SET " _
	      & "       categoryDesc = '"     & replace(categoryDesc,"'","''") & "'," _
	      & "       idParentCategory = "  & idParentCategory & "," _
	      & "       categoryFeatured = '" & categoryFeatured & "'," _
		  & "       categoryHTML = '"     & replace(categoryHTML,"'","''") & "'," _
		  & "       sortOrder = "		  & sortOrder & "," _
		  & "       categoryHTMLLong = '" & replace(categoryHTMLLong,"'","''") & "'," _
		  & "		breadCrumb = '" 	  & validSQL(getCategoryPos(idParentCategory,"","n"),"A") & "'," _
		  & "		breadCrumbLinked = '" & validSQL(getCategoryPos(idParentCategory,"","y"),"A") & "' " _
	      & "WHERE  idCategory = " & idCategory
	set rs = openRSexecute(mySQL)
	'
	' Check othere records for name change
	'
	'Response.write oldCatDesc & " " & replace(categoryDesc,"'","''") & "<br/>"
	if oldCatDesc <> replace(categoryDesc,"'","''") then
		' update breadCrumb
		mySQL = "SELECT idCategory, breadCrumb FROM categories WHERE breadCrumb LIKE '%" & validSQL(oldCatDesc,"A") & "%'"
		set rs = openRSexecute(mySQL)
		do while Not rs.eof
			idCategory = rs("idCategory")
			breadCrumb = rs("breadCrumb")
			breadCrumb = replace(breadCrumb," &gt  ", " &gt; ")
			breadCrumb = replace(breadCrumb,"&gt; " & oldCatDesc, "&gt; " & replace(categoryDesc,"'","''"))
			mySQL = "UPDATE categories SET breadCrumb = '" & validSQL(breadCrumb,"A") & "' WHERE idCategory = " & idCategory & ";"
			'Response.write mySQL & "<br/>"
			set rsTemp = openRSexecute(mySQL)
			rs.movenext
		loop
		' update breadCrumbLinked
		mySQL = "SELECT idCategory, breadCrumbLinked FROM categories WHERE breadCrumbLinked LIKE '%" & validSQL(oldCatDesc,"A") & "%'"
		set rs = openRSexecute(mySQL)
		do while Not rs.eof
			idCategory = rs("idCategory")
			breadCrumbLinked = rs("breadCrumbLinked")
			breadCrumbLinked = replace(breadCrumbLinked,">" & oldCatDesc, ">" & replace(categoryDesc,"'","''"))
			mySQL = "UPDATE categories SET breadCrumbLinked = '" & validSQL(breadCrumbLinked,"A") & "' WHERE idCategory = " & idCategory & ";"
			'Response.write mySQL & "<br/>"
			set rsTemp = openRSexecute(mySQL)
			rs.movenext
		loop		
	end if
	errMsg = "Category was edited."
	call closeDB()

	Response.Redirect "SA_cat.asp?msg=" & server.URLEncode(errMsg)
	'Response.end
end if

'ROOT
if action = "root" then

	'Check no Root Category exists
	mySQL = "SELECT idCategory " _
	      & "FROM   categories " _
	      & "WHERE  idParentCategory = 0"
	set rs = openRSexecute(mySQL)
	if not rs.eof then
		errMsg = "Root Category already exists."
		call closeDB()

		Response.redirect "sysMsg.asp?errMsg=" & server.URLEncode(errMsg)
	end if
	call closeRS(rs)

	'Create Root Record
	mySQL = "INSERT INTO categories (" _
	      & "categoryDesc, idParentCategory, " _
	      & "categoryFeatured, categoryHTML,case lCase("payMsgPayPal")
		payMsgPayPal		= rs("configVal")
	case lCase("payMsgTwoCheckOut")
		payMsgTwoCheckOut	= rs("configVal")
	case lCase("payMsgOther")
		payMsgOther			= rs("configVal")
	case lCase("payMsgNotReq")
		payMsgNotReq		= rs("configVal")
	case lCase("pEmailFriendSec")
		pEmailFriendSec		= rs("configVal")
	case lCase("pMaxDownloadHours")
		pMaxDownloadHours	= rs("configVal")
	case lCase("pMaxDownloadCount")
		pMaxDownloadCount	= rs("configVal")
	case lCase("payDefault")
		payDefault			= rs("configVal")
	case lCase("pAuthNetFrontEnd")
		pAuthNetFrontEnd	= rs("configVal")
	case lCase("pCompanyAddr")
		pCompanyAddr		= rs("configVal")
	case lCase("payMsgAuthNet")
		payMsgAuthNet		= rs("configVal")
	case lCase("TwoCheckoutMD5")
		TwoCheckoutMD5		= rs("configVal")
	case lCase("pHideAddStockLevel")
		pHideAddStockLevel	= rs("configVal")
	case lCase("payCustom")
		payCustom			= rs("configVal")
	case lCase("payMsgCustom")
		payMsgCustom		= rs("configVal")
	case lCase("taxOnShipping")
		taxOnShipping		= rs("configVal")
	case lCase("allowShipAddr")
		allowShipAddr		= rs("configVal")
	case lCase("prodViewLayout")
		prodViewLayout		= rs("configVal")
	case lCase("shipDisplayType")
		shipDisplayType		= rs("configVal")
	case lCase("defaultCountryCode")
		defaultCountryCode	= rs("configVal")
	case lCase("payCallIn")
		payCallIn			= rs("configVal")
	case lCase("payFaxIn")
		payFaxIn			= rs("configVal")
	case lCase("payCOD")
		payCOD				= rs("configVal")
	case lCase("payMsgCallIn")
		payMsgCallIn		= rs("configVal")
	case lCase("payMsgFaxIn")
		payMsgFaxIn			= rs("configVal")
	case lCase("payMsgCOD")
		payMsgCOD			= rs("configVal")
	case lCase("listViewLayout")
		listViewLayout		= rs("configVal")
	case lCase("taxBillOrShip")
		taxBillOrShip		= rs("configVal")
	case lCase("statUpdPending")
		statUpdPending		= rs("configVal")
	case lCase("handlingFeeAmt")
		handlingFeeAmt		= rs("configVal")
	case lCase("handlingFeeTax")
		handlingFeeTax		= rs("configVal")
	case lCase("payPalCurrCode")
		payPalCurrCode		= rs("configVal")
	case lCase("authNetTxKey")
		authNetTxKey		= rs("configVal")
	case lCase("homeViewLayout")
		homeViewLayout		= rs("configVal")
	case lCase("pEmailStockLevel")
		pEmailStockLevel	= rs("configVal")
	case lCase("pAuthNetType")
		pAuthNetType		= rs("configVal")
	case lCase("pHTMLarea")
		pHTMLarea			= rs("configVal")
	case lCase("pProdThumbs")
		pProdThumbs			= rs("configVal")
	case lCase("homeViewRandom")
		homeViewRan
