var isPatron=false;
var checkoutway="2"

var iCounter=1;

var gOrder = new Array();
var gPerfs = new Array();
var gIsSeason = false;
var gSeasonLightningSeat = false;
gOrder["TicketsXML"] = "<Tickets></Tickets>";
gOrder["SubscriptionsXML"] = "<Subscriptions></Subscriptions>";
var gQuickSaleMode = false;

var Events = new Array();
var arrItems  = new Array();
var arrTkPerf  = new Array();
var arrTkPerTypes  = new Array();
var arrTickets  = new Array();
var arrSubscriptions  = new Array();
var arrChangedSeats = new Array();
var SeasonPackages = new Array();
var gCurrentOrderId="";
var gCurrentPaymentXML;
var gCurrentClientXML;
var gCurrentPerformanceId;
var gCurrentPerformanceName;
var gCurrentPerformanceDate;
//var gCurrentTicketXML;
var gCurrentTicketOrderDetailsXML;
var gClientId;
var gOrderCompleted = 0;
var gVenueId = 0;
var gOrderTotal = 0;
var gOrderTotalTPS = 0;
var gSubscriptionTotal = 0;
var gTicketsTotal = 0;
var gShippingAddress;
var gTransactionTotal = 0;
var gClientCoupons = null;
var gSeasonRunNumber = null;
var gSeasonRunId = null;
var gCallBack = false;
var gCurrentOrderXML = "";
var gGetPerfIdOnly = false;
var gSecid=null;

var tickets = new Array();
var hexdec = new Array();
var thisdata = new Array();
var aryPayTypes = new Array();
var htmlstr = "";
var strTransXML;
var formFocusTempVal;
var bTPSTransaction=false;
var vHoldOverlayId;

//object factory, proxy for object calls	
var gSOAPListenerURL = "UserControls/ObjectFactory.aspx";
var gFunctionXmlHttpRequestAnisochronousComplite = null;

//OrderManager.js
var gItemId = null;
var gOrderId = null;
var	gCountTixEdit= null;
var gAddressFindType="patron";//"bill","shipp" - by address scope; "patron" - by patron scope
var gnCoupon=0;
//END OrderManager.js

//GetTickets.js
/*
* oParentIDHolder is an array consisting of currently selected object ID's
* e.g. if user selected all venues for Polinesian Cultural Center as a current Client, then
* the id of this client is recorded as a parentID for Venues object. e.g.
* - oParentIDHolder["Venues"] = CurrentClientID;
* - also we will save XML of selected object. i.e. oParentIDHolder["VenuesXML"] = "<Client><ID>6</ID></Client>"
* - and type of parent object, oParentIDHolder["VenuesParentType"] = "Client"
*/
var oParentIDHolder = new Object();
//END GetTickets.js


/** xmlData:
			"<cmds>" +
					"<cmd>" +
					"<fn>FunctionName</fn>" +
					"<arg>argument0</arg>" +
					"<arg>argument1</arg>" +
					...
					"</cmd>"
				"</cmds>";
*/

function FunctionFactory(xmlData) {
	if(null == xmlData) 
	{
		//clickTab(0);
		return;
	}
	var xmlDoc
	if(!isSafari) 
		{
		xmlDoc= jsXML.createDOMDocument("", "root");
		xmlDoc.loadXML(xmlData)
		}
	else 
		{
		xmlDoc = new DOMParser();
		xmlDoc = xmlDoc.parseFromString(xmlData, "text/xml");
		}
	var cmds = xmlDoc.getElementsByTagName("cmd");
	for(var iC = 0; iC < cmds.length; iC++)
	{
		var cmd = cmds[iC];
		var oFns = cmd.getElementsByTagName("fn");
		if(null == oFns)
			continue;
		var strFunction = oFns[0].firstChild.nodeValue;
		if("" == strFunction) 
			continue;
		var oArgs = cmd.getElementsByTagName("arg");
		var args = new Array();
		var strArgs = "";
		for(var iA = 0; iA < oArgs.length; iA++)
		{
			args[iA] = "";
			if(null != oArgs[iA].firstChild)
				args[iA] = oArgs[iA].firstChild.nodeValue;
			strArgs += "args["+iA+"],";
		}
		strArgs = strArgs.substring(0,strArgs.length-1);
		eval(strFunction + "("+strArgs+");");
	}
}
function SelectPerformanceBodyClick()
{
	if(null != gEBI('divOrderExtraFees'))
		gEBI('divOrderExtraFees').style.display='none';
}

function ToUpperCaseFirstChars(pSentence, pDelimiter)
{
	var lWords = pSentence.split(pDelimiter);
	pSentence = "";
	for(var i=0; i<lWords.length; i++)
	{
		lWord = lWords[i];
		pSentence += lWord.substr(0,1).toUpperCase()+lWord.substr(1);
		if(i < lWords.length-1) pSentence += pDelimiter;
	}
	return Trim(pSentence);
}
function CorrectName(pField)
{
	var lFV = pField.value;
	if(lFV != lFV.toUpperCase() && lFV != lFV.toLowerCase()) return;
	
	lFV = Trim(lFV).toLowerCase();
	lFV = ToUpperCaseFirstChars(lFV," ");
	lFV = ToUpperCaseFirstChars(lFV,"-");
	lFV = ToUpperCaseFirstChars(lFV,".");
	
	pField.value = lFV;
}

function GetPerformances()
{
	document.frmPerformance.StartDate.value = arguments[0];
  	document.frmPerformance.submit();
}
function HideLegend()
{ 
	$("#divLegend").hide();
}
function ShowLegend()
{	
//	alert(gEBI('divImageMap').innerHTML)
	if(gEBI('divImageMap').innerHTML.indexOf('GAQuantity') ==-1)
		gEBI('divLegend').style.display = "block";
}


function prepareForBypassGetSections()
{
	if (null!=gEBI('divOrders'))
	gEBI('divOrders').style.display = 'none';
	if (null!=gEBI('divNonOrders'))
	HideScanTabs();
	gEBI('divNonOrders').style.display = 'block';
	//hide confirm
	var vPerformanceId = arguments[0];
	var oDivConfirm = gEBI('divConfirm');
	if (vPerformanceId!=-1)
	  if(null != oDivConfirm)
		oDivConfirm.style.display = 'none';
}					
					
function SetUnsetAsDefaultPerformance(cl,perfId,evId,vid,lid,sdy,sdm,sdd,sdh,sdmin,sds,checked)
{
	if(checked)
	{
		var dt = new Date();
		dt.setMonth(dt.getMonth()+1);
		SetCookie(cl+"eid",evId,dt,"/");
		SetCookie(cl+"pid",perfId,dt,"/");
		SetCookie(cl+"vid",vid,dt,"/");
		SetCookie(cl+"lid",lid,dt,"/");
		SetCookie(cl+"sdy",sdy,dt,"/");
		SetCookie(cl+"sdm",sdm,dt,"/");
		SetCookie(cl+"sdd",sdd,dt,"/");
		SetCookie(cl+"sdh",sdh,dt,"/");
		SetCookie(cl+"sdmin",sdmin,dt,"/");
		SetCookie(cl+"sds",sds,dt,"/");
	}
	else
	{
		DeleteCookie(cl+"eid","/");
		DeleteCookie(cl+"pid","/");
		DeleteCookie(cl+"vid","/");
		DeleteCookie(cl+"lid","/");
		DeleteCookie(cl+"sdy","/");
		DeleteCookie(cl+"sdm","/");
		DeleteCookie(cl+"sdd","/");
		DeleteCookie(cl+"sdh","/");
		DeleteCookie(cl+"sdmin","/");
		DeleteCookie(cl+"sds","/");
	}
}
function SetUnsetAsDefaultSection(cl,perfId,secId,checked)
{
	if(checked)
	{
		var dt = new Date();
		dt.setMonth(dt.getMonth()+1);
		SetCookie(""+cl+""+perfId+"sid",secId,dt,"/");
	}
	else
	{
		DeleteCookie(""+cl+""+perfId+"sid","/");
	}
}
function SetUnsetAsDefaultScanSection(cl,perfId,secId,checked)
{
	if(checked)
	{
		var dt = new Date();
		dt.setMonth(dt.getMonth()+1);
		SetCookie(""+cl+""+perfId+"scansid",secId,dt,"/");
	}
	else
	{
		DeleteCookie(""+cl+""+perfId+"scansid","/");
	}
}

/*
arguments[0] = performance id
arguments[1] = venue id
arguments[2] = layout id
arguments[3] = client id
arguments[4] = user id
*/

function runGetSections()
{
	var xmlData = 
				"<cmds>" +
					"<cmd>" +
					"<fn>GetSections</fn>" +
					"<arg>"+arguments[0]+"</arg>" +
					"<arg>"+arguments[1]+"</arg>" +
					"<arg>"+arguments[2]+"</arg>" +
					"<arg>"+arguments[3]+"</arg>" +
					"<arg>"+arguments[4]+"</arg>" +
					"<arg>"+arguments[5]+"</arg>";
	if("undefined" != typeof(arguments[6]))
		xmlData += "<arg>"+arguments[6]+"</arg>";
	if("undefined" != typeof(arguments[7]))
		xmlData += "<arg>"+arguments[7]+"_</arg>";
	if("undefined" != typeof(arguments[8]))
		xmlData += "<arg>"+arguments[8]+"</arg>";
	if("undefined" != typeof(arguments[9]))
		xmlData += "<arg>"+arguments[9]+"</arg>";
		xmlData +=	"</cmd>" +
				"</cmds>";
	handleMouseClick("getsections"+arguments[0],xmlData,"CallBackSALES");
}
	
function GetSections()
{
	HideScanTabs();
	//check for quick sale mode
	if(gQuickSaleMode == true)
	{
		SetCookie("QuickSalePerformance", arguments[0],null,"/");
		runShowQuickSale();
		return;
	}
	//used for quick ticket echange ticketsechange.aspx
	if(gGetPerfIdOnly == true)
	{
		SetCookie("QuickExchangePerformance", arguments[0],null,"/");
		gPerformanceId = arguments[0];
		window.location.reload();
		return;
	}
	window.scroll(0, 0);
	// back & forward buttons
	if($('#divOrders').length > 0)
	{
		$("#divCart").hide();
		$("#divPayCart").hide();
		$("#divConfirm").hide();

		$("#divImageMap").html("");
		$("#divImageMap").show();
	}

	$('#divOrders').hide();
	$('#divNonOrders').show();
	
	//hide confirm
	var vPerformanceId = arguments[0];
	if (vPerformanceId!=-1)	
		$("#divConfirm").hide();
	
	//if(null != gCountTixEdit) 
	gPerformanceId = vPerformanceId;
	
	var vVenueId = arguments[1];
	var vLayoutId = arguments[2];
	var vClientId = arguments[3];
	var vPricingOverlayId='';
	var vDefaultSectionId = 0;
	var vSectionId = 0;	
	vHoldOverlayId='0';
	var vSeasonPackageId = -1;
	vSeasonPackageName = "";
	if (vPerformanceId!=-1)
	if("undefined" != typeof(arguments[6]))
		vSeasonPackageId = arguments[6];
	if("undefined" != typeof(arguments[7]))
		vSeasonPackageName = arguments[7];
	if("undefined" != typeof(arguments[8]))
		vDefaultSectionId = arguments[8];
	
	gVenueId = vVenueId;
	//var vPerformanceDateTime = arguments[4];
	var dt = new Date(arguments[4]);
	
	if (vPerformanceId==-1)
	if("undefined" != typeof(arguments[6]))
	    vPricingOverlayId=arguments[6];
	    
    if("undefined" != typeof(arguments[7]))
	    vHoldOverlayId=arguments[7];
	    
    if("undefined" != typeof(arguments[9]))
	    vSectionId=arguments[9];
	
	//alert("vHoldOverlayId:"+vHoldOverlayId);
	var vPerformanceName = arguments[5];
	var soapMsgBody = "";
	var vEventId = -1;
	
	var sPerfList = "";
    var lCurrPerfs = GetCurrSeasonPerformanceList(gPerfs, vPerformanceId);
    for(var i = 0; i < lCurrPerfs.length; i++)
    {
		sPerfList +=lCurrPerfs[i][0]+",";
    }
    
    //if manual select only send next performance
    if(!gSeasonLightningSeat)
		sPerfList = vPerformanceId+",";
		
	soapMsgBody	 = "<SeasonPackage><ID>" + vSeasonPackageId + "</ID><sPerfIDs>"+sPerfList+"</sPerfIDs></SeasonPackage>";
	soapMsgBody += "<Performance><ID>" + vPerformanceId + "</ID></Performance>"
	soapMsgBody += "<Venue><ID>" +	vVenueId + "</ID></Venue>"
	soapMsgBody += "<Layout><ID>" +	vLayoutId + "</ID></Layout>";
	soapMsgBody += "<Client><ID>" +	vClientId + "</ID></Client>";
	if (vPerformanceId==-1)
	 { soapMsgBody += "<PricingOverlay><ID>" + vPricingOverlayId + "</ID></PricingOverlay>";
	   soapMsgBody += "<HoldOverlay><ID>" + vHoldOverlayId + "</ID></HoldOverlay>";
	  }
	if(vSectionId!=0)
	{
		soapMsgBody+= "<Section><ID>" + vSectionId + "</ID></Section>";
	}
	strSoapMessage = '<Envelope><Body>' + soapMsgBody + '</Body></Envelope>';
	
	gCurrentPerformanceId = vPerformanceId;
	gClientId = vClientId;
	gCurrentClientXML = "<Client><ID>" + vClientId + "</ID></Client>";

	if(-1 != vPerformanceId && gEBI('divH').innerHTML.indexOf('tblSelectedSeason') != -1)
		ShowSelectedPackageTable(vPerformanceId,vSeasonPackageId);
	if(-1 != vPerformanceId)
		ShowPleaseWaitMessage(document.getElementById('divSection'));
	if(-1 != vPerformanceId)	
	{ 
		if(isBox && -1 == vSeasonPackageId && null == gCountTixEdit && null != GetCookie(""+vClientId+""+vPerformanceId+"sid"))
		{
			GetSection(vPerformanceId,vLayoutId,vClientId,GetCookie(""+vClientId+""+vPerformanceId+"sid"),"-1","","-1","-1","-1",2);
			return "";
		}
		else if(isBox && -1 == vSeasonPackageId && null == gCountTixEdit && null != GetCookie(""+vClientId+""+vPerformanceId+"scansid"))
		{
			if(DefaultScanView(vPerformanceId,GetCookie(""+vClientId+""+vPerformanceId+"scansid"))==1) 
				return "";
		}
		
		//call sales_imagemap.ascx
		var afterGetSections = function()
			{
				$("#divSection").html("");
				if(isBox) // it is for default section - to add Edit Holds
				{
					$('#ulBestAvailable').html($('#SectionHoldManager').html());
					$('#ulBestAvailable').show();
				}
				
				ShowLegend();
				
				if(null == gItemId)
				{
					showBestAvailable();
				    
					var baTixCount = gEBI("Best_Available_TikCount");
					if(null != gCountTixEdit && null != baTixCount) //new image map
					{
						baTixCount.value = gCountTixEdit;
						baTixCount.readOnly = true;
						$("#divImageMap").hide();
						$("#divLegend").hide();
					}
				}
				
				if(gIsSeason || -1 != vSeasonPackageId)
				{
					if($("#hBestAvailable").length > 0)
						$("#ulBestAvailable").hide();
				}
				if(null != gItemId || gIsSeason)
				{
					$("#defPerformance").hide();
				}
				gIsSeason = false;
				
			}; //end afterGetSections
			
		window.setTimeout(function(){
			embedHTTPPage("Sales_ImageMap.aspx", strSoapMessage, 'divImageMap', afterGetSections);  
			}, 10);
	}
	else //vPerformanceId == -1
	{
		var afterGetSections = function()
			{
				$("#plzWait").hide();
			}
		
		window.setTimeout(function(){
			embedHTTPPage("Sales_ImageMap.aspx", strSoapMessage, 'divImageMap', afterGetSections);  
			}, 10);
	}
	
	return "";
}

function showBestAvailable()
{
	if(gEBI("hBestAvailable")!=null)
	{
		gEBI("ulBestAvailable").innerHTML = gEBI("hBestAvailable").innerHTML;
		gEBI("ulBestAvailable").style.display = "block";
		gEBI("hBestAvailable").innerHTML="";
	}
}
		
/// <summary>
///	Filters performances of current season package with equal layouts by performance.
/// </summary>
/// <param name="arrPerfs">All performances of current season package</param>
/// <param name="perfId">Current performance</param>
/// <returns>Comma separated string with Performances Id</returns>
function GetCurrSeasonPerformanceList(arrPerfs, perfId)
{
	var arrPerfList = new Array;
    var iLt = 0;//LayoutId
   	var bLayouts = false;
	for(var i = 0; i < gPerfs.length; i++)
	{
		if(gPerfs[i][0] == perfId)
			iLt = gPerfs[i][1];
		if(gPerfs[0][1]!=gPerfs[i][1])
			bLayouts = true;
	}

    for(var i = 0; i < arrPerfs.length; i++)
    {
		if((i>=iLayout-1 && !bLayouts || bLayouts) && iLt == arrPerfs[i][1] || iLt == 0)
			arrPerfList.push(arrPerfs[i]);
    }
    return arrPerfList;
}

function runGetSection(vPerformanceId,vLayoutId,vClientId,vSectionId)
{

	var xmlData = 
				"<cmds>" +
					"<cmd>" +
					"<fn>GetSection</fn>" +
					"<arg>"+vPerformanceId+"</arg>" +
					"<arg>"+vLayoutId+"</arg>" +
					"<arg>"+vClientId+"</arg>" +
					"<arg>"+vSectionId+"</arg>";
	if("undefined" != typeof(arguments[4]))
		xmlData += "<arg>"+arguments[4]+"</arg>";
	xmlData +=	"</cmd>" +
			"</cmds>";

	handleMouseClick("getsection"+vSectionId,xmlData,"CallBackSALES");
}
/*
arguments[0] = performance id
arguments[1] = venue id
arguments[2] = layout id
arguments[3] = client id
arguments[4] = user id
*/
function ScanView()
{
	var tdScanView = gEBI("tdScanView");
	var tdDefaultView = gEBI("tdDefaultView");
	
	var dt = new Date();
	dt.setMonth(dt.getMonth()+1);
	SetCookie(tdScanView.getAttribute("PerformanceId")+"scanview",1,dt,"/");
	
	SetTabToScan(tdScanView,tdDefaultView);
	GetScanSectionView(tdScanView.getAttribute("PerformanceId"),tdScanView.getAttribute("SectionId"));
}

function SetTabToScan(tdScanView,tdDefaultView)
{
	if(null != tdScanView && null != tdDefaultView)
	{
		tdScanView.style.cursor = "default";
		tdScanView.style.color = "#C24124"
		tdScanView.style.backgroundColor = "#FFFFFF";
		tdScanView.style.border = "1 solid #75747A";
		tdScanView.style.borderBottom = "none";
		
		tdDefaultView.style.cursor = "pointer";
		tdDefaultView.style.color = "#000000"
		tdDefaultView.style.backgroundColor = "#D6D7DE";
		tdDefaultView.style.border = "none";
		tdDefaultView.style.borderBottom = "1 solid #75747A";
	}
}

function DefaultScanView(vPerformanceId,vSectionId)
{
	if (null!=gEBI('tabCalendar') && null!=gEBI('MapViewTabs'))
	{
	gEBI('tabCalendar').style.display = 'none';
	gEBI('MapViewTabs').style.display = 'block';
	var tdScanView = gEBI("tdScanView");
	var tdDefaultView = gEBI("tdDefaultView");
	SetTabToScan(tdScanView,tdDefaultView);
	GetScanSectionView(vPerformanceId,vSectionId);
	return 1;
	}
	return 0;
}

function GetScanSectionView(vPerformanceId,vSectionId)
{
var soapMsgBody = "<Performance><ID>" + vPerformanceId + "</ID></Performance>";
	soapMsgBody += "<Section><ID>" +vSectionId + "</ID></Section>";

	strSoapMessage = '<Envelope><Body>'+ soapMsgBody + '</Body></Envelope>';
	if (null!=document.getElementById('divSection'))
		ShowPleaseWaitMessage(document.getElementById('divSection'));
		
	//hide BA
	if(null != gEBI('ulBestAvailable'))
		gEBI('ulBestAvailable').style.display = "none";
	
	 window.setTimeout(function(){ 
			embedHTTPPage("Sales_SelectSeats.aspx?view=scanmap", strSoapMessage, 'divSection', true);				
			}, 10);
}

function DefaultSeatsView()
{
	var tdScanView = gEBI("tdScanView");
	var tdDefaultView = gEBI("tdDefaultView");
	
	DeleteCookie(""+tdScanView.getAttribute("PerformanceId")+"scanview","/");
	
	if(null != tdScanView && null != tdDefaultView)
	{
		tdDefaultView.style.cursor = "default";
		tdDefaultView.style.color = "#C24124"
		tdDefaultView.style.backgroundColor = "#FFFFFF";
		tdDefaultView.style.border = "1 solid #75747A";
		tdDefaultView.style.borderBottom = "none";
		
		tdScanView.style.cursor = "pointer";
		tdScanView.style.color = "#000000"
		tdScanView.style.backgroundColor = "#D6D7DE";
		tdScanView.style.border = "none";
		tdScanView.style.borderBottom = "1 solid #75747A";
	}
	GetSection(tdDefaultView.getAttribute("PerformanceId"),tdDefaultView.getAttribute("LayoutId"),tdDefaultView.getAttribute("ClientId"),tdDefaultView.getAttribute("SectionId"),tdDefaultView.getAttribute("SeasonPackageId"),tdDefaultView.getAttribute("SeasonPackageName"),tdDefaultView.getAttribute("PricingOverlayId"),tdDefaultView.getAttribute("VenueId"),tdDefaultView.getAttribute("HoldOverlayId"));
}

function HideScanTabs()
{
	if(!isWeb)
		$('#tabCalendar').show();
	
	$('#MapViewTabs').hide();
}

function GetSection(vPerformanceId,vLayoutId,vClientId,vSectionId)
{
	// back & forward buttons
	if($('#divOrders').length > 0)
	{
		$('#divCart').hide();
		$('#divPayCart').hide();
		$('#divConfirm').hide();

		HideLegend();
	
		$('#divSection').show();
	}

	gPerformancePieChart = null;
	$('#PerformancePieChart').hide();
	$('#divOrders').hide();
	
	$('#divNonOrders').show();
	
	$('#defPerformance').hide();
	$('#divMapLegend').hide();
	$('#ulBestAvailable').hide();
	
	var vSeasonPackageId	= -1;
	var vSeasonPackageName	= "";
	var vVenueId="";
	var vPricingOverlayId="";

    //if (vPerformanceId!=-1)
	   if("undefined" != typeof(arguments[4]))
	    	vSeasonPackageId = arguments[4];
	if("undefined" != typeof(arguments[5]))
		vSeasonPackageName = arguments[5];
		
	if (vPerformanceId==-1)
	 { if("undefined" != typeof(arguments[6]))
	      vPricingOverlayId=arguments[6];
	   
	   if("undefined" != typeof(arguments[7]))
	      vVenueId=arguments[7];   
	      
	   if("undefined" != typeof(arguments[8]))
	      vHoldOverlayId=arguments[8];   
     }	
	
    var xmlDisplayMode = "";
     if("undefined" != typeof(arguments[9]))
           xmlDisplayMode="<DisplayMode>"+arguments[9]+"</DisplayMode>";
    
    var sPerfList = "";
    var lCurrPerfs = GetCurrSeasonPerformanceList(gPerfs, vPerformanceId);
    for(var i = 0; i < lCurrPerfs.length; i++)
    {
		sPerfList +=lCurrPerfs[i][0]+",";
    }

    //if manual select only send next performance
    if(!gSeasonLightningSeat)
		sPerfList = vPerformanceId+",";
		  
	var soapMsgBody	 = "<SeasonPackage><ID>" + vSeasonPackageId + "</ID><sPerfIDs>"+sPerfList+"</sPerfIDs></SeasonPackage>";
		soapMsgBody += "<Performance><ID>" + vPerformanceId + "</ID></Performance>";
		soapMsgBody += "<Layout><ID>" +	vLayoutId + "</ID></Layout>";
		
		 soapMsgBody += oParentIDHolder["VenuesXML"];
  // if (vPerformanceId=-1)	
  //     	soapMsgBody += "<Venue><ID>" +	vVenueId + "</ID></Venue>"
      if (vPerformanceId==-1)
	   { soapMsgBody += "<PricingOverlay><ID>" + vPricingOverlayId + "</ID></PricingOverlay>";
	     soapMsgBody += "<HoldOverlay><ID>" + vHoldOverlayId + "</ID></HoldOverlay>";
	   }
		soapMsgBody += "<Section><ID>" +vSectionId + "</ID></Section>";

	strSoapMessage = '<Envelope><Body>'+ xmlDisplayMode + soapMsgBody + '</Body></Envelope>';

	gCurrentPerformanceId = vPerformanceId;
	gClientId = vClientId;
	
	$('#divLegend').hide();
	$('#tblPerformanceList').hide();

	if (vPerformanceId!=-1)
		if (null!=document.getElementById('divSection'))
			ShowPleaseWaitMessage(document.getElementById('divSection'));
		
	if (null!=gEBI('tabCalendar') && null!=gEBI('MapViewTabs'))
	{
		gEBI('tabCalendar').style.display = 'none';
		gEBI('MapViewTabs').style.display = 'block';
		var tdScanView = gEBI("tdScanView");
		var tdDefaultView = gEBI("tdDefaultView");
		if(tdScanView!=null)
			{
			tdScanView.setAttribute("PerformanceId",vPerformanceId);
			tdScanView.setAttribute("SectionId",vSectionId);			
			}
		if(tdDefaultView!=null)
			{
			tdDefaultView.setAttribute("PerformanceId",vPerformanceId);
			tdDefaultView.setAttribute("SectionId",vSectionId);	
			tdDefaultView.setAttribute("LayoutId",vLayoutId);	
			tdDefaultView.setAttribute("ClientId",vClientId);
			tdDefaultView.setAttribute("SeasonPackageId",vSeasonPackageId);
			tdDefaultView.setAttribute("SeasonPackageName",vSeasonPackageName);
			tdDefaultView.setAttribute("VenueId",vVenueId);
			tdDefaultView.setAttribute("PricingOverlayId",vPricingOverlayId);
			tdDefaultView.setAttribute("HoldOverlayId",vHoldOverlayId);						
			}
		SetTabToScan(tdDefaultView,tdScanView);	
	}
	if (vPerformanceId!=-1)
	    OrderImageMapZoomOut();
	if(GetCookie(""+vPerformanceId+"scanview")!=null)
	{
		ScanView();
		return "";
	}
	if (vPerformanceId!=-1)
	{
		var afterSelectSeats = function(){
				//put hold manager tool on left panel
				if(isBox)
				{
					$("#ulBestAvailable").html($("#SectionHoldManager").html());
					$("#ulBestAvailable").show();
				}
			}
		
		window.setTimeout(function(){
			embedHTTPPage("Sales_SelectSeats.aspx", strSoapMessage, 'divSection', afterSelectSeats);
			}, 10);
	}
	else   
	{
		if(null != gEBI("plzWait"))
			gEBI("plzWait").style.display = "block";
		window.setTimeout(function(){
			arrChangedSeats = new Array();
			embedHTTPPage("SelectSeatsHolds.aspx", strSoapMessage, 'divSection', true);
			if(null != gEBI("plzWait"))
			{
					gEBI("plzWait").style.display = "none";
					if(null != gCurrentBrush)
						if(null != gCurrentBrush["Name"] && null != gEBI("divVenueComment") && null != gEBI("divVenueCommentPOLevel"))
						{
							gEBI("divVenueComment").style.visibility="visible";
							gEBI("divVenueCommentPOLevel").innerHTML = gCurrentBrush["Name"];
							gEBI("divVenueCommentPOLevel").style.background = gCurrentBrush["Color"];
						}
			}
	   
		},10);
	}

	return "";
}

function AddBestAvailableToCart(PerformanceId,eventId,venueId,polvlId,preferences,ticketCount,chckSpanRows)
{
	var strReq = "";
	var lSpanRows = null == chckSpanRows?false:chckSpanRows.checked;
	if(null == gCountTixEdit)
		strReq = "BestAvailable.aspx?perfId="+PerformanceId+"&eventId="+eventId+"&venueId="+venueId+"&polvlId="+polvlId+"&preferences="+preferences+"&ticketCount="+ticketCount+"&spanRows="+lSpanRows;
	else
		strReq = "BestAvailable.aspx?exchange=1&perfId="+PerformanceId+"&eventId="+eventId+"&venueId="+venueId+"&polvlId="+polvlId+"&preferences="+preferences+"&ticketCount="+ticketCount+"&spanRows="+lSpanRows;
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: strReq,
				data: "<a>a</a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	if(null != gCountTixEdit)
	{
		var strHTML = "<br />" + strResp + "<br/><input class=buttonSc id=Add_To_Cart_js onclick=onApplyExchange() type=button value=Apply />";
		//$("#divImageMap").html(strHTML); //causes problem for quick exchange
		
		$("#divImageMap").html(strHTML);
	}
	else
	{
		gOrder["TicketsXML"] = strResp;
		runShowShoppingCart();
	}
}

function onBAAddToCart(pPerformanceId,pEventId,pVenueId)
{
	var oGAQuants = gEBI('GAQuantity');
	var oQuants = getChildrenByPartialIdOrName(oGAQuants, 'gapol', true);
	var StrXML = "";

	arrSeatInputs = new Array();

	for(var i=0; i<oQuants.length; i++)
	{
		if(parseInt(oQuants[i].value) > 0)
		{
			StrXML+="<BA><TicketType>"+oQuants[i].getAttribute("ttid")+"</TicketType>"+"<POLevel>"+oQuants[i].getAttribute("polid")+"</POLevel>"+"<Count>"+oQuants[i].value+"</Count></BA>";
		}
	}
    if(StrXML == "")
	{
		alert("Please Select a total of seats.");
		return;
	}
	
	strReq = "BestAvailable.aspx";
	StrXML="<Find><Performance>"+pPerformanceId+"</Performance>"+"<Event>"+pEventId+"</Event>"+"<Venue>"+pVenueId+"</Venue>"+StrXML+"</Find>";
   
    ShowProgressbar(0);
    
    $.post(strReq, StrXML, function(data){
			FillShoppingCartBA(data);
		});
}

function ShowMapInPopUp(MAPsrc)
{
	if($('#MapPopUp').length==0)
	{
		var MapPopUp=document.createElement("div");
		MapPopUp.id = "MapPopUp";
		MapPopUp.style.display="none";
		document.body.appendChild(MapPopUp);
	     $('#MapPopUp').dialog(
				{
				    modal: true,
				    resizable: true,
				    draggable: true,
				    autoOpen: false,
				    width: 800,
				    height: 600,
				    overlay: {
				        opacity: 0.5,
				        background: "black"
				    }
				}
			);
		$("#MapPopUp").show();
		$("#MapPopUp").dialog("open");	
		$("#MapPopUp").html("<img src='" + MAPsrc + "' />");
	}
	else
	{
		$("#MapPopUp").show();
		$("#MapPopUp").dialog("open");
		$("#MapPopUp").html("<img src='" + MAPsrc + "' />");
	}
	return false;
}

function AddToCartBASeats(pPerformanceId,pEventId,pVenueId,pSelect,pInput)
{
	var count = pSelect!=null ? pSelect.value : pInput.value;
	
	var polevel = $("#BAPOLevel").val();
	
    count = parseInt(count);
    if(isNaN(count) || count <= 0)
	{
		alert("Please Select a total of seats.");
		return;
	}
	
	var strReq = "BestAvailable.aspx?perfId="+pPerformanceId+"&eventId="+pEventId+"&venueId="+pVenueId+"&polvlId="+polevel+"&ticketCount="+count;
   
    ShowProgressbar();
    
    $.post(strReq, "<a></a>", 
		function(data){
			FillShoppingCartBA(data);
		});
}

function FillShoppingCartBA(strResp)
{
	ShowProgressbar();
	if(strResp=='<Tickets></Tickets>')
		{
		alert('No available Tickets Please change Count Of Tickets or select other POLevel');
		return;
		}
	gOrder["TicketsXML"] = strResp;
	ShowShoppingCart();
}

function onQuickSaleAddToCart()
{
	gQuickSaleMode = true;
	//set cookie for POLevel AND TicketType
	SetCookie("QSTicketType", gEBI("QSTicketType").value, null, "/");
	SetCookie("QSPOLevel", gEBI("qsPOLevel").value, null, "/");
	//check quantity
	if(gEBI("QSQuantity").value == "" || isNaN(gEBI("QSQuantity").value) == true)
	{
		alert("You must enter a valid quantity to proceed.");
		return false;
	}
	
	//var prf = lookupPerformance(gCurrentPerformanceId);
	var strReq = "";
	strReq = "BestAvailable.aspx?perfId="+gCurrentPerformanceId+"&eventId="+qsEventId+"&venueId="+qsVenueId+"&polvlId="+gEBI("qsPOLevel").value+"&preferences=front&ticketCount="+gEBI("QSQuantity").value;
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: strReq,
				data: "<a>a</a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	//inject tickettype node
	if(strResp.indexOf("<GA>True</GA>") >= 0)
	{
		strResp = strResp.replace(/<Ticket>/gi, "<Ticket GA='true'><TicketType><ID>" + gEBI("QSTicketType").value + "</ID></TicketType>");
	}
	else
		strResp = strResp.replace("<Ticket>", "<Ticket><TicketType><ID>" + gEBI("QSTicketType").value + "</ID></TicketType>");
	
	gOrder["TicketsXML"] = strResp;
	var currentSalesPayCart = gEBI("addressForm");
	ShowShoppingCart();
	
	var newSalesPayCart = gEBI("addressForm");
	var newSalesPayCartParent = newSalesPayCart.parentNode; 
	newSalesPayCartParent.removeChild(newSalesPayCart);
	newSalesPayCartParent.appendChild(currentSalesPayCart);
	
	//default tickettype
	var arrTTs = getChildrenByPartialIdOrName(gEBI("tblCart"), "tickettype_td", true);
	if(arrTTs.length > 0)
	{
		var oFirstTT = getChildByTagName(arrTTs[0], "SELECT", true)
		var oFirstTTArrow = getChildByTagName(arrTTs[0], "IMG", true)
		var TTstring = gEBI("QSTicketType")[gEBI("QSTicketType").selectedIndex].innerHTML
		ChangeSelectByValue(oFirstTT, TTstring, true)
		oFirstTTArrow.onclick();
	}

	if(gEBI('pay_0_total') != null)
		window.setTimeout(function(){gEBI('pay_0_total').value = parseFloat(gOrderTotal).toFixed(2)}, 100);
	gEBI("pc_process").style.display = "block";
	
}
function ReturnObjectFromSelectSeats(sObjName, ticketId, vPerformanceId, vLayoutId, vSectionId, vClientId, vSeasonPackageId, vSeasonPackageName)
{
	var strResp = ReturnObject(sObjName, ticketId);
	GetSection(vPerformanceId, vLayoutId, vClientId, vSectionId, vSeasonPackageId, vSeasonPackageName);
}
function ExchangeTicketFromSelectSeats(ticketId, PerformanceId, LayoutId, SectionId, ClientId, SeasonPackageId, SeasonPackageName)
{
	var str = "TicketExchange.aspx?ticketId="+ticketId+"&PerformanceId="+PerformanceId+"&LayoutId="+LayoutId+"&SectionId="+SectionId+"&ClientId="+ClientId+"&SeasonPackageId="+SeasonPackageId+"&SeasonPackageName="+SeasonPackageName;
	var wnd = window.open(str,'TicketExchangeWin','width=1050,height=700,scrollbars=yes,resize=yes,top=20,left=20,location=0,directories=0,toolbar=0,menubar=1');
}
function OrderSeatToggle(oTD, id, OrderId, sInput)
{
	var st = "";
	var oSeats = "";
	if(OrderId != "")
		oSeats = document.getElementById("OrderPackageSeatsInput" + OrderId);
	else
	{
		oSeats = document.getElementById(sInput);
		st = "st";	//add st to seatid for buytickets
	}

	if(oTD.getAttribute("isSelected") == "0")
	{
		oTD.style.backgroundColor = getValueFromXMLNode(oParentIDHolder["VenuesXML"], Array("Client", "IncartColor"), 0);
		oSeats.value += st + id + ","
		
		//add seatname to hidden input for orders
		if(OrderId != "")
			document.getElementById("OrderPackageSeatNames" + OrderId).value += oTD.getAttribute('title') + ",";

		oTD.setAttribute("isSelected", "1");

		if(OrderId != "" && OrderId != "-1" && gOrderLookupMode == false)
			OrderAutoFillQuantity(OrderId);

		//swap images if defined for this seat
		var oLImg = getChildByIdOrName(oTD, "large");
		var oSImg = getChildByIdOrName(oTD, "small");
		if(oSImg != null && oSImg.getAttribute("imagetype") == 'graphic')
		{
			InvertObjectVisibility(oLImg);
			InvertObjectVisibility(oSImg);
		}
	}
	else
	{
		oTD.style.backgroundColor = oTD.getAttribute("defCol");
		oSeats.value = oSeats.value.replace(st+id+",", "");

		//remove seatname from hidden input for orders
		if(OrderId != "")
		{
			var oSeatNames = document.getElementById("OrderPackageSeatNames" + OrderId);
			oSeatNames.value = oSeats.value.replace(oTD.getAttribute('title') + ",", "");
		}

		oTD.setAttribute("isSelected", "0");

		if(OrderId != "" && OrderId != "-1" && gOrderLookupMode == false)
			OrderAutoFillQuantity(OrderId);

		//swap images if defined for this seat
		var oLImg = getChildByIdOrName(oTD, "large");
		var oSImg = getChildByIdOrName(oTD, "small");
		if(oSImg != null  && oSImg.getAttribute("imagetype") == 'graphic')
		{
			InvertObjectVisibility(oLImg);
			InvertObjectVisibility(oSImg);
		}

	}
	//update running seat count
	OrderUpdateSeatCount(OrderId);
}

function OrderSectionZoomInOut(obj, OrderId)
{
	var oSectionTable = getParentByPartialId(obj, "SectionTable");
	var oSectionTD = oSectionTable.parentNode;
	var oSectionTR = oSectionTD.parentNode
	var oTDs = getChildrenByTagName(oSectionTR, "TD");
	var oTRs = getChildrenByTagName(oSectionTR.parentNode, "TR");
	if(oSectionTable.childNodes.length != 2)
		oSectionTable = oSectionTable.childNodes[0]; //fix for ie/ns table handling
	else
		oSectionTable = oSectionTable.childNodes[1]; //fix for ie/ns table handling

	//decide to zoom in or out.
	var strdsp = 'none';
	var cellspacing = 1;
	var nsize = 20;

	//hide zoom out link (with case for buy tickets)
	if(OrderId != "")
		document.getElementById("OrderSectionZoomOut"+OrderId).style.display = "block";
	else
		document.getElementById("OrderSectionZoomOut-1").style.display = "block";

	if(getChildByTagName(oSectionTable, "TD", true).style.width == nsize + "px")
	{
		strdsp = 'block';
		nsize = 10;
		cellspacing = 0;
		var oZoomLink = document.getElementById("OrderSectionZoomOut"+OrderId);
		if(oZoomLink != null)
			oZoomLink.style.display = "none";
	}

	//hide all sections cells in same row, aside from selected section's
	for(var i=0;i<oTDs.length;i++)
		if(oTDs[i] != oSectionTD)
			InvertObjectVisibility(oTDs[i]);

	//hide all tier rows in VenueTable, aside from selected section's
	for(var i=0;i<oTRs.length;i++)
		if(oTRs[i] != oSectionTR && oTRs[i].id.search("StaticRow") == -1)
			InvertObjectVisibility(oTRs[i]);

	//enlarge seat size to simulate zoom in
	oTRs = getChildrenByTagName(oSectionTable, "TR")
	oSectionTable.parentNode.cellSpacing = cellspacing;
	for(var i=0; i<oTRs.length;i++)
	{
		oTDs = getChildrenByTagName(oTRs[i], "TD");
		for(var j=0; j<oTDs.length;j++)
		{
			oTDs[j].style.width = nsize;
			oTDs[j].style.height = nsize;

			var oSmallImg = getChildByIdOrName(oTDs[j], "small");
			var oLargeImg = getChildByIdOrName(oTDs[j], "large");
			if(oSmallImg != null)
			{
				//if seat has a graphic invert it
				InvertObjectVisibility(oLargeImg);
				InvertObjectVisibility(oSmallImg);
			}

			//change text size if this seat has text defined
			var oTextDiv = oTDs[j];//getChildByTagName(oTDs[j], "DIV");
			if(oTextDiv != null && oTextDiv.innerHTML.search('nbsp') == -1)
			{
				if(nsize==10)
					oTextDiv.style.fontSize = "8px";
				else
					oTextDiv.style.fontSize = "14px";
			}
		}
	}

	//set tablewidth
	oSectionTable.style.width= ((oTDs.length)*nsize) + "px";
}

function OrderImageMapZoomOut()
{
	$("#divImageMap").hide();
	$("#MiniMapDiv").toggle();
}

function OrderUpdateSeatCount(nID)
{
	if(null != gEBI("selectedCount")) 
		gEBI("selectedCount").style.display = 'block';
		
	var oCountSpan = gEBI("selectedCount");
	var oSeatsInput = gEBI("txtSeats");
	var nCount = oSeatsInput.value.split(",").length - 1;

	if(oCountSpan != null)
		oCountSpan.innerHTML = nCount + " Selected";
}

function getPerformanceIndex(PerfID){
	var P = -1;
	for(var p=0;p<arrEvents.length;p++){
		if(arrEvents[p]['PerformanceId']==PerfID){
			P = p;
			break;
		}
	}
	return P;
}

function ShowCartContents()
{
	var spID = "";
	if("undefined" != typeof(arguments[0]))
		spID = arguments[0];

	//if coming from subscription seat selection
	if(isSeason==1 && iLayout<=gPerfs.length && (iLayout-1)>=0)
	{
		{
			ContinueSeats();
		}
		return;
	}
	else{
		var str = String(gEBI('txtSeats').value);
		if (str.substr(str.length-1) == ",")
			str = str.substr(0, str.length-1);

		var arrSeats = str.split(",");
		var strTicketsXML;
		if((null!=gOrder["TicketsXML"])&&(gOrder["TicketsXML"].length>0))
		{
			strTicketsXML = gOrder["TicketsXML"].replace("</Tickets>","");
		}
		else{
			strTicketsXML = "<Tickets>";
		 }

		if(arrSeats.length > 0 && arrSeats[0] != "")
			for(var st=0;st<arrSeats.length;st++){
				arrSeats[st] = arrSeats[st].replace("st","");
				var prf = lookupPerformance(gCurrentPerformanceId);
				if(arrSeats[st].indexOf('GA') < 0)
				{
					strTicketsXML += "<Ticket><Seat><ID>" + arrSeats[st] + "</ID></Seat><Performance><ID>" + gCurrentPerformanceId + "</ID>";
					if((prf!=null)&&(prf.Event!=null)&&(prf.Event.Venue!=null))	strTicketsXML +="<Event><ID>" + prf.Event.ID + "</ID><Venue><ID>" + prf.Event.Venue.ID + "</ID></Venue></Event>";
					strTicketsXML += "</Performance></Ticket>";
				}
				else
				{
					var arr = arrSeats[st].split("GA");
					arrSeats[st] = arr[0];
					strTicketsXML += "<Ticket GA='true'><TicketType><ID>" + arr[1] + "</ID></TicketType><Seat><ID>" + arrSeats[st] + "</ID></Seat>";
					strTicketsXML += "<Performance><ID>" + gCurrentPerformanceId + "</ID>";
					if((prf!=null)&&(prf.Event!=null)&&(prf.Event.Venue!=null))	strTicketsXML +="<Event><ID>" + prf.Event.ID + "</ID><Venue><ID>" + prf.Event.Venue.ID + "</ID></Venue></Event>";
					if(-1 != arr[2] && null != arr[2])
						strTicketsXML += "<TicketLimits><TicketLimit><Limit>"+arr[2]+"</Limit></TicketLimit></TicketLimits>";
					strTicketsXML += "</Performance></Ticket>";
				}
			}
		strTicketsXML += "</Tickets>";
	}

	gOrder["TicketsXML"] = strTicketsXML;

	runShowShoppingCart();
}
function runShowShoppingCart()
{
    
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
		"<fn>ShowShoppingCart</fn>" +
		"</cmd>" +
	"</cmds>";

	handleMouseClick("sc",xmlData,"CallBackSALES");
}
function ShowShoppingCart()
{
	HideLegend();
    HideScanTabs();
    if(null == gEBI('divNonOrders')) return;
	gEBI('divNonOrders').style.display = 'block';
	gEBI('divOrders').style.display = 'none';
	gEBI("ulBestAvailable").style.display = 'none';
	
	$("#selectedCount").hide();
	
	gOrder["ItemOrdersXML"] = "";
	
	gOrder["ItemOrdersXML"] = '<ItemOrders>';
	for(var i=0;i<arrItems.length;i++)
	 {
	   if (null!=arrItems[i] && null!=arrItems[i]["Price"])
		{   
            gOrder["ItemOrdersXML"] +="<ItemOrder><Item><ID>" + arrItems[i]["ID"] + "</ID><Name>" + arrItems[i]["Name"] + "</Name><Repeat>false</Repeat>"+"<IsMembership>"+arrItems[i]["IsMembership"]+"</IsMembership>";
            gOrder["ItemOrdersXML"] +="<Points>"+arrItems[i]["Points"]+"</Points>"
            gOrder["ItemOrdersXML"] +="<CanSellWithPoints>"+arrItems[i]["CanSellWithPoints"]+"</CanSellWithPoints>"
            gOrder["ItemOrdersXML"] +="<Category><isMember>"+arrItems[i]["isMemberCategory"]+"</isMember><CategoryType>"+arrItems[i]["CategoryType"]+"</CategoryType></Category>"
            gOrder["ItemOrdersXML"] +="<ListPrice>"+ FormatCurrency(arrItems[i]["Price"],2) + "</ListPrice></Item><Quantity>" + arrItems[i]["Qty"] + "</Quantity></ItemOrder>";
	    } 
     }

	gOrder["ItemOrdersXML"] += '</ItemOrders>';

	$("#divConfirm").hide();

	strSoapMessage = '<Envelope><Body><Order>' + gOrder["TicketsXML"] + gOrder["SubscriptionsXML"]+ gOrder["CouponOrdersXML"]+ gOrder["CouponPackageOrdersXML"]+ gOrder["ItemOrdersXML"] + '</Order></Body></Envelope>';
	//hide all DIVs except cart page
	$("#divH").html("");
	
	gEBI('divCart').style.display = "inline";
	gEBI('divPayCart').style.display='inline';
	
	$("#divSection").hide();
	$("#divImageMap").hide();
	
	var strURL = gShoppingCartURL;
	if($("#divPayCart").length > 0 && "" != $("#divPayCart").html())
		strURL += "?NoPayCart=1";
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: strURL,
				data: strSoapMessage,
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	if("" == strResp)
		return;

	CartInner(strResp);

	gOrder["TicketsXML"] = "";
	gOrder["SubscriptionsXML"] = "";
	gOrder["CouponOrdersXML"] = "";
	gOrder["CouponPackageOrdersXML"] = "";
	gOrder["ItemOrdersXML"] = "";
	arrItems = new Array();
	//initialize PayCart
	if(gIsSafari)
	{
	if(isBox) getPatronCoupons();
	PayCartComplite();
	}
	else
	{
	if(isWeb&&!isBox){
	window.setTimeout(function(){PayCartComplite();}, 10);
	}
	else
	window.setTimeout(function(){getPatronCoupons();PayCartComplite();}, 10);
	}
	//----------added by olegc 
	if (null!=gEBI("hIsEdit").value)
	  if (gEBI("hIsEdit").value=="Yes")
	    if (iCounter==1 )
	     { 
	       iCounter+=1;
	       var tempObj = new Object()
	       if(gEBN('hItemOrder')&&(gEBN('hItemOrder').length>0)){
		      for(var i=0;i<gEBN('hItemOrder').length;i++){
		        currentItem=parseInt(gEBN('hItemOrder')[i].getAttribute('ItemId')); 
		        if (typeof(arrItems[currentItem])=="undefined" ){
					addItemToBasket( currentItem,gEBN('hItemOrder')[i].getAttribute('ItemName'),parseFloat(gEBN('hItemOrder')[i].getAttribute('ListPrice')),gEBN('hItemOrder')[i].getAttribute('IsMembership'),gEBN('hItemOrder')[i].getAttribute('CanSellWithPoints'),gEBN('hItemOrder')[i].getAttribute('Points'),gEBN('hItemOrder')[i].getAttribute('isMemberCategory'),parseInt(gEBN('hItemOrder')[i].getAttribute('Quantity')),null,parseInt(gEBN('hItemOrder')[i].getAttribute('CategoryType')));
		           } 
		       }
	        }
	}
	//---------end------------------
	
}

function CartInner(strResp)
{
	var oSpan = document.createElement("SPAN");
	oSpan.innerHTML = strResp;
	var lWords = oSpan.innerHTML.split('<!-- PayCart -->');
	oSpan.innerHTML = lWords[0];
	gEBI('divCart').innerHTML = "";
	gEBI('divCart').appendChild(oSpan);

	if("undefined" == typeof(lWords[1]))
	{
		gEBI('divPayCart').style.display = "none";
		return;
	}
	if("" == lWords[1])
	{
		gEBI('divPayCart').style.display = "none";
		return;
	}
	if(-1 == lWords[1].indexOf("<"))
	{
		gEBI('divPayCart').style.display = "none";
		return; //no HTML in paycart
	}
	
	//process paycart
	if(gEBI('divPayCart').innerHTML=="")
	{
		oSpan = document.createElement("SPAN");
		oSpan.innerHTML = lWords[1];
		gEBI('divPayCart').innerHTML = "";
		gEBI('divPayCart').appendChild(oSpan);	
	}
	else
	{
		oSpan = document.createElement("SPAN");
		oSpan.innerHTML = lWords[1];
		oSpan=getChildByTagName(oSpan,'select',false);
		
		if(oSpan == null)
		{
			oSpan = document.createElement("SPAN");
			oSpan.innerHTML = lWords[1];
			oSpan = getChildByIdOrName(oSpan, gEBI("deliverymethodUniqueId").value, true);
		}
		
		pSelect = gEBI(gEBI("deliverymethodUniqueId").value);
		for(var i=pSelect.options.length; i>=0; i--)
		{
			pSelect.remove(i);
		}
             
		for(var i=0; i<oSpan.options.length; i++)
		{
			var opt = document.createElement('OPTION');
			opt.value = oSpan.options[i].value;
			opt.text = oSpan.options[i].text;		    
			opt.title = oSpan.options[i].text;	    
			if(oSpan.options[i].selected)
				opt.selected = true;
			pSelect.options.add(opt, pSelect.length);
		}
	}
}

function toggleWebStuff(pCnt){
	if(null == gEBI('divPayMethods')) return;
	if(isWeb&&!isBox){
		var lCCVal=	parseFloat(gEBI('txtTotal').value)-gTransactionTotal;
		if(lCCVal < 0) lCCVal = 0;
		gEBI('pay_'+pCnt+'_total').value = parseFloat(lCCVal).toFixed(2);
		gEBI('divPayMethods').style.display = 'inline';
	}
}

function runShowShoppingCartDirect()
{  
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
		"<fn>ShowShoppingCartDirect</fn>" +
		"<arg>"+arguments[0]+"</arg>" +		
		"</cmd>" +
	"</cmds>";

	handleMouseClick("sc",xmlData,"CallBackSALES");
}

function EracePaycart()
{
 if(gEBI('divPayCart')!=null) 
	gEBI('divPayCart').innerHTML="";
}

function ShowShoppingCartDirect()
{
	HideScanTabs();
	gEBI('divOrders').style.display = 'none';
	gEBI('divItems').style.display = 'none';
	gEBI('divNonOrders').style.display = 'block';
	gEBI('scleftlink').style.display='block';
	if (null!=gEBI('divItems'))
		gEBI('divItems').style.display = 'none';
	if(null != gEBI("divConfirm"))gEBI("divConfirm").style.display = "none";
	
	document.getElementById("divCart").style.display = "inline";
	
	ShowShoppingCart(arguments[0]);

	document.getElementById("divConfirm").style.display = "none";
	window.scroll(0,0);
}

function PayCartComplite()
{
	SetCountryAndState("patron");
	SetCountryAndState("shipping");
	
	DefaultDeliveryMethod();
	window.scroll(0,0);
	
	setDefaultPaymentType();
}
function AddPhone()
{
	var oAddPhones = gEBI("addPhones");
	var oAddPhonesShippSpace = gEBI("addPhonesShippSpace");
	
	var oPhoneType = gEBI("patron_phonetype");
	var iPhone = gEBN("AdditionalPhones").length;
	var strPhone = "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhone"+iPhone+"'>";
	strPhone +="<TR><TD class='tdFieldLeft' align='right'>&nbsp;Phone Number</TD>";
	strPhone +="<TD class='tdFieldRight' align='center'>";
	strPhone +="<INPUT type='text' class='textfield' id='AdditionalPhone"+iPhone+"' name='AdditionalPhones' onFocus='select();' PatronPhoneId='0' PhoneId='0'>";
	strPhone +="</TD>";
	strPhone +="<TD><span onmouseover='this.style.color=\"#fc6600\";' onmouseout='this.style.color=\"#000000\";'  style='cursor: pointer;' onclick='DeletePhone("+iPhone+");'><IMG src='images/remove.gif' border='0'></span></TD>";
	strPhone +="</TR>";
	strPhone +="</TABLE>";
	
	var strPhoneShippSpace = "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhoneShippSpace"+iPhone+"'><TR><TD>&nbsp;</TD></TR></TABLE>";


	if(null != oPhoneType)
	{
		strPhone += "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhoneType"+iPhone+"'>";
		strPhone +="<TR><TD class='tdFieldLeft' align='right'>&nbsp;Phone Type</TD>";
		strPhone +="<TD class='tdFieldRight' align='center'>";
		strPhone +="<SELECT id='AdditionalPhoneType"+iPhone+"' name='AdditionalPhoneTypes' PhoneTypeID='0'>"+oPhoneType.innerHTML+"</SELECT>";
		strPhone +="</TD>";
		strPhone +="</TR>";
		strPhone +="</TABLE>";
		
		strPhoneShippSpace += "<TABLE class='tblField' cellSpacing='0' cellPadding='1' id='tblAdditionalPhoneTypeShippSpace"+iPhone+"'><TR><TD>&nbsp;</TD></TR></TABLE>";
	}

	oAddPhones.innerHTML +=strPhone;
	oAddPhonesShippSpace.innerHTML +=strPhoneShippSpace;
}
function DeletePhone(iPhone)
{
	gEBI("AdditionalPhone"+iPhone).setAttribute('PhoneId','-1');
	gEBI("tblAdditionalPhone"+iPhone).style.display = "none";
	gEBI("tblAdditionalPhoneShippSpace"+iPhone).style.display = "none";
	if(null != gEBI("AdditionalPhoneType"+iPhone))
	{
		gEBI("AdditionalPhoneType"+iPhone).setAttribute('PhoneTypeID','-1');
		gEBI("tblAdditionalPhoneType"+iPhone).style.display = "none";
		gEBI("tblAdditionalPhoneTypeShippSpace"+iPhone).style.display = "none";
	}
}
function DefaultDeliveryMethod()
{
	if(null == gEBI("deliverymethodUniqueId"))
		return;

	var oDm = gEBI(gEBI("deliverymethodUniqueId").value);
	if(null == oDm) return;
	if(isWeb && !isBox)
	{
		var gotMail = false;
		for(var i = 0; i<oDm.options.length; i++)
			if(oDm.options[i].innerHTML == "Take Tickets Now")
			{
				oDm.remove(i);
				break;
			}
			else if(oDm.options[i].innerHTML == "Mail")
				gotMail = true;
		
		oDm.selectedIndex = 0;
		oDm.onchange();
		if(!gotMail)
			if(gEBI("MesMail") != null)
				gEBI("MesMail").style.display = "inline";
			
	}
	else
	{	try{
			if(gClientId == 16)
			{
				oDm.selectedIndex = 0;
				oDm.onchange();
			}
			else
			{
				oDm.onchange();
			}
		}catch(e){}
	}
}
function SetCountryAndState(strDetailType)
{	
	if(null != gEBI("sel"+strDetailType+"_country"))
	{
		gEBI("sel"+strDetailType+"_country").value = gEBI(strDetailType+"_country").value
		if(gEBI("sel"+strDetailType+"_country").value != gEBI(strDetailType+"_country").value || gEBI(strDetailType+"_country").value =="")
		{
			gEBI("sel"+strDetailType+"_country").value = "other";
			gEBI(strDetailType+"_country").style.display = "block";
		}
		else 		
			gEBI(strDetailType+"_country").style.display = "none";
	}

	var lSelState = gEBI("sel"+strDetailType+"_state");
	
	if(null == lSelState) return;
	if(null != gEBI("sel"+strDetailType+"_country") && null != gEBI("sel"+strDetailType+"_state_"+gEBI("sel"+strDetailType+"_country").value))
	{
		var lSelHiddenState = gEBI("sel"+strDetailType+"_state_"+gEBI("sel"+strDetailType+"_country").value);
		var lLength = lSelState.options.length;
		for (var i=lLength-1; i>=0; i--)
			lSelState.removeChild(lSelState.options[i]);
		for (var i=0; i<lSelHiddenState.options.length; i++)
		{
			lSelState.options[lSelState.options.length] = new Option(lSelHiddenState.options[i].innerHTML,lSelHiddenState.options[i].value);
		}
			
		//gEBI("sel"+strDetailType+"_state").innerHTML = gEBI("sel"+strDetailType+"_state_"+gEBI("sel"+strDetailType+"_country").value).innerHTML;
		
		lSelState.value = String(gEBI(strDetailType+"_state").value).replace(" ","");
		lSelState.style.display = "block";
		gEBI(strDetailType+"_state").style.display = "none";
	}
	else{
		gEBI("sel"+strDetailType+"_state").style.display = "none";
		gEBI(strDetailType+"_state").style.display = "block";
	}

}
function ChangeCountry(oThis,strDetailType)// strDetailType: shipping, patron
{
	if(oThis.value == "other"){
		gEBI(strDetailType+"_country").style.display = "block";
		gEBI(strDetailType+"_country").value = "";
	}
	else{
		gEBI(strDetailType+"_country").style.display = "none";
		gEBI(strDetailType+"_country").value = oThis.value;
	}
	var lSelState = gEBI("sel"+strDetailType+"_state");
	if(lSelState!=null)
	{
		var lSelHiddenState = gEBI("sel"+strDetailType+"_state_"+oThis.value);
		if(lSelHiddenState !=null)
		{
			var lLength = lSelState.options.length;
			for (var i=lLength-1; i>=0; i--)
				lSelState.removeChild(lSelState.options[i]);


			for (var i=0; i<lSelHiddenState.options.length; i++)
			{
						var oOption = document.createElement("OPTION");
						lSelState.options.add(oOption);
						oOption.innerHTML = lSelHiddenState.options[i].innerHTML;
						oOption.value = lSelHiddenState.options[i].value;
			}
			gEBI(strDetailType+"_state").value = lSelState.value;
			lSelState.style.display = "block";
			gEBI(strDetailType+"_state").style.display = "none";
		}
		else
		{
			lSelState.style.display = "none";
			gEBI(strDetailType+"_state").style.display = "block";
			gEBI(strDetailType+"_state").value = "";
		}
	}
}
function SetCustomCartFields(strHiddenName, bOther)
{
	var selName = gEBI("sel"+strHiddenName);
	var hName = gEBI(strHiddenName);
	
	if(null == selName && null != hName)
	{
		if("INPUT" == hName.tagName.toUpperCase())
		{
			if("CHECKBOX" == hName.type.toUpperCase())
			{
				try{
					hName.checked = eval(hName.value);
				}catch(e)
				{
					hName.checked = false;
				}
			}
		}
	}
	
	if(null == selName || null == hName) return false;
	
	if("SELECT" == selName.tagName.toUpperCase())
	{
		selName.value = hName.value
		if(selName.value != hName.value || Trim(hName.value) == "")
		{
			if(false == bOther)
			{
					if(Trim(hName.value) != "")
					{
						var oOption = document.createElement("OPTION");
						selName.options.add(oOption);
						oOption.innerHTML = hName.value;
						oOption.value = hName.value;
						selName.value = hName.value
					}
					hName.style.display = "none";
			}
			else
			{
				selName.value = "other";
				hName.style.display = "block";
			}
		}
		else 		
			hName.style.display = "none";
	}
	if("INPUT" == selName.tagName.toUpperCase())
	{
		if("CHECKBOX" == selName.type.toUpperCase())
		{
			try{
				selName.checked = eval(hName.value);
			}catch(e)
			{
				selName.checked = false;
			}
		}
		if("RADIO" == selName.type.toUpperCase())
		{
			var selN = gEBN("sel"+strHiddenName);
			for(var i=0; i<selN.length;i++)
				if(selN[i].value == hName.value)
					{
						selN[i].checked = true;
						break;
					}
		}
	}

}
function ChangeCustomCartDropDown(oThis,strHiddenName)
{
	if(oThis.value == "other"){
		gEBI(strHiddenName).style.display = "block";
		gEBI(strHiddenName).value = "";
	}
	else{
		gEBI(strHiddenName).style.display = "none";
		gEBI(strHiddenName).value = oThis.value;
	}
}
function CreatePayTypeControl(p,sSubName,sType,sValues)
{
	if("input" == sType)
		return '<input type="text" class="textfield" name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '" value="" onfocus="select();" />';
	if("checkbox" == sType)
		return '<input type="checkbox" onclick="gEBI(\'pay_' + p + sSubName+ '\').value=this.checked;">'+
			'<input type="text" style="display:none" class="textfield" name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '" value="false" onfocus="select();" />';
	if("dropdown" == sType)
	{
		var arrValues = sValues.split(";");
		strValues = '<select name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '">';
		for(var i=0; i<arrValues.length-1;i++)
			strValues +='<option value="'+arrValues[i]+'" >'+arrValues[i];
		strValues += '</select>';		
		return strValues;
	}
	if("radiobutton" == sType)
	{
		var arrValues = sValues.split(";");
		strValues = '<table>';
		for(var i=0; i<arrValues.length-1;i++)
			strValues +='<tr><td>'+ arrValues[i] +'</td><td><input type="radio" value="'+arrValues[i]+'" name="selPay_' + p + sSubName+ '" id="selPay_' + p + sSubName+ '" onclick="gEBI(\'pay_' + p + sSubName+ '\').value=this.value;"></td></tr>';
		strValues += '</table>';
		strValues += '<input type="text" style="display:none" class="textfield" name="pay_' + p + sSubName+ '" id="pay_' + p + sSubName+ '" value="" onfocus="select();" />';
		return strValues;
	}
}

function SwitchWebPaymentType(pTyp, oType, bDontDraw)
{
	//hide all transaction tables besides the one selected
	var cnt = 0;
	var oTable = gEBI('tblPay'+cnt);
	while(oTable != null)
	{
		var oSpanPayRemove = gEBI("spanPayRemove"+cnt);
		if(oType.selectedIndex != cnt)
		{
			oTable.style.display = "none";
			if(null != oSpanPayRemove)
				oSpanPayRemove.style.display = "inline";
		}
		else
		{
			oTable.style.display = "inline";
			if(oTable.style.display == "inline")
			{
				gEBI('pay_'+cnt+'_total').value="0.00";
				CheckTransactionTotals(null, false);
				toggleWebStuff(cnt);
			}
			if(null != gEBI("pay_"+cnt+"_code"))
				gEBI("pay_"+cnt+"_code").focus();
				
			if(null != oSpanPayRemove)
			{
				oSpanPayRemove.style.display = "none";
			}
		}
		
		cnt++;
		oTable = gEBI('tblPay'+cnt);
	}
}

/*
var thisdata = new Array();
var aryPayTypes = new Array();
var htmlstr = "";
*/
function AddPaymentType(pTyp, oType, bDontDraw)
{

	if(isWeb&&!isBox)
	{
		SwitchWebPaymentType(pTyp, oType, bDontDraw);
		CheckTransactionTotals(null, false);
		return;
	}
	if(pTyp == "")
		return;

	htmlstr = "";
	var newPT = null; //currently added paytype
	
	if ((pTyp != null)&&(pTyp != "undefined"))
	{
		var last = aryPayTypes.length;
		var initIndx = 0;
		
		for(var xx=0;xx<last;xx++)
			if(initIndx <= aryPayTypes[xx].initIndex)
				initIndx = aryPayTypes[xx].initIndex+1;
		
		var selOption = oType.options[oType.selectedIndex];
		aryPayTypes[last] = new Object();
		newPT = aryPayTypes[last];
		
		newPT.initIndex = initIndx; //used to handle cases when paytypes are added and deleted and it is impossible to get paytype by index in aryPayTypes
		newPT.Name = selOption.innerHTML;
		newPT.Value = pTyp;
		newPT.TransactionTypeId = selOption.getAttribute('TransactionTypeId');
		newPT.PaymenttypesClientId = selOption.getAttribute('PaymenttypesClientId');
		newPT.IsStandart = selOption.getAttribute('IsStandart');
		newPT.CCTYPES = selOption.getAttribute('CCTYPES'); //coded presentation of available CCTYPES in form ID:Name,ID:Name,ID:Name
		
		if("false" == aryPayTypes[last].IsStandart)
		{
			newPT.NameCustom1 = selOption.getAttribute('NameCustom1');
			newPT.NameCustom2 = selOption.getAttribute('NameCustom2');
			newPT.NameCustom3 = selOption.getAttribute('NameCustom3');
			newPT.NameCustom4 = selOption.getAttribute('NameCustom4');
			newPT.NameCustom5 = selOption.getAttribute('NameCustom5');
			newPT.TypeCustom1 = selOption.getAttribute('TypeCustom1');
			newPT.TypeCustom2 = selOption.getAttribute('TypeCustom2');
			newPT.TypeCustom3 = selOption.getAttribute('TypeCustom3');
			newPT.TypeCustom4 = selOption.getAttribute('TypeCustom4');
			newPT.TypeCustom5 = selOption.getAttribute('TypeCustom5');
			newPT.ValuesCustom1 = selOption.getAttribute('ValuesCustom1');
			newPT.ValuesCustom2 = selOption.getAttribute('ValuesCustom2');
			newPT.ValuesCustom3 = selOption.getAttribute('ValuesCustom3');
			newPT.ValuesCustom4 = selOption.getAttribute('ValuesCustom4');
			newPT.ValuesCustom5 = selOption.getAttribute('ValuesCustom5');
			newPT.IsEnabledCustom1 = selOption.getAttribute('IsEnabledCustom1');
			newPT.IsEnabledCustom2 = selOption.getAttribute('IsEnabledCustom2');
			newPT.IsEnabledCustom3 = selOption.getAttribute('IsEnabledCustom3');
			newPT.IsEnabledCustom4 = selOption.getAttribute('IsEnabledCustom4');
			newPT.IsEnabledCustom5 = selOption.getAttribute('IsEnabledCustom5');
		}
	}

	var curI = 0;
	if(true != bDontDraw)
	{
		curI = newPT.initIndex;
		
		var payType = newPT.Value;
		if (/*(pTyp == "credit")&&*/payType == "credit" || payType == "creditcardsave") {

			htmlstr += '<table id="tblPay' + curI + '" class="tblData">';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Credit_Card_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" class="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">';
			htmlstr += GetTranslation("Cardholder_s_Name");
			htmlstr += '<a href="JavaScript:doSwipe(' + curI + ');"><img class="ccSwipeImg" src="images/swipecard.gif" alt="';
			htmlstr += GetTranslation("swipe_credit_card");
			htmlstr += '" border="0" /></a><input type="text" style="color:#cc0000;background-color:#cc0000;width:8px;height:8px;" name="TrackData' + curI + '" id="TrackData' + curI + '" size="3" onfocus="startCheckLoop(' + curI + ');" onBlur="endCheckLoop(' + curI + ');" /></td>\n';
			htmlstr += '  <td class="tblDataTd" nowrap>\n';
			htmlstr += '  <input type="text" style="display:none" class="textfield" style="width:30px;" name="pay_' + curI + '_salutation" id="pay_' + curI + '_salutation" value="" onfocus="select();" />\n';
			htmlstr += '  <input type="text" class="textfield" style="width:66px;" name="pay_' + curI + '_firstname" id="pay_' + curI + '_firstname" value="" onfocus="select();" />\n';
			htmlstr += '  <input type="text" class="textfield" style="width:66px;" name="pay_' + curI + '_lastname" id="pay_' + curI + '_lastname" value="" onfocus="select();" />\n';
			htmlstr += '  <img style="cursor:pointer;" title="Paste Name" onclick="if(null != gEBI(\'pay_' + curI + '_firstname\')) gEBI(\'pay_' + curI + '_firstname\').value = gEBI(\'patron_firstname1\').value; if(gEBI(\'pay_' + curI + '_lastname\')) gEBI(\'pay_' + curI + '_lastname\').value = gEBI(\'patron_lastname1\').value;" src="images/paste.gif" />\n';
			htmlstr += '  </td>\n';
			htmlstr += ' </tr>\n';

			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Card_Type")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><select class="textfield" name="pay_' + curI + '_cardtype" id="pay_' + curI + '_cardtype" />\n';
			
			if(newPT != null)
				if(null != newPT.CCTYPES && "" != newPT.CCTYPES)
				{
					var arrTypes = newPT.CCTYPES.split(",");
					for(var zz=0;zz<arrTypes.length;zz++)
					{
						var arrTypeData = arrTypes[zz].split(":");
						htmlstr += '	<option value="' + arrTypeData[0] + '">' + arrTypeData[1] + '</option>\n';
					}
				}
			htmlstr += '</select>\n';
			htmlstr += ' </td>\n';
			htmlstr += ' </tr>\n';

			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Card_Number")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_cardnumber" id="pay_' + curI + '_cardnumber" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Expiration_Date")+'</td>\n';
/*			htmlstr += '  <td class="tblDataTd">\n';
			htmlstr += '   <input type="text" class="textfield" style="width:25px;" name="pay_' + curI + '_expmo" id="pay_' + curI + '_expmo" value="" onfocus="select();" /> / \n';
			htmlstr += '   <input type="text" class="textfield" style="WIDTH: 25px" MAXLENGTH="2" name="pay_' + curI + '_expyr" id="pay_' + curI + '_expyr" value="" onfocus="select();" />\n';
			htmlstr += '  </td>\n';
*/
			htmlstr += '  <td class="tblDataTd">\n';
			htmlstr += '   <select class="textfield" style="width:40px;" name="pay_' + curI + '_expmo" id="pay_' + curI + '_expmo" > \n';
			htmlstr += '   	<option VALUE="" SELECTED="">--</option> \n';
			htmlstr += '   	<option VALUE="01">01</option> \n';
			htmlstr += '   	<option VALUE="02">02</option> \n';
			htmlstr += '   	<option VALUE="03">03</option> \n';
			htmlstr += '   	<option VALUE="04">04</option> \n';
			htmlstr += '   	<option VALUE="05">05</option> \n';
			htmlstr += '   	<option VALUE="06">06</option> \n';
			htmlstr += '   	<option VALUE="07">07</option> \n';
			htmlstr += '   	<option VALUE="08">08</option> \n';
			htmlstr += '   	<option VALUE="09">09</option> \n';
			htmlstr += '   	<option VALUE="10">10</option> \n';
			htmlstr += '   	<option VALUE="11">11</option> \n';
			htmlstr += '   	<option VALUE="12">12</option> \n';
			htmlstr += '   </select> / \n';
			htmlstr += '   <select class="textfield" style="WIDTH: 40px" name="pay_' + curI + '_expyr" id="pay_' + curI + '_expyr" > \n';
			htmlstr += '   	<option VALUE="" SELECTED="">--</option> \n';
			htmlstr += '   	<option VALUE="09">09</option> \n';
			htmlstr += '   	<option VALUE="10">10</option> \n';
			htmlstr += '   	<option VALUE="11">11</option> \n';
			htmlstr += '   	<option VALUE="12">12</option> \n';
			htmlstr += '   	<option VALUE="13">13</option> \n';
			htmlstr += '   	<option VALUE="14">14</option> \n';
			htmlstr += '   	<option VALUE="15">15</option> \n';
			htmlstr += '   	<option VALUE="16">16</option> \n';
			htmlstr += '   	<option VALUE="17">17</option> \n';
			htmlstr += '   	<option VALUE="18">18</option> \n';
			htmlstr += '   	<option VALUE="19">19</option> \n';
			htmlstr += '   	<option VALUE="20">20</option> \n';
			htmlstr += '   </select> \n';
			htmlstr += '  </td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("CVV_Number")+' <a href="cvv_pop.htm" target="_blank">?</a></td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_cvvnumber" id="pay_' + curI + '_cvvnumber" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			if(isBox == true && gClientId == 44)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Signature")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><span id="pay_' + curI + '_sigSpan" >'
				htmlstr += '   <table border="0" cellpadding="0">'
				htmlstr += '  <tr>'
				htmlstr += '  	<td>'
				htmlstr += '      <OBJECT classid="clsid:69A40DA3-4D42-11D0-86B0-0000C025864A" height="75" id="pay_' + curI + '_signature" name="SigPlus" style="HEIGHT: 80px; WIDTH: 275px;VIEWASTEXT" VIEWASTEXT>'
				htmlstr += '                         <PARAM NAME="_Version" VALUE="131095" />'
				htmlstr += '                                                     <PARAM NAME="_ExtentX" VALUE="4842" />'
				htmlstr += '                                                     <PARAM NAME="_ExtentY" VALUE="1323" />'
				htmlstr += '                                                    <PARAM NAME="_StockProps" VALUE="0" />'
				htmlstr += '                                                  </OBJECT>'
				htmlstr += '                                               </td>'
				htmlstr += '                                            </tr>'
				htmlstr += '                                         </table>'
				htmlstr += '                                         <INPUT id="OrderSignBtn' + curI + '" name="OrderSignBtn' + curI + '" type="button" value="Sig Start" onclick="OrderSigPadOnSign(' + curI + ')" />'
				htmlstr += '                                         <INPUT id="OrderDoneBtn' + curI + '" name="OrderDoneBtn' + curI + '" type="button" value="Sig Done" onclick="OrderSigPadOnStop(' + curI + ')" />'
				htmlstr += '                                         <INPUT id="OrderClearBtn' + curI + '" name="OrderClearBtn' + curI + '" type="button" value="Clear" onclick="OrderSigPadOnClear(' + curI + ')" />'
	                                     
				htmlstr += '  </span>\n';
				htmlstr += ' </tr>\n';
			}
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "cash")&&*/payType == "cash") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Cash_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Cash_Tendered")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "check")&&*/payType == "check") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Check_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Check_Number")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_checknumber" id="pay_' + curI + '_checknumber" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "travellers")&&*/payType == "travellers") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblDatad">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Travellers_Check_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();CheckCurrencyTemp=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} else if (/*(pTyp == "voucher")&&*/payType == "voucher") {
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Voucher_Coupon_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%"><input type="radio" name="RedeemedCoupon'+ curI +'" id="RedeemedCouponCode'+ curI +'"/>'+GetTranslation("Code")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_code" id="pay_' + curI + '_code" value="" RedeemedCoupon="0" CouponValue="0" onclick="checkCoupon(this);" onblur="getCouponAmount(this, curI);"  onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			if(!isNaN(parseInt(gEBI('patron_id').value))&&(parseInt(gEBI('patron_id').value)>0)){
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%"><input type="radio" name="RedeemedCoupon'+ curI +'" id="RedeemedCouponPatron'+ curI +'" checked>'+GetTranslation("Patron_Coupons")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><select style="font: 7pt Arial;" id="selPatronCoupon' + curI + '" onchange="(this.selectedIndex>0)?gEBI(\'pay_' + curI + '_total\').value=this.options[this.selectedIndex].getAttribute(\'CouponValue\'):gEBI(\'pay_' + curI + '_total\').value=0;"><option>'+GetTranslation("Select_Coupon")+'</option>' + listCoupons() + '</select></td>\n';
				htmlstr += ' </tr>\n';
			}
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		} 
		else if (payType == "TPS"){
		
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("TPS_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("TPS_Tendered")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		
		} 
		else if (payType == "account")
		{
			if (null!=selOption)
			{
				htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation("Account_Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
				htmlstr += ' </tr>\n';
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Account_Tendered")+'</td>\n';
				htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onkeyup="CheckAccount(this,\''+selOption.getAttribute('Amount')+'\');" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
				htmlstr += ' </tr>\n';
				htmlstr += '</table><br />\n';
			}
		
		}
		else if("false" == newPT.IsStandart)
		{
		
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+newPT.Name+' '+GetTranslation("Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			if("true" == newPT.IsEnabledCustom1)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom1+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield1", newPT.TypeCustom1, newPT.ValuesCustom1) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom2)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom2+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield2", newPT.TypeCustom2, newPT.ValuesCustom2) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom3)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom3+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield3", newPT.TypeCustom3, newPT.ValuesCustom3) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom4)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom4+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield4", newPT.TypeCustom4, newPT.ValuesCustom4) + '</td>\n';
				htmlstr += ' </tr>\n';
			}
			if("true" == newPT.IsEnabledCustom5)
			{
				htmlstr += ' <tr>\n';
				htmlstr += '  <td class="tblDataTd" width="99%">'+newPT.NameCustom5+'</td>\n';
				htmlstr += '  <td class="tblDataTd">'+ CreatePayTypeControl(curI,"_customfield5", newPT.TypeCustom5, newPT.ValuesCustom5) + '</td>\n';
				htmlstr += ' </tr>\n';
			}

			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		}
		else { //all other default types, payType == "comp", "prepaid", "accountsreceivable", "svnimportpayment", "paypal", "wire", "webmoney"
			htmlstr += '<table id="tblPay' + curI + '" class="tblData">\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <th class="tblDataTh" id="thPay' + curI + '" colspan="2">'+GetTranslation(payType) + "_" +GetTranslation("Transaction")+' &nbsp; <a href="JavaScript:RemovePaymentType(\'' + newPT.Value + '\',\'' + curI + '\');" clas="menu"><span class="small" style="color:#ffffff;">[ '+GetTranslation("remove")+' ]</span></a></th>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Note")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_note" id="pay_' + curI + '_note" value="" onfocus="select();" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += ' <tr>\n';
			htmlstr += '  <td class="tblDataTd" width="99%">'+GetTranslation("Total")+'</td>\n';
			htmlstr += '  <td class="tblDataTd"><input type="text" class="textfield" name="pay_' + curI + '_total" id="pay_' + curI + '_total" value="" onfocus="select();formFocusTempVal=this.value;" onblur="CheckCurrency(this.value,this);CheckTransactionTotals(this);" /></td>\n';
			htmlstr += ' </tr>\n';
			htmlstr += '</table><br />\n';
		}
		document.getElementById("divPayMethods").style.display = "block";
		var oPayDiv = document.getElementById("divPayMethods")
		oPayDiv.innerHTML += htmlstr;
		//focus on newly added type
		var oInp = gEBI('pay_' + curI + '_total');
		if(null != oInp)
		{
			try{
				oInp.focus();
			}
			catch(e)
			{
			}
		}
	} //bDontDraw
	
	/*for(var z=0;z<aryPayTypes.length;z++){
		if(!isNaN(parseInt(gEBI('patron_id').value))&&(parseInt(gEBI('patron_id').value)>0)){
			if((null!=gEBI('RedeemedCouponCode' + z))&&((!gEBI('RedeemedCouponCode' + z).checked)||(!gEBI('RedeemedCouponPatron' + z).checked))){
				gEBI('RedeemedCouponCode' + z).checked = true;
			}
		}
		else{
			if(null!=gEBI('RedeemedCouponCode' + z)){
				gEBI('RedeemedCouponCode' + z).checked = true;
				gEBI('RedeemedCouponCode' + z).style.display = 'none';
			}
		}
	}*/
	updateTotals();
	if((pTyp == "credit" || payType == "creditcardsave") && aryPayTypes.length > 0)
	{
		var lCCVal=	gOrderTotal-gTransactionTotal;
		if(lCCVal < 0) lCCVal = 0;
		gEBI('pay_' + curI + '_total').value = parseFloat(lCCVal).toFixed(2);
		gEBI('pay_' + curI + '_total').onblur();
		doSwipe(curI);
	}
	
oType.selectedIndex=0;
}

/* pTypIndex - initIndex of the type to be removed */
function RemovePaymentType(pType, pTypIndex)
{
	var nAry = aryPayTypes;
	var bWasRemoved = false;
	
	for (var i=0; i<nAry.length; i++)
	{
		if (nAry[i].initIndex == pTypIndex)
		{
			nAry.splice(i, 1);
			bWasRemoved = true;
			bTPSTransaction=false;
			break;
		}
	}

	if(bWasRemoved)
	{
		aryPayTypes = nAry;
		//removing table for this method
		var oTbl = gEBI('tblPay' + pTypIndex);
		if(null != oTbl)
		{
			var oBR = getNextSibling(oTbl);
			oTbl.parentNode.removeChild(oTbl);
			if(oBR)
				oBR.parentNode.removeChild(oBR);
		}
		updateTotals();
	}
}

function makeDonation(decAmount, cpnID){
	return "<CouponOrder><ID>0</ID><Coupon><ID>" + cpnID + "</ID><Client><ID>" + gClientId + "</ID></Client><CouponValue>" + (-1*decAmount) + "</CouponValue><CouponType><ID>2</ID></CouponType></Coupon><Quantity>1</Quantity></CouponOrder>";
}
function checkDueTransaction(){
    oModeSelect=gEBI("UserModeSelect"); 		
    if (null!=oModeSelect)
    {
		var bIsDueTransaction = (oModeSelect[oModeSelect.selectedIndex].getAttribute("isDueTransaction") == "true")?true:false;		
		if(bIsDueTransaction) 
			return true;
	}
	else
	{
		if(isBox)
			return true;
	}


	tempSubTotal=0;
	gTransactionTotal = 0; 
	var thisTotal = 0;
  	var subTotal = parseFloat(gOrderTotal).toFixed(2);
	if (aryPayTypes.length > 0) 
	{
		for (var pt=0;pt<aryPayTypes.length;pt++) 
		{
			var paymentType=(aryPayTypes[pt].Value).replace(" ","");
			var idx = aryPayTypes[pt].initIndex;
			var cpval = 0;
			if((null!=gEBI('RedeemedCouponPatron'+idx))&&(gEBI('RedeemedCouponPatron'+idx).checked))
				cpval = gEBI('selPatronCoupon'+idx).options[gEBI('selPatronCoupon'+idx).selectedIndex].getAttribute('CouponValue');
			else if((null!=gEBI('RedeemedCouponCode'+idx))&&(gEBI('RedeemedCouponCode'+idx).checked))
				cpval = gEBI(String('pay_' + idx + '_code')).getAttribute('CouponValue');
				
			if(null != gEBI(String('pay_' + idx + '_total')))
				thisTotal = Number(gEBI(String('pay_' + idx + '_total')).value + cpval);
			if (paymentType != "TPS")	
				gTransactionTotal += NumAccuracy(parseFloat(thisTotal), 2);
		}
	}
	
	if ( NumAccuracy(gTransactionTotal, 2)<subTotal)
		return false;
	else 
		return true;
}
function Wait(butCheckOut,ContainPrintAtHome)
{    
    var regpatron=checkRegisteredpatron()
	if (!regpatron) return;
	
	if (checkoutway==3){
	   isPatronRegistered=gEBI('h_PatronRegister').value;
	   isPatronRegistered=isPatronRegistered.replace(" ","");
	   if (isPatronRegistered=='false'){
	        alert("You have to login before you can continue");
			return;
		}
	  }
	
	if(!setWebTransactions()) return;
	
	if (!checkDueTransaction())
	{
		if(isBox)
		{
			alert("You may not process orders that are unbalanced.  Please make adequate payment for this order.");
			return;
		}
		if(isWeb&&!isBox)
		{
			alert("You cannot process an order with balance due.  Please make adequate payment for this order.")
			return;
		}
	}
	if (!CheckVoucherAndTicket())
	   return;
	gEBI("Wait").style.display			="block";
	butCheckOut.style.display	="none";

	flag = OnOrderPay(ContainPrintAtHome);
	if(!flag)
	{
		gEBI("Wait").style.display			="none";
		butCheckOut.style.display	="block";
	}
	else
	{  
		if (arrItems.length > 0)   
		{ 
			arrItems.splice(0,arrItems.length);
			gEBI("itemsCount").innerHTML="";
			gEBI("itemsAmount").innerHTML="";
		}
		updateTotalItems();
	}
}

function setWebTransactions()
{
	//if it's web trans, then we should build aryPayTypes manually from available HTML
	if(isWeb&&!isBox)
	{
		aryPayTypes = new Array();
		var cnt = 0;
		var oTable = gEBI('tblPay'+cnt);
		while(oTable != null)
		{
			if(oTable.style.display != "none")
			{
				var oTr = new Object();
				oTr.TransactionTypeId = oTable.getAttribute("ptid");
				oTr.Name = oTable.getAttribute("ptname");
				oTr.initIndex = oTable.getAttribute("ptidx");
				oTr.Value = oTable.getAttribute("ptval");
				aryPayTypes.push(oTr);
				//break;
			}
		
			cnt++;
			oTable = gEBI('tblPay'+cnt);
		}
		if(0 == aryPayTypes.length && gOrderTotal > 0)
		{
			alert("Do not have any transactions in web mode");
			return false;
		}
		if(null != gEBI("displayOrderBalanceTotal"))
		{
			if(Number(gEBI("displayOrderBalanceTotal").value) > 0)
			{
				alert("You cannot process an order with balance due.  Please make adequate payment for this order.");
				return false;
			}
		}	
	}
	return true;
}
function OnOrderPay(ContainPrintAtHome)
{
	var strOrderXML=GenerateOrderXML(ContainPrintAtHome);
	if(strOrderXML == false) return false;
	if(strOrderXML == "") return false;

	gCurrentOrderXML = strOrderXML;	
	
	strUXML = oParentIDHolder["UsersXML"];
	strUserXML = strUXML.replace("<User xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">", "<User>");
	var strRequestXML = "<envelope><body>" +
						"<command name=\"CommitOrderWeb\">" +
						"<class name=\"" + 'Orders' + "\" />";
						
	strRequestXML += "<param type=\"" + "Order" + "\">" + strOrderXML + "</param>";
	strRequestXML += "<param type=\"" + "Client" + "\">" + gEBI('hCurrentVenuesXML').value + "</param>";
	strRequestXML += "<param type=\"" + "User" + "\">" + strUserXML + "</param>";
	
	var invId = $("#selSuperUserInventories").val();
	if("" == invId || null == invId)
		invId = $("#hInventoryID").val();
	strRequestXML += "<param type=\"" + "Inventory" + "\"><Inventory><ID>" + invId + "</ID></Inventory></param>";

	var strModeId = $("#UserModeSelect").val();
	if("" == strModeId || null == strModeId)
		strModeId = "0";
	strRequestXML += "<param type=\"" + "Mode" + "\"><Mode><ID>" + strModeId + "</ID></Mode></param>";
		
	strRequestXML += "</command><xslt>TicketsFormat.xslt</xslt></body></envelope>";
	
	//alert(strRequestXML);
	//document.write("<div><xmp>" + strRequestXML +  "</xmp></div>");
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: gSOAPListenerURL,
				data: strRequestXML,
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	$("#scleftlink").hide();

	handleHistoryAdd("end",null);
	//alert('ORDERID: ' + strResp);
	if(strResp.indexOf('Exception') >= 0 || strResp.indexOf('Error') >= 0)
	{
	    EraseOrderData();
		ShowErrorMessage(strResp);
		window.scroll(0,0);
		return false;
	}
	
	//if we got here, means that order was saved and processed correctly, however we are not 100% sure that payment was made at this point (PayPal, Wire Transfer, WebMoney)
	gCurrentOrderId = Number(strResp);
	//gCurrentTicketOrderDetailsXML = strResp;
	ShowConfirmation(ContainPrintAtHome);
	if(gClientId == 10 || gClientId == 11 || gClientId == 14 || gClientId == 16 || gClientId == 39 || gClientId == 22 || gClientId == 23 || gClientId == 27 || gClientId == 26 || gClientId == 29 || gClientId == 19 || gClientId == 31 || gClientId == 34 || gClientId == 32 || gClientId == 35 || gClientId == 18 || (gClientId >= 40  && (gClientId != 70  && gClientId != 71)))
	{
	  if (null!=gEBI("frPrintFgl"))
	    gEBI("frPrintFgl").style.display='block';
	}
	else
	{
	  if (null!=gEBI("frPrintFgl"))
	  {
		gEBI("frPrintFgl").src="";
	    gEBI("frPrintFgl").style.display='none';
	    }
	
	}	
	
	var oDm = gEBI(gEBI("deliverymethodUniqueId").value);
	
	if(oDm[oDm.selectedIndex].innerHTML == GetTranslation("DeliveryMethods_taketicketsnow"))
	{
		if(CheckTransactionTotals(0, false))
			if(confirm(GetTranslation("Would_you_like_to_print")))
				DoQuickPrintNewWay(gCurrentOrderId);
				//previous function was DoQuickPrint();
	}

	if(oDm[oDm.selectedIndex].innerHTML == GetTranslation("Print At Home"))
	{
		if(isBox)
		{
			if(CheckTransactionTotals(0, false))
				DoPrintAtHome();
		}
		else
			DoPrintAtHome();
	}
	
	EraseOrderData(); //when the order was paid
	
	return true;
}

function BuildShippingXML()
{
		var strShippXML = "<PatronAddress>";
		
		strShippXML += "<Address>";
		strShippXML +=		"<ID>" + gEBI('patron_shippingaddressid').value + "</ID>";
		

		if("0" != buildCustomXML(gEBI("shipping_salutation1"),"Salutation")) strShippXML +=	buildCustomXML(gEBI("shipping_salutation1"),"Salutation");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_firstname1"),"FirstName")) strShippXML +=	buildCustomXML(gEBI("shipping_firstname1"),"FirstName");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_lastname1"),"Name")) strShippXML +=	buildCustomXML(gEBI("shipping_lastname1"),"Name");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_salutation2"),"PartnerSalutation")) strShippXML +=	buildCustomXML(gEBI("shipping_salutation2"),"PartnerSalutation");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_firstname2"),"PartnerFirstName")) strShippXML +=	buildCustomXML(gEBI("shipping_firstname2"),"PartnerFirstName");
		else return false;
		
		if("0" != buildCustomXML(gEBI("shipping_lastname2"),"PartnerLastName")) strShippXML +=	buildCustomXML(gEBI("shipping_lastname2"),"PartnerLastName");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_company"),"Company")) strShippXML +=	buildCustomXML(gEBI("shipping_company"),"Company");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_address"),"Street")) strShippXML +=	buildCustomXML(gEBI("shipping_address"),"Street");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_address2"),"Street2")) strShippXML +=	buildCustomXML(gEBI("shipping_address2"),"Street2");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_city"),"City")) strShippXML +=	buildCustomXML(gEBI("shipping_city"),"City");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_state"),"State")) strShippXML +=	buildCustomXML(gEBI("shipping_state"),"State");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_zip"),"ZIP")) strShippXML +=	buildCustomXML(gEBI("shipping_zip"),"ZIP");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_country"),"Country")) strShippXML +=	buildCustomXML(gEBI("shipping_country"),"Country");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_region"),"Region")) strShippXML +=	buildCustomXML(gEBI("shipping_region"),"Region");
		else return false;			
			
		if("0" != buildCustomXML(gEBI("shipping_phone"),"Phone")) strShippXML +=	buildCustomXML(gEBI("shipping_phone"),"Phone");
		else return false;

		if("0" != buildCustomXML(gEBI("shipping_email"),"EMail")) strShippXML +=	buildCustomXML(gEBI("shipping_email"),"EMail");
		else return false;

			
		var oSel = gEBI("shipping_phonetype");
		if(null != oSel)			
			strShippXML +=		"<PhoneType>" + String(oSel.options[oSel.selectedIndex].innerHTML) + "</PhoneType>";		
		oSel = gEBI("shipping_emailtype");
		if(null != oSel)
			strShippXML +=		"<EmailType>" + String(oSel.options[oSel.selectedIndex].innerHTML) + "</EmailType>";		
		strShippXML +=		"<AddressType><ID>1</ID></AddressType>";
		if("0" != buildCustomXML(gEBI("shipping_custom1"),"Custom1")) strShippXML +=	buildCustomXML(gEBI("shipping_custom1"),"Custom1");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom2"),"Custom2")) strShippXML +=	buildCustomXML(gEBI("shipping_custom2"),"Custom2");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom3"),"Custom3")) strShippXML +=	buildCustomXML(gEBI("shipping_custom3"),"Custom3");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom4"),"Custom4")) strShippXML +=	buildCustomXML(gEBI("shipping_custom4"),"Custom4");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom5"),"Custom5")) strShippXML +=	buildCustomXML(gEBI("shipping_custom5"),"Custom5");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom6"),"Custom6")) strShippXML +=	buildCustomXML(gEBI("shipping_custom6"),"Custom6");
		else return false;
		if("0" != buildCustomXML(gEBI("shipping_custom7"),"Custom7")) strShippXML +=	buildCustomXML(gEBI("shipping_custom7"),"Custom7");
		else return false;
		strShippXML += "</Address>";

		strShippXML += "<AddressType><ID>1</ID></AddressType>";
	strShippXML += "</PatronAddress>";
	return strShippXML;
}
function EraseOrderData(pOrderOnly)
{
	gOrder["TicketsXML"] = gOrder["SubscriptionsXML"] = gOrder["CouponOrdersXML"]
				= gOrder["CouponPackageOrdersXML"]= gOrder["ItemOrdersXML"] = "";
	
	if(null == pOrderOnly || false == pOrderOnly)
	{
		//erase payment options for previous order			
		aryPayTypes = new Array();
		htmlstr = "";
	}
}

/*
*Builds XML for Transaction Collection of an Order
*/
function OrderBuildTransactionsXML()
{
	//build xml for billing address
	var strBillingAddress = OrderBuildBillingAddressXML();
	//build xml for each payment type
	var nTotal = gOrderTotal;
	var bHasCashTransaction = false;

	strTransXML += "<Trnxs>";
	
	if (null!=gEBI("txtTotalTPS") && gEBI("txtTotalTPS").value>0){
		strTransXML += "<Transaction>" +
		    			"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
						"<TransactionType>" +
						"<ID>33</ID>" +
						"<Name>"+GetTranslationPaymentTypes("PaymentTypes_TPS")+"</Name>" +
						"</TransactionType>" +
						"<Amount>" + gEBI("txtTotalTPS").value  + "</Amount>";
		strTransXML += "</Transaction>";
	}
	for(var i=0; i<aryPayTypes.length;i++)
	{
		var curI = aryPayTypes[i].initIndex;
		
		switch(String(aryPayTypes[i].Value).toLowerCase())
		{
			case 'credit':
			case 'creditcardsave':
				var oInpCCNumber = gEBI(String('pay_' + curI + '_cardnumber'));
				var oInpExpMM = gEBI(String('pay_' + curI + '_expmo'));
				var oInpExpYY = gEBI(String('pay_' + curI + '_expyr'));
				var oInpCVV = gEBI(String('pay_' + curI + '_cvvnumber'));
				var oSelectCCType = gEBI(String('pay_' + curI + '_cardtype'));
				var oCardFirstName = gEBI(String('pay_' + curI + '_firstname'));
				var oCardLastName = gEBI(String('pay_' + curI + '_lastname'));
				var oInpCCwasSwiped = gEBI(String('CCwasSwiped' + curI));
				var sSig = OrderSigPadGetSig(curI);
				
				var ccwasSwiped = "false";
				if(oInpCCwasSwiped != null)
					ccwasSwiped = oInpCCwasSwiped.value;
					
				//get amount for this payment method
				var nAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(nAmount == '')
					nAmount = nTotal;


				strUXML = oParentIDHolder["UsersXML"];
				strUserXML = strUXML.replace("<User xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">", "<User>");
				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" +
									"<TransactionType>" +
										"<ID>"+aryPayTypes[i].TransactionTypeId+"</ID>" +
										"<Name><![CDATA["+GetTranslationPaymentTypes("PaymentTypes_Credit Card")+"]]></Name>" +
									"</TransactionType>" +
									"<Amount>" + nAmount + "</Amount>" +
									strBillingAddress + strUserXML;
				//must check validity of ccnumber
						IsCCValid = validCCForm(Number(oSelectCCType.value), oInpCCNumber, oInpExpMM, oInpExpYY);
						var IsCVVValid =  (oInpCVV != null && oInpCVV.value.indexOf('.') < 0)?true:false;
						if(!IsCVVValid)
						{
							alert("Credit Card CVV Incorrect")
							return false;
						}		
						if(!IsCCValid)
						{
							//alert("Credit Card Incorrect")
							return false;
						}

						strTransXML += 	"<CreditCard>" +
											"<CCTYPE>" +
												"<ID>" + Number(oSelectCCType.value) + "</ID>" +
												"<Name>" + oSelectCCType[oSelectCCType.selectedIndex].innerHTML +"</Name>" +
											"</CCTYPE>" +
											"<Number>" + oInpCCNumber.value + "</Number>" +
											"<SigString>" + sSig + "</SigString>" +
											"<ExpiryMonth>" + oInpExpMM.value + "</ExpiryMonth>" +
											"<ExpiryYear>" + oInpExpYY.value + "</ExpiryYear>" + 
											"<WasSwiped>" + ccwasSwiped + "</WasSwiped>";
						
						if(oCardFirstName != null && oCardLastName != null)
							strTransXML += 	"<FirstName><![CDATA["+oCardFirstName.value+"]]></FirstName>"+
											"<LastName><![CDATA["+oCardLastName.value+"]]></LastName>";
							
						var anum=/(^\d+$)|(^\d+\.\d+$)/
						if(Trim(oInpCVV.value) != "" && !anum.test(Trim(oInpCVV.value)))
						{
							alert("CVV is incorrect.  Please click the ? link next to CVV Number for an explanation on what a CVV is.")
							return false;
						}
						if(Trim(oInpCVV.value) != "")
							strTransXML += "<CVV>" + oInpCVV.value + "</CVV>";

						strTransXML += "</CreditCard>";
						
					if(oCardFirstName != null && oCardLastName != null)
					{
						strTransXML += "<CheckNumber><![CDATA[" + oCardFirstName.value + " " + oCardLastName.value + "]]></CheckNumber>";
					}
				strTransXML += "</Transaction>";
				break;

			case 'cash':
				bHasCashTransaction = true;
				//get amount for this payment method
				var nAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(nAmount == '')
					nAmount = nTotal;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>1</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_cash")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + nAmount  + "</Amount>";

				strTransXML += "</Transaction>";
				break;

			case 'check':
				//get amount for this payment method
				var nAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(nAmount == '')
					nAmount = nTotal;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>3</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_check")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + nAmount  + "</Amount>" +
									"<CheckNumber>" + gEBI(String('pay_' + curI + '_checknumber')).value + "</CheckNumber>";

				strTransXML += "</Transaction>";
				break;

			case 'travellers':
				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>6</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_travellers")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + gEBI(String('pay_' + curI + '_total')).value  + "</Amount>";

				strTransXML += "</Transaction>";
				break;

			case 'voucher':
						var rcID = 0;
						var cpval = 0;
						var nVoucherAmount = gEBI(String('pay_' + curI + '_total')).value
					if(isNaN(nVoucherAmount) || nVoucherAmount == '')
						nVoucherAmount  = nTotal;
					if(isNaN(nVoucherAmount) || nVoucherAmount == '')
						nVoucherAmount = 0;
						try{
						if(gEBI('RedeemedCouponPatron'+curI).checked){
							rcID = gEBI('selPatronCoupon'+curI).options[gEBI('selPatronCoupon'+curI).selectedIndex].getAttribute('RedeemedCoupon');
							cpval = gEBI('selPatronCoupon'+curI).options[gEBI('selPatronCoupon'+curI).selectedIndex].getAttribute('CouponValue');
						}
						else{
							rcID = gEBI(String('pay_' + curI + '_code')).getAttribute('RedeemedCoupon');
							cpval = gEBI(String('pay_' + curI + '_code')).getAttribute('CouponValue');
						}
						}
						catch(e)
						{
							cpval = gEBI(String('pay_' + curI + '_total')).value
							rcID = 0;
						}
						if(parseFloat(cpval) < parseFloat(gEBI(String('pay_' + curI + '_total')).value))
						{	
							strAlert ="The amount due is $"+parseFloat(gEBI(String('pay_' + curI + '_total')).value).toFixed(2)+" which is greater than the coupon '"+gEBI(String('pay_' + curI + '_code')).value+"' amount ($"+parseFloat(cpval).toFixed(2)+"). \n\tPlease add another coupon, cash or creditcard transaction."
							//alert(strAlert);
							//return false;
						}
				if(rcID == null || rcID == "null")
					rcID = 0;
				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>7</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_voucher")+"</Name>" +
									"</TransactionType>" +
									"<RedeemedCouponId>" + rcID + "</RedeemedCouponId>" +
									"<Amount>" + nVoucherAmount  + "</Amount>";
				//alert(nVoucherAmount)
				if(rcID == 0)
					strTransXML += "<CheckNumber>" + gEBI(String('pay_' + curI + '_code')).value + "</CheckNumber>";
				strTransXML += "</Transaction>";
				break;

			case 'comp':
			var compAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(isNaN(compAmount) || compAmount == '')
					compAmount = nTotal;
				if(isNaN(compAmount)  || compAmount == '')
					compAmount = 0;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>4</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_comp")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + compAmount  + "</Amount>" +
									"<CompNote>" + gEBI(String('pay_' + curI + '_note')).value + "</CompNote>";

				strTransXML += "</Transaction>";
				break;
				
			case 'prepaid':
				var compAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(isNaN(compAmount) || compAmount == '')
					compAmount = nTotal;
				if(isNaN(compAmount)  || compAmount == '')
					compAmount = 0;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>9</ID>" +
										"<Name>"+GetTranslationPaymentTypes("PaymentTypes_prepaid")+"</Name>" +
									"</TransactionType>" +
									"<Amount>" + compAmount  + "</Amount>" +
									"<Note>" + gEBI(String('pay_' + curI + '_note')).value + "</Note>";

				strTransXML += "</Transaction>";
				break;
			default:
				//PayPal, WebMoney, Wire Transfer are processed just as custom paytypes
				var compAmount = gEBI(String('pay_' + curI + '_total')).value;
				if(isNaN(compAmount) || compAmount == '')
					compAmount = nTotal;
				if(isNaN(compAmount)  || compAmount == '')
					compAmount = 0;

				strTransXML += "<Transaction>" +
									"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
									"<TransactionType>" +
										"<ID>"+aryPayTypes[i].TransactionTypeId+"</ID>" +
										"<Name><![CDATA["+GetTranslationPaymentTypes("PaymentTypes_"+aryPayTypes[i].Name)+"]]></Name>" +
									"</TransactionType>" +
									"<Amount>" + compAmount  + "</Amount>";
									if("true" == aryPayTypes[i].IsEnabledCustom1)
										strTransXML += "<CustomField1>"+ gEBI(String('pay_' + curI + '_customfield1')).value +"</CustomField1>";
									if("true" == aryPayTypes[i].IsEnabledCustom2)
										strTransXML += "<CustomField2>"+ gEBI(String('pay_' + curI + '_customfield2')).value +"</CustomField2>";
									if("true" == aryPayTypes[i].IsEnabledCustom3)
										strTransXML += "<CustomField3>"+ gEBI(String('pay_' + curI + '_customfield3')).value +"</CustomField3>";
									if("true" == aryPayTypes[i].IsEnabledCustom4)
										strTransXML += "<CustomField4>"+ gEBI(String('pay_' + curI + '_customfield4')).value +"</CustomField4>";
									if("true" == aryPayTypes[i].IsEnabledCustom5)
										strTransXML += "<CustomField5>"+ gEBI(String('pay_' + curI + '_customfield5')).value +"</CustomField5>";
				strTransXML += "</Transaction>";
				break;
		}

	}//end Transaction for loop
	
	//check for overpayment with cash and do auto cash trans for change given back
	if(bHasCashTransaction && parseFloat(gEBI("displayOrderBalanceTotal").value) < 0)
	{
		strTransXML += "<Transaction>" +
			"<OrderID>" + oParentIDHolder["gEditOrderId"] + "</OrderID>" + 
			"<TransactionType>" +
				"<ID>1</ID>" +
				"<Name>"+GetTranslationPaymentTypes("PaymentTypes_cash")+"</Name>" +
			"</TransactionType>" +
			"<Amount>" + parseFloat(gEBI("displayOrderBalanceTotal").value)  + "</Amount>";
			strTransXML += "</Transaction>";
	}

				
	strTransXML += "</Trnxs>";
	gCurrentPaymentXML = strTransXML;
	return strTransXML;
}

	  
function FocusTxtBA(txtFind)
  {
	txtFind.select();
  }
			  
function KeyPressBA(e)
  {				
	if(!e) e = window.event; 
	if(e.keyCode==13)
	{
		gEBI('AddBestAvailablebtn').click();
	}
	return true; 
  }

function ShowConfirmation(ContainPrintAtHome)
{
	if(null != gEBI("ulOptionsInner"))
		gEBI("ulOptionsInner").style.display="none";
	gEBI('tabCalendar').style.display = 'none';
	var bEmail = true;
	if (isNaN(gCurrentOrderId)==false)
	{
	var strOrderID = '<Order><ID>' + gCurrentOrderId + '</ID>';
	var strContainPrintAtHomeXml = "<ContainPrintAtHome>"+ContainPrintAtHome+"</ContainPrintAtHome>";
	strOrderID+=strContainPrintAtHomeXml;
	gCurrentOrderXML=strOrderID+"</Order>";
	var strXML = "<Envelope><Body>"+gCurrentOrderXML;
	strXML +="</Body></Envelope>";

	//hide all DIVs except cart page
	document.getElementById("divCart").style.display = "none";
	gEBI('divPayCart').style.display='none';
	document.getElementById("divConfirm").style.display = "inline";
	embedHTTPPage("OrderComplete.aspx?checkoutway="+checkoutway, strXML, "divConfirm");
	gEBI('divConfirm').innerHTML = unescape(gEBI('divConfirm').innerHTML);
	window.scrollTo(0,0);
	}
}

function ShowErrorMessage(sError)
{
	//hide all DIVs except cart page
	$("#divCart").hide();
	$("#divPayCart").hide();
	
	document.getElementById("divConfirm").style.display = "inline";
	$("#divConfirm").html(sError);
}

function CheckTPStransaction (){
 TotalTPS=0;
	if (aryPayTypes.length > 0) {
		for (pt=0;pt<aryPayTypes.length;pt++) {
			paymetType=(aryPayTypes[pt].Value).replace(" ","");	
			ptHTMLIdx = aryPayTypes[pt].initIndex;
			var cpval = 0;
			if((null!=gEBI('RedeemedCouponPatron'+ptHTMLIdx))&&(gEBI('RedeemedCouponPatron'+ptHTMLIdx).checked)){
				cpval = gEBI('selPatronCoupon'+ptHTMLIdx).options[gEBI('selPatronCoupon'+ptHTMLIdx).selectedIndex].getAttribute('CouponValue');
			}
			else if((null!=gEBI('RedeemedCouponCode'+ptHTMLIdx))&&(gEBI('RedeemedCouponCode'+ptHTMLIdx).checked)){
				cpval = gEBI(String('pay_' + ptHTMLIdx + '_code')).getAttribute('CouponValue');
			}
			
	
			if(null != gEBI(String('pay_' + ptHTMLIdx + '_total')) && paymetType=="TPS") {
				TotalTPS = Number(gEBI(String('pay_' + ptHTMLIdx + '_total')).value + cpval);
				
				}
		}
	}
		return TotalTPS;
}
function CheckTransactionTotals(id, bShowMsg) {
	if(bShowMsg == null)
		bShowMsg = true;
	gTransactionTotal = 0;
	//gTransactionTotalTPS=0;
	var thisTotal = 0;
  	var subTotal = parseFloat(gOrderTotal).toFixed(2);
  	var nCheckAmount=0;
	var nCCAmount=0;
	var vccnt=0;
  	//var subTotalTPS=parseFloat(gOrderTotalTPS).toFixed(2);
	if (isBox && aryPayTypes.length > 0) {//isBox
		for (pt=0;pt<aryPayTypes.length;pt++) {
			ptHTMLIdx = aryPayTypes[pt].initIndex;
			//paymetType=(aryPayTypes[pt].Value).replace(" ","");	
			
			var cpval = 0;
			if((null!=gEBI('RedeemedCouponPatron'+ptHTMLIdx))&&(gEBI('RedeemedCouponPatron'+ptHTMLIdx).checked)){
				cpval = gEBI('selPatronCoupon'+ptHTMLIdx).options[gEBI('selPatronCoupon'+ptHTMLIdx).selectedIndex].getAttribute('CouponValue');
			}
			else if((null!=gEBI('RedeemedCouponCode'+ptHTMLIdx))&&(gEBI('RedeemedCouponCode'+ptHTMLIdx).checked)){
				cpval = gEBI(String('pay_' + ptHTMLIdx + '_code')).getAttribute('CouponValue');
			}
			
			if(null != gEBI(String('pay_' + ptHTMLIdx + '_total')))
				thisTotal = Number(gEBI(String('pay_' + ptHTMLIdx + '_total')).value + cpval);
			
			gTransactionTotal += NumAccuracy(parseFloat(thisTotal), 2);
		}
	}else{//isWeb
		var cnt = 0;
		var oTable = gEBI('tblPay'+cnt);
		while(oTable != null)
		{
			if(oTable.style.display == "inline" && null != gEBI('pay_' + cnt + '_total'))
			{
				thisTotal = Number(gEBI(String('pay_' + cnt + '_total')).value);
				gTransactionTotal += NumAccuracy(parseFloat(thisTotal), 2);
				//alert(oTable.getAttribute("ptval")+   '   '+oTable.getAttribute("ptname"));
				if (oTable.getAttribute("ptval").toLowerCase()!='voucher')
					nCCAmount+=NumAccuracy(parseFloat(thisTotal), 2);
				else{	
					nCheckAmount+=NumAccuracy(parseFloat(thisTotal), 2);
					vccnt=cnt;
					
					}
				
			}
			
			cnt++;
			oTable = gEBI('tblPay'+cnt);
		}
		if(1 == cnt)
			{
			gEBI(String('pay_0_total')).disabled = true;
			gEBI(String('pay_0_total')).value=FormatCurrency(subTotal,2);
			}
	}
	gTransactionTotal=NumAccuracy(gTransactionTotal, 2);
	if(null == gEBI("displayOrderBalanceTotal")) 
		return;

	gEBI("displayOrderBalanceTotal").value = FormatCurrency(subTotal - gTransactionTotal,2);
	//alert('nCheckAmount='+nCheckAmount+'   nCCAmount='+nCCAmount+'  vccnt='+vccnt);
	//check balance; set tdBalance.innerHTML = to appropriate wording (overpayment,etc.) and if donations or PWYC exist then pop-up confirmation to do with balance
	if (!isBox && isWeb)
	{   
		if (nCheckAmount>0)
		{
			if ( (subTotal - nCCAmount)>nCheckAmount )
				{
				gEBI(String('pay_' + vccnt + '_total')).value=FormatCurrency(nCheckAmount,2);
				
				}
			else
			  { 
			    if ( subTotal - nCCAmount >0 )
				{
						gEBI(String('pay_' + vccnt + '_total')).value=FormatCurrency( subTotal - nCCAmount,2);
				}
				else 
					gEBI(String('pay_' + vccnt + '_total')).value=FormatCurrency(0,2);
			  }	
		}
		else
		{gEBI('patron_id').value=0;
		PatronLookUpById(0);
			}
		
	}
	if (gTransactionTotal < subTotal ) {//check if undefined discount exists
		//processAnyway = confirm("Payment transactions are not sufficient for order total.\n\nAre you sure you wish to continue?");
		//return processAnyway;
		//if(bShowMsg)
		//	alert(GetTranslation("Payment_transactions_are_not_order_total")+".");

			return false;   //
	} else if (gTransactionTotal > subTotal) {//check if donation exists
		/*if(bShowMsg)
			alert("Current payments are $ " + FormatCurrency(gTransactionTotal-subTotal,2) + " greater than the order total. Please correct payments before completing the order.")
		*/ 

			return true;
	} else {
			gEBI("displayOrderBalanceTotal").value = FormatCurrency(subTotal - gTransactionTotal,2);
		return true;
	}
	
	
}

function CheckCurrency(val,id) {
    val = parseFloat(val);
	if (!isNaN(val)) {
		id.value = FormatCurrency(val,2);
	} else {
		id.value = formFocusTempVal;
	}
}

function FormatCurrency(data,acc) {
	data = parseFloat(data);
	if(isNaN(data))
		return "0.00";

  	data = data.toString();
  	if (data.indexOf(".") == -1){
  		data += ".00";
  	} else {
  		var decs = data.substr(data.indexOf(".")+1, data.length).length;
  		if (decs > acc) {
  			data = NumAccuracy(parseFloat(data),acc);
  		} else if (decs < acc) {
			for (d=1;d<=(acc-decs);d++) {
				data += "0";
			}
  		}
  	}
	return data;
}

function CheckAccount(obj,AccAmount)
{
 if ( parseFloat(obj.value)>parseFloat(AccAmount))
   {
		obj.value=AccAmount;
		alert('Your account balance is' +AccAmount+ ' $  \n You cannot exceed this limit when paying from your account.');
   }
}
function NumAccuracy(val,acc) {
 	if (isNaN(val)) {
		val = 0;
	} else {
		acc = Math.pow(10,acc);
		val = Math.round(val*acc)/acc;
	}
	return val;
}

// Credit Card Validation Functions:
//
// isValidExpDate(formField,fieldLabel,required)
//   -- checks for date in the format MM/YY or MM/YYYY against the current date
// isValidCreditCardNumber(formField,ccType,fieldLabel,required)
//   -- checks for valid credit card format using the Luhn check and known digits about various cards
// http://javascript.about.com/library/scripts/blccvalid.htm
function validRequired(formField,fieldLabel)
{
	var result = true;

	if (formField.value == "")
	{
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}

	return result;
}


function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

function inValidCharSet(str,charset)
{
	var result = true;

	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}

	return result;
}

function isValidExpDate(formFieldMM, formFieldYY,fieldLabel,required)
{
	var result = true;

	if (required && !validRequired(formFieldMM,fieldLabel))
		return false;

	if(required && !validRequired(formFieldYY,fieldLabel))
		return false;

 	if (result &&
 		(formFieldMM.value.length>0) &&
 		(formFieldYY.value.length>0))
 	{
 		var elems = new Array();
 		elems[0] = formFieldMM.value;
 		elems[1] = formFieldYY.value;

 		result = (elems.length == 2); // should be two components
 		var expired = false;

 		var month = parseInt(elems[0],10);
 		var year = parseInt(elems[1],10);

 		if (elems[1].length == 2)
 			year += 2000;

 		var now = new Date();

 		var nowMonth = now.getMonth() + 1;
 		var nowYear = now.getFullYear();

 		expired = (nowYear > year) || ((nowYear == year ) && (nowMonth > month));

		result = allDigits(elems[0]) && (month > 0) && (month < 13);

 		if (!result)
 		{
 			alert('Please enter a date in the format MM for the "' + fieldLabel +'" field.');
			formFieldMM.focus();
			return result;
		}

		//YY field
		result = allDigits(elems[1]) && ((elems[1].length == 2) || (elems[1].length == 4));
		if (!result)
 		{
 			alert('Please enter a date in the format YY or YYYY for the "' + fieldLabel +'" field.');
			formFieldYY.focus();
			return result;
		}

		if (expired)
		{
 			result = false;
 			alert('The date for "' + fieldLabel +'" has expired.');
			formFieldMM.focus();
		}
	}

	return result;
}

function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (required && !validRequired(formField,fieldLabel))
		result = false;

  	if (result && (formField.value.length>0))
 	{
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}

		if (result)
 		{

 			if (!validateCCNum(ccType,ccNum) || !LuhnCheck(ccNum))
 			{
 				alert('Please enter a valid card number for the "' + fieldLabel +'" field.');
				formField.focus();
				result = false;
			}
		}

	}

	return result;
}

function LuhnCheck(str)
{
  var result = true;

  var sum = 0;
  var mul = 1;
  var strLen = str.length;

  for (i = 0; i < strLen; i++)
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;

  return result;
}

function GetRadioValue(rArray)
{
	for (var i=0;i<rArray.length;i++)
	{
		if (rArray[i].checked)
			return rArray[i].value;
	}

	return null;
}


function validateCCNum(cardType,cardNum)
{
	var result = false;
	//cardType = cardType.toUpperCase();

	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case 1: //"VISA"
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case 2: //"MASTERCARD"
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case 3: //"DISCOVER"
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case 4: //"AMEX"
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case 5: //"DINERS"
			var validNums = "068";
			result = (cardLen == 14) && (first4digs == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case 6: //"Bankcard"
			//var validNums = "068";
			result = (cardLen == 16) ;//&& (first4digs == "5610"); //&& (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

function validCCForm(nCcType,ccNumField,ccExpFieldMM,ccExpFieldYY)
{
	var result = isValidCreditCardNumber(ccNumField, nCcType, "Credit Card Number", true)
			&& isValidExpDate(ccExpFieldMM, ccExpFieldYY,"Expiration Date",true);

	return result;
}
//End credit card validation

function TicketTypeChange(oTicketTypeSelect, strId)
{
	var priceval = oTicketTypeSelect.value
	var priceTypeAry = priceval.split("|");

	//get the INPUT object that holds current price, it is one of the TR's children
	var oPriceInput = getChildByIdOrName(findRow(oTicketTypeSelect), "TTValue", true);
	//update it with the new price selected for this ticket
	oPriceInput.value = priceTypeAry[0];

	//now also get hidden tickettype input and populate it with correct tickettypeid (chosen by user)
	var oTicketType = gEBI(String("TicketTypeId" + arguments[2]));
	oTicketType.value = priceTypeAry[1];

	recalculateCart();
}

function recalculateCart()
{
	//get all price INPUT fields
	var vc = document.getElementsByName("TTValue");
	//calculate and update fees
	var subTotal = 0;
	for(var nX = 0; nX < vc.length; ++nX)
	{
		subTotal += parseFloat(vc[nX].value);
	}
	//at this point we have order price excluding discounts and fees

	/****** TODO: Include calculations *****************
	//calculate discounts
	var discountsTotal = CalculateDiscounts(oParentIDHolder["Performance_Discounts"], subTotal);

	//calculate and update fees
	var feesTotal = CalculateFees(oParentIDHolder["Client_FeeGroups"], subTotal);

	subTotal -= discountsTotal;
	subTotal += feesTotal;
	*/

	//calculate and update subtotal
	var stv = document.getElementById("subtotalval");
	stv.value = subTotal;

}

function findParentByTag(e, strTag)
{
	if (e.tagName == strTag)
		return e;
	else if (e.tagName == "BODY")
		return null;
	else
		return findParentByTag(e.parentNode, strTag);
}

function findRow(e)
{
	return findParentByTag(e, "TR");
}

function findCell(e)
{
	return findParentByTag(e, "TD");
}

function findTable(e)
{
	return findParentByTag(e, "TABLE");
}

function formatPhone(id,format) {
  	// only supports us format at present
  	rxPhone = /^(\(?\d{3}\)?[-\s.]?)?\d{3}[-\s.]?\d{4}$/;
  	testnum = id.value;
  	if (rxPhone.test(testnum)) {
		phonenum = String(testnum).replace(/\(/g,"").replace(/\)/g,"").replace(/\./g,"").replace(/-/g,"").replace(/ /g,"");
		if (phonenum.length == 7) {
			formatnum = phonenum.substr(0,3) + "-" + phonenum.substr(3,4);
		} else {
			formatnum = "(" + phonenum.substr(0,3) + ") " + phonenum.substr(3,3) + "-" + phonenum.substr(6,4);
		}
		id.value = formatnum;
	}
}


function NumAccuracy(val,acc) {
 	if (isNaN(val)) {
		val = 0;
	} else {
		acc = Math.pow(10,acc);
		val = Math.round(val*acc)/acc;
	}
	return val;
}

function DeleteItem(servID,itemID)
{
	var strUrl = gShoppingCartURL + "?RemoveItem=1&servID=" + servID + "&itemID=" + itemID;
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: strUrl,
				data: "<a>a</a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	CartInner(strResp);
	
	aryPayTypes = new Array(); //reset payment details
	updateTotals();
	PayCartComplite();
}

function BuyMore()
{
	
	var S = 0;
	if(gEBI('h_SubCounts'))
		S = Number(gEBI('h_SubCounts').value);
    
    var T = 0;
	if(gEBI('h_TicketCounts'))
		T = Number(gEBI('h_TicketCounts').value);
	if(T>0){
	  var oTP = gEBI('trTicket_0').parentNode
	  var oTicketRowsArray = getChildrenByPartialIdOrName(oTP, "trTicket_");
	  var T = oTicketRowsArray.length;
     }

	var CPO = 0;
	if(gEBN('hCouponOrder'))
		CPO = gEBN('hCouponOrder').length;

	var ITO = 0;
	if(gEBN('hItemOrder'))
		ITO = gEBN('hItemOrder').length;
	
	if (S==0 && T==0 && CPO==0 && ITO>0)
	 {
       if (gEBI("hCategory")!=null && gEBI("hCategory").value>0)
       {
	     clickCategory(gEBI("hCategory").value);
	    }
	    else
	    {
			runClickTab(2);	    
	    }
	 }
	 else
	   runClickTab(0);

	window.scroll(0,0);
}
function DeleteAll(){
	
	if (arrItems.length> 0)   
	 { arrItems.splice(0,arrItems.length);
	   gEBI("itemsCount").innerHTML="";
       gEBI("itemsAmount").innerHTML="";
       gEBI("ticketCount").innerHTML="";
       gEBI("SeasonCount").innerHTML="";
     }
     updateTotalItems();
	//self.location = self.location;

	EracePaycart();

	if(gClientId == 41)
	{
		runShowShoppingCartDirect('&RemoveAll=2');
		window.opener.focus();
	}
	else
		runClickTab(0,'RemoveAll=2');
	
	window.scroll(0,0);
}
function AddPointsToAccountBalance(nPointAmount)
{
	var hAccountBalance = gEBI("h_AccountBalance");
	if(null == hAccountBalance) 
		return;
	hAccountBalance.value = Number(hAccountBalance.value) + Number(nPointAmount);
}

function ChangeExtraDiscounts(pSelect,pExtraSelect)
{
    if(pExtraSelect!=null)
    {
        if(pExtraSelect.getAttribute('ttis')=='' || pExtraSelect.getAttribute('ttis').indexOf(pSelect.options[pSelect.selectedIndex].getAttribute('TicketType'))!=-1)
        {
            pExtraSelect.style.display='inline';
        }
        else
        {
            pExtraSelect.style.display='none';
        }    
    }
}

function AddOrderExtraFee(pDollarFee,pFeeID)
{
	var lOrderFees = gEBI("txtExtraOrderFees");
     
	if(null == lOrderFees) return;
	lOrderFees.setAttribute("ExtraFeeIDs", lOrderFees.getAttribute("ExtraFeeIDs")+pFeeID+",");
	lOrderFees.setAttribute("ExtraFeeAmount", Number(Number(lOrderFees.getAttribute("ExtraFeeAmount"))+Number(pDollarFee)));
}
function BalanceOrderFee(pThis)
{
	var lFeeID = pThis.getAttribute("feeID");
	var lBalanceOrderFees = gEBI("txtBalanceOrderFee");
	var lExtraOrderFees = gEBI("txtExtraOrderFees");
	if(null == lBalanceOrderFees || null == lExtraOrderFees) return;

	if(lExtraOrderFees.getAttribute("ExtraFeeIDs").indexOf(","+lFeeID + ",") == -1 && lExtraOrderFees.getAttribute("ExtraFeeIDs").indexOf(lFeeID + ",") != 0)
	{			
		lBalanceOrderFees.setAttribute("ExtraFeeIDs", lBalanceOrderFees.getAttribute("ExtraFeeIDs")+lFeeID+",");
		lExtraOrderFees.setAttribute("ExtraFeeIDs", lExtraOrderFees.getAttribute("ExtraFeeIDs")+lFeeID+",");
	}
	var lBalanceValue = Number(Number(lBalanceOrderFees.getAttribute("BalanceFeeAmount"))-Number(gEBI("txtTotal").value) );
	if(lBalanceValue < 0) lBalanceValue = 0;
	lBalanceOrderFees.setAttribute("BalanceFeeAmount", lBalanceValue);
	pThis.style.display = "none";
}
function ClearExtraFees()
{
	var lOrderFees = gEBI("txtExtraOrderFees");
	if(null == lOrderFees) return;
	lOrderFees.setAttribute("ExtraFeeIDs", "");
	lOrderFees.setAttribute("ExtraFeeAmount", 0.00);
}
function EnableDisableTransaction()
{
	if(!(isWeb&&!isBox)) return;
	
	var oSel = gEBI(gEBI("paymentmethodUniqueId").value);
	if(null == oSel) return;
	
	var cnt = 0;
	var oTable = gEBI('tblPay'+cnt);
	if(gOrderTotal <= 0)
	{
		oSel.disabled = true;
		while(oTable != null)
		{
			oTable.style.display = "none";
			cnt++;
			oTable = gEBI('tblPay'+cnt);
		}
	}
	else
	{
		oSel.disabled = false;
		SwitchWebPaymentType(null,oSel, null);
	}
}
function TotalDiscounts(oItDiscount,k)
{
	    var oNextItemDiscount = oItDiscount;
	    var nLimitMax=0;
	    var oItem=gEBI("hItemOrder_"+k);
	    var nDollarAmount;
	    var nPercentageAmount;
	    var TotalDiscounts=0;
	    var nDiscountAmount = 0;
	    do{
		oNextItemDiscount = getNextSibling(oNextItemDiscount);
		//alert("oNextItemDiscount=" + oNextItemDiscount);
		if(null == oNextItemDiscount)
			break;
		//alert("oNextItemDiscount.tagName=" + oNextItemDiscount.tagName);
		if("INPUT" != oNextItemDiscount.tagName)
			continue;
		//alert("oNextItemDiscount.type=" + oNextItemDiscount.type);
		if("hidden" != oNextItemDiscount.type)
			continue;
//		alert("oNextItemDiscount.name=" + oNextItemDiscount.name);
		var nDollarAmount = oNextItemDiscount.getAttribute("dollaramount");
		var nPercentageAmount = oNextItemDiscount.getAttribute("percentageamount");
		var nLimit = oNextItemDiscount.getAttribute("Limit");

		//alert(nLimit);
		if (oItem.getAttribute("Quantity")>=nLimit && nLimitMax<nLimit)
		{
		  if (nLimit>nLimitMax)
		     {nLimitMax=nLimit;
		      nDollarAmount = oNextItemDiscount.getAttribute("dollaramount");
		      nPercentageAmount = oNextItemDiscount.getAttribute("percentageamount");
		      
		      if (nDollarAmount!=null)
		        { TotalDiscounts=nLimitMax*nDollarAmount;
		          oItem.setAttribute("DiscountId",oNextItemDiscount.getAttribute("discountID"));
		          oItem.setAttribute("DiscountAmount",parseFloat(nDollarAmount).toFixed(2));
		          oItem.setAttribute("Limit",oNextItemDiscount.getAttribute("Limit"));
		        }
			  else
				 { TotalDiscounts=( (oItem.getAttribute("ListPrice")*nPercentageAmount)/100)*nLimitMax ;
				   oItem.setAttribute("DiscountId",oNextItemDiscount.getAttribute("discountID"));
		           oItem.setAttribute("DiscountAmount", parseFloat((oItem.getAttribute("ListPrice")*nPercentageAmount)/100).toFixed(2) );
		           oItem.setAttribute("Limit",oNextItemDiscount.getAttribute("Limit"));
				 }
		  
				gEBI("txtItemOrderDiscount_"+k).value=TotalDiscounts.toFixed(2);
		    
		     }
		   
		}
		}while(oNextItemDiscount != null);
		


		return TotalDiscounts;
}

function deliverymethod_onchange(oSelect)
{
	updateTotals();
	EnableDisableCustomCartFields(oSelect);
}

function EnableDisableCustomCartFields(pSelect)
{
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom1"));
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom2"));
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom3"));
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom4"));
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom5"));
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom6"));
	EnableDisableCustomCartField(pSelect.value, gEBI("patron_custom7"));
	
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom1"));
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom2"));
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom3"));
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom4"));
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom5"));
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom6"));
	EnableDisableCustomCartField(pSelect.value, gEBI("shipping_custom7"));
}

function EnableDisableCustomCartField(pDeliveryMethodId, pField)
{
	if(null == pField) return;
	var lDeliveryMethodIds = pField.getAttribute("DeliveryMethodIds");
	if(null == lDeliveryMethodIds) return
	
	var lDisabled = (-1 == lDeliveryMethodIds.indexOf(","+pDeliveryMethodId+","));
	
	EnableDisableTree(pField.parentNode.parentNode, lDisabled);
}

function EnableDisableTree(pParent, pDisabled)
{
	if(null != pParent.disabled)
		pParent.disabled = pDisabled;

	for(var i=0; i<pParent.childNodes.length; i++)
	{
		EnableDisableTree(pParent.childNodes[i], pDisabled)
	}
}
function FillSelectPerformanceForMonth(Date1,nextevent)
{
	if(nextevent != "nextevent") nextevent = "";
	var strShortDate = "" + Date1.getFullYear() + "-" + (Date1.getMonth()+1) + "-1";
	var strUrl = "FillSelectPerformance.aspx?" + GetRandomQSParam() + "&t=0&d1=" + strShortDate +"&for=old&ne="+nextevent + (arguments[2]!=null?'&'+arguments[2]:'');
	
	$.post(strUrl
		,function(data){
			var strResp = data;
			var oSpan = document.createElement("SPAN");
			oSpan.innerHTML = strResp;
			oSpan=getChildByTagName(oSpan,'span',true);
			var lWords = oSpan.innerHTML.split('<!-- Calendar -->');
			oSpan.innerHTML = lWords[0];
			var divSingle=gEBI('divSingle');
			if(divSingle==null) divSingle=gEBI('tdList');
			divSingle.innerHTML = "";
			divSingle.appendChild(oSpan);
			oSpan = document.createElement("SPAN");
			oSpan.innerHTML = lWords[1];
			gEBI('tdCal').innerHTML = "";
			gEBI('tdCal').appendChild(oSpan);
		});
}

function runBeforeFillPerformances(str,id)
{
	var strId = "" + cal.Date.getFullYear() + "" + (cal.Date.getMonth()+1) + id;
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
		"<fn>BeforeFillPerformances</fn>" +
		"<arg>"+str+"</arg>" +
		"</cmd>" +
	"</cmds>";

	handleMouseClick("bfp"+strId,xmlData,"CallBackSALES");
}
function BeforeFillPerformances(str)
{
	eval(str);
}
function runFillPerformances()
{
	var strId = "" + cal.Date.getFullYear() + "" + (cal.Date.getMonth()+1) + arguments[1];
	var xmlData = "<cmds>";
		if("" != arguments[0])
		{
		xmlData += "<cmd>" +
		"<fn>BeforeFillPerformances</fn>" +
		"<arg>"+arguments[0]+"</arg>" +
		"</cmd>";
		}
		xmlData += "<cmd><fn>fillPerformances</fn>";
		if(null != arguments[2])
		xmlData += "<arg>"+arguments[2]+"</arg>";
		if(null != arguments[3])
		xmlData += "<arg>"+arguments[3]+"</arg>";
		if(null != arguments[4])
		xmlData += "<arg>"+arguments[4]+"</arg>";
		xmlData += "</cmd>"+
	"</cmds>";

	handleMouseClick("fp"+strId,xmlData,"CallBackSALES");

}
function fillPerformances()
{
	if($("#divOrders").length > 0)
	{
		$("#divCart").hide();
		$("#divPayCart").hide();
		
		HideLegend();
		
		$("#divSection").html("");
		$("#divSection").show();
		
		$("#divImageMap").html("");
		$("#divImageMap").show();
		
		$("#divOrders").show();
		
		$("#divNonOrders").hide();
		$("#ulBestAvailable").hide();
		
		$("#divH").html("");
	}
	
	$("#tdList").html( PerformanceList(arguments[0],arguments[1],arguments[2]) );
}
function runShowCalendar()
{
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
		"<fn>ShowCalendar</fn>" +
		"</cmd>" +
	"</cmds>";

	handleMouseClick("showcal",xmlData,"CallBackSALES");
}
function ShowCalendar()
{
	gQuickSaleMode = false;
	var dt = new Date();
	dt.setMonth(dt.getMonth()+1);
	SetCookie("ShowCal","LView",dt,"/");

	var tdCalendarView = gEBI("tdCalendarView");
	var tdListView = gEBI("tdListView");
	var tdQuickSaleView = gEBI("tdQuickSaleView");
	if(null != tdCalendarView && null != tdListView)
	{
		tdListView.style.cursor = "default";
		tdListView.style.color = "#C24124"
		tdListView.style.backgroundColor = "#FFFFFF";
		tdListView.style.border = "1 solid #75747A";
		tdListView.style.borderBottom = "none";
		
		tdCalendarView.style.cursor = "pointer";
		tdCalendarView.style.color = "#000000"
		tdCalendarView.style.backgroundColor = "#D6D7DE";
		tdCalendarView.style.border = "none";
		tdCalendarView.style.borderBottom = "1 solid #75747A";
		
		tdQuickSaleView.style.cursor = "pointer";
		tdQuickSaleView.style.color = "#000000"
		tdQuickSaleView.style.backgroundColor = "#D6D7DE";
		tdQuickSaleView.style.border = "none";
		tdQuickSaleView.style.borderBottom = "1 solid #75747A";
	}
	if(null != gEBI('tdCal')) gEBI('tdCal').style.display = "block";
	show_calendar();cal.set();
}

function runShowCalendarPerformances(m,y)
{
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
		"<fn>ShowCalendarPerformances</fn>" +
		"<arg>"+m+"</arg>"+
		"<arg>"+y+"</arg>"+
		"</cmd>" +
	"</cmds>";

	handleMouseClick("showcalp"+String(m)+String(y),xmlData,"CallBackSALES");
}

function ShowCalendarPerformances(m,y)
{
	gQuickSaleMode = false;
	var dt = new Date();
	dt.setMonth(dt.getMonth()+1);
	SetCookie("ShowCal","CView",dt,"/");

	var tdCalendarView = gEBI("tdCalendarView");
	var tdListView = gEBI("tdListView");
	var tdQuickSaleView = gEBI("tdQuickSaleView");
	if(null != tdCalendarView && null != tdListView)
	{
		tdCalendarView.style.cursor = "default";
		tdCalendarView.style.color = "#C24124"
		tdCalendarView.style.backgroundColor = "#FFFFFF";
		tdCalendarView.style.border = "1 solid #75747A";
		tdCalendarView.style.borderBottom = "none";
		
		tdListView.style.cursor = "pointer";
		tdListView.style.color = "#000000"
		tdListView.style.backgroundColor = "#D6D7DE";
		tdListView.style.border = "none";
		tdListView.style.borderBottom = "1 solid #75747A";
		
		tdQuickSaleView.style.cursor = "pointer";
		tdQuickSaleView.style.color = "#000000"
		tdQuickSaleView.style.backgroundColor = "#D6D7DE";
		tdQuickSaleView.style.border = "none";
		tdQuickSaleView.style.borderBottom = "1 solid #75747A";
	}
	
	$('#tdCal').hide();
	if($('#divOrders').length > 0)
	{
		$('#divCart').hide();
		$('#divPayCart').hide();
	
		HideLegend();
		
		$('#divSection').show();
		$('#divSection').html("");
		$('#divImageMap').show();
		$('#divImageMap').html("");
		$('#divOrders').show();
		$('#divNonOrders').hide();
		$('#ulBestAvailable').hide();
	}
	var rq = "Events.aspx";
	if(m != 0 || y != 0) rq += "?m="+m+"&y="+y;
	
	$.ajax({
			type: "POST",
			url: rq,
			data: "<a>asd</a>",
			async: false, 
			contentType: "text/xml; charset=utf-8",
			dataType: "text",
			success: function(data, textStatus) {
				var arrResp = data.split('--BREAK HERE FOR JS--');
				$('#divSingle').html(arrResp[0]);
				try{
					eval(arrResp[1]);
				}
				catch(e){
					alert(e);
				}
				return false;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("error = " + XMLHttpRequest.responseText);
				return false;
			}
		});
		
		
}

function runShowQuickSale()
{
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
			"<fn>ShowQuickSale</fn>" +
		"</cmd>" +
	"</cmds>";

	handleMouseClick("showquicksale",xmlData,"CallBackSALES");
}

function ShowQuickSale()
{
	//clean up any existing cart objects
	try{
		gEBI("addressForm").parentNode.removeChild(gEBI("addressForm"))
	}catch(e){}
	
	var qsPerfCookie = GetCookie("QuickSalePerformance");
	var dt = new Date();
	dt.setMonth(dt.getMonth()+1);
	SetCookie("ShowCal","QSView",dt,"/");

	var tdCalendarView = gEBI("tdCalendarView");
	var tdListView = gEBI("tdListView");
	var tdQuickSaleView = gEBI("tdQuickSaleView");
	if(null != tdCalendarView && null != tdListView && null != tdQuickSaleView )
	{
		tdQuickSaleView.style.cursor = "default";
		tdQuickSaleView.style.color = "#C24124"
		tdQuickSaleView.style.backgroundColor = "#FFFFFF";
		tdQuickSaleView.style.border = "1 solid #75747A";
		tdQuickSaleView.style.borderBottom = "none";
		
		tdCalendarView.style.cursor = "pointer";
		tdCalendarView.style.color = "#000000"
		tdCalendarView.style.backgroundColor = "#D6D7DE";
		tdCalendarView.style.border = "none";
		tdCalendarView.style.borderBottom = "1 solid #75747A";
		
		tdListView.style.cursor = "pointer";
		tdListView.style.color = "#000000"
		tdListView.style.backgroundColor = "#D6D7DE";
		tdListView.style.border = "none";
		tdListView.style.borderBottom = "1 solid #75747A";
	}
	
	$("#tdCal").hide();
	
	if(gEBI('divOrders'))
	{
		$("#divCart").hide();
		$("#divPayCart").hide();

		HideLegend();

		$("#divSection").html("");
		$("#divSection").show();
		
		$("#divImageMap").html("");
		$("#divImageMap").show();
		
		$("#divOrders").show();
		
		$("#divNonOrders").hide();
		$("#ulBestAvailable").hide();
	}
	
	if(qsPerfCookie == null || isNaN(qsPerfCookie))
	{
		gQuickSaleMode = true;
		show_calendar();			
		cal.set();
		$("#divSingle").html("<div style='font-weight:bold;background-color:ffffaa'>Please choose a default performance for quick sale mode</div>" + $("#divSingle").html() );
		return;
	}

	var rq = "QuickSale.aspx?pid=" + qsPerfCookie;
	var strResp = "";
	
	$.ajax({
				type: "POST",
				url: rq,
				data: "<a>a</a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	var arrResp = strResp.split('--BREAK HERE FOR JS--');
	$("#divSingle").html(arrResp[0]);
//	DebugWrite(arrResp[1]);
//	DebugShowResults();
	try{
		eval(arrResp[1]);
	}
	catch(e){
	}

}

function PerformanceList(){
	HideScanTabs();
	var isOnDate = arguments[0];
	var dtNow = new Date();
	var strHTML = "<DIV id='PerformanceInfo' style='position:absolute;display:none;BACKGROUND-COLOR: #ffffff;'>"+
			"<TABLE style='border:1px solid;border-color:#000000;' cellspacing='0' cellpadding='0'>"+
			"<TR><TD><DIV id='PerformancePieChart' align='center'></DIV></TD></TR>"+
			"</TABLE></DIV>"+
			"<table id='tblPerformanceList' cellSpacing='0' cellPadding='0' width='635' border=0>";
	var z = 0;
	var q = 0;
	
	var PerfIDs = null;
	if("undefined" != typeof(cal))
	{
		if('orderlookup' == cal.coller)
		{
			var ohPLID	= gEBI("hPerfListID");
			var tmpPerfIDs = ohPLID.value.split(",");
			PerfIDs = Array();
			for(var ID in tmpPerfIDs)
				PerfIDs[tmpPerfIDs[ID]] = 1;
		}	
	}
	var num = 0;
	for(var e=0;e<Events.length;e++){
		if(isBox){
			var isExists = false;
			var strHTMLPerf = "<tr><td colspan='2' align=center class='EventList'>" + unescape(Events[e].Name) + " <span id='Alltod' onclick='runFillPerformances(\"\","+Events[e].ID+",\"event\","+Events[e].ID+")' onmouseover='this.className=\"PerformanceListOver1\";' onmouseout='this.className=\"PerformanceList\"'>["+GetTranslation("show_all")+"]</span></td></tr><tr><td";
			if(!Events[e].ImageOnBox)
				strHTMLPerf += " colspan ='2'";
			strHTMLPerf += "><table cellSpacing='0' width='100%'>";

			if(Events[e].ImageOnBox)
				if(null!=Events[e].Description){
					strHTMLPerf += "<tr><td class='EventListDescription'>" + unescape(Events[e].Description).replace(/{/g,"<").replace(/}/g,">") + "&nbsp;</td></tr>";
				}

			var iStripy = 0;
			for(var p=0;p<Events[e].Performances.length;p++){
			
				if('orderlookup' == cal.coller)
				{
					if(null == CheckedPerfIDs[Events[e].Performances[p].ID])
					{
						CheckedPerfIDs[Events[e].Performances[p].ID] = new Object();
						CheckedPerfIDs[Events[e].Performances[p].ID].checked = "";
						CheckedPerfIDs[Events[e].Performances[p].ID].Name = Events[e].Performances[p].Name;
						CheckedPerfIDs[Events[e].Performances[p].ID].DateTime = Events[e].Performances[p].DateTime;
					}
					if(null != PerfIDs[Events[e].Performances[p].ID])
						CheckedPerfIDs[Events[e].Performances[p].ID].checked = "checked";
				}			
				
				if((Events[e].Performances[p].DateTime.getMonth()==cal.Date.getMonth())&&(Events[e].Performances[p].DateTime.getFullYear()==cal.Date.getFullYear())&&((null == isOnDate)
					||('next'  == isOnDate && 'selectperformance' == cal.coller && ('=' == CompareByDateTime(Events[e].Performances[p].DateTime,dtNow) || '>' == CompareByDateTime(Events[e].Performances[p].DateTime,dtNow)))
					||('next'  == isOnDate && 'orderlookup' == cal.coller) 
					||('date'  == isOnDate && Events[e].Performances[p].DateTime.getDate()==cal.Date.getDate())
					||('day'   == isOnDate && Events[e].Performances[p].DateTime.getDay()==arguments[1])
					||('week'  == isOnDate && Events[e].Performances[p].DateTime.getDate()>=arguments[1] && Events[e].Performances[p].DateTime.getDate()<=arguments[2])
					||('event' == isOnDate && Events[e].Performances[p].Event.ID == arguments[1])
					))
				{
					isExists = true;
					
					if('selectperformance' == cal.coller)
					{
						strHTMLPerf += "<tr><td align=left id='trPerf" + Events[e].Performances[p].ID + "' class='PerformanceList" + (iStripy%2) + "' onmouseover='this.className=\"PerformanceListOver" + (iStripy%2) + "\";' onmouseout='this.className=\"PerformanceList" + (iStripy%2) + "\";' PerfDate='" + Events[e].Performances[p].DateTime + "' PerfID='" + Events[e].Performances[p].ID + "'  onclick='gCurrentPerformanceId=parseInt(this.getAttribute(\"PerfID\"));isSeason=0;";
						if(null!=gEBI("SeasonPackages")){
							strHTMLPerf += "gEBI(\"SeasonPackages\").style.display=\"none\";";
						}
						var strDate=LongDate(Events[e].Performances[p].DateTime, 1) + " " + ShortTime(Events[e].Performances[p].DateTime);
						//LongDate(Events[e].Performances[p].DateTime, 1) + " " + ShortTime(Events[e].Performances[p].DateTime);
						var strName = escape(Events[e].Performances[p].Name);
						strHTMLPerf += "ItsDate = new Date("+Events[e].Performances[p].DateTime.getFullYear()+","+Events[e].Performances[p].DateTime.getMonth()+","+Events[e].Performances[p].DateTime.getDate()+","+Events[e].Performances[p].DateTime.getHours()+","+Events[e].Performances[p].DateTime.getMinutes()+");runGetSections(" + Events[e].Performances[p].ID + "," + Events[e].Performances[p].Event.Venue.ID + "," + Events[e].Performances[p].PricingOverlay.LayoutID + "," + gClientId + ",ItsDate,\"" + strName + "\",-1,\"\"," + Events[e].Performances[p].DefaultSectionId + ");'>"+
							"<img style='cursor:auto;'onmouseover='ShowPerformanceInfo(" + gClientId + "," + Events[e].Performances[p].PricingOverlay.LayoutID + "," + Events[e].Performances[p].ID + ");' onmouseout='ClosePerformanceInfo();' src='images/icn_popup_blue.gif'/> "+
							unescape(strName) + " &nbsp;&nbsp;<span class='PerformanceListDate'>" + strDate + "</span></td>";
						strHTMLPerf += "</tr>";
						num++;
						if('next' == isOnDate) break;
					}
					if('orderlookup' == cal.coller)
					{
						strHTMLPerf += "<tr><td  align=left class='PerformanceList" + (iStripy%2) + "' onmouseover='this.className=\"PerformanceListOver" + (iStripy%2) + "\";' onmouseout='this.className=\"PerformanceList" + (iStripy%2) + "\";' PerfDate='" + Events[e].Performances[p].DateTime + "' PerfID='" + Events[e].Performances[p].ID + "'  onclick='checkPerformance("+e+","+p+")';";
						var strDate = LongDate(Events[e].Performances[p].DateTime, 1) + " " + ShortTime(Events[e].Performances[p].DateTime);
						var strName = Events[e].Performances[p].Name;
						strHTMLPerf += "'><input id='chPerf"+Events[e].Performances[p].ID+"' type='checkbox' "+CheckedPerfIDs[Events[e].Performances[p].ID].checked+" >" + unescape(strName) + " &nbsp;&nbsp;<span class='PerformanceListDate'>" + strDate + "</span></td>";
						strHTMLPerf += "</tr>";
					}
					iStripy++;
				}
			}
			strHTMLPerf += "</table></td>"
			if(Events[e].ImageOnBox){
				if(null!=Events[e].Graphic){
					strHTMLPerf += "<td align='right'><img src='" + Events[e].Graphic.URL + "'/></td>";
				}
			}
			strHTMLPerf += "</tr>";
			if(isExists)
			strHTML += strHTMLPerf;
		}
		else if(isWeb&&!isBox){
			//for(var e=0;e<Events.length;e++){
				strHTML += "<tr><td align=center class='EventList' colspan=2>" + unescape(Events[e].Name) + "</td></tr>";
				var rowspan = Events[e].Performances.length;
				var strImg = "";
				var imgHTML = "";
				if(null!=Events[e].Graphic){
					imgHTML = "<img src='" + Events[e].Graphic.URL + "'>";
				}
				if(null!=Events[e].Description){
					rowspan++;
					strHTML += "<tr><td class='EventListDescription'>" + unescape(Events[e].Description).replace(/{/g,"<").replace(/}/g,">") + "&nbsp;</td><td rowspan=" + rowspan + " valign='top' align='center'>" + imgHTML + "</td></tr>";
				}
				else{
					strImg = "<td rowspan=" + rowspan + " valign='top' align='center'>" + imgHTML + "</td>";
				}
				for(var p=0;p<Events[e]['Performances'].length;p++){
					if(Events[e].Performances[p].SoldOut != true)
						strHTML += "<tr><td align=left id='trPerf" + Events[e].Performances[p].ID + "' class='PerformanceList" + (p%2) + "' onmouseover='this.className=\"PerformanceListOver" + (p%2) + "\";' onmouseout='this.className=\"PerformanceList" + (p%2) + "\";' PerfDate='" + Events[e].Performances[p].DateTime + "' PerfID='" + Events[e].Performances[p].ID + "'  onclick='gCurrentPerformanceId=parseInt(this.getAttribute(\"PerfID\"));isSeason=0;";
					else
						strHTML += "<tr><td align=left id='trPerf" + Events[e].Performances[p].ID + "' class='PerformanceList" + (p%2) + "' PerfDate='" + Events[e].Performances[p].DateTime + "' PerfID='" + Events[e].Performances[p].ID + "' onclick='alert(\"Tickets are no longer available for this performance.\")'";
					num++;
					if(null!=gEBI("SeasonPackages")){
						strHTML += "gEBI(\"SeasonPackages\").style.display=\"none\";";
					}
					
					var strDate = LongDate(Events[e].Performances[p].DateTime,1) + " " + ShortTime(Events[e].Performances[p].DateTime);
					var strName = escape(Events[e].Performances[p].Name);
					if(Events[e].Performances[p].SoldOut != true)
						strHTML += "ItsDate = new Date("+Events[e].Performances[p].DateTime.getFullYear()+","+Events[e].Performances[p].DateTime.getMonth()+","+Events[e].Performances[p].DateTime.getDate()+","+Events[e].Performances[p].DateTime.getHours()+","+Events[e].Performances[p].DateTime.getMinutes()+");runGetSections(" + Events[e].Performances[p].ID + "," + Events[e].Performances[p].Event.Venue.ID + "," + Events[e].Performances[p].PricingOverlay.LayoutID + "," + gClientId + ",ItsDate ,\"" + strName + "\",-1,\"\"," + Events[e].Performances[p].DefaultSectionId + ");'>" + unescape(strName) + " &nbsp;&nbsp;<span class='PerformanceListDate'>" + strDate + "</span></td>";
					else
						strHTML += unescape(strName) + " &nbsp;&nbsp;<span class='PerformanceListDate'>" + strDate + "</span></td>";
					if(p==0)
						strHTML += strImg;
					strHTML += "</tr>";
				}
			//}
		}
	}
	strHTML += "</table>";
	//if(isBox && null != isOnDate && (('next' != isOnDate && 'orderlookup' == cal.coller) || 'orderlookup' != cal.coller))strHTML += "<br/><span id='ShowListPerf' onclick='cal.Date.setDate(1);fillPerformances();' onmouseover='this.className=\"PerformanceListOver1\";' onmouseout='this.className=\"PerformanceList\"'>[show all performances]</span>";
	//var win = window.open('','_blank');
	//win.document.write(strHTML);
	return strHTML;
}

function openDiv(obj){
	var div = obj.parentNode.childNodes[obj.parentNode.childNodes.length-1];
	if(obj.innerHTML=='+'){
		div.style.display = 'block';
		obj.innerHTML = '-';
		var TBL = div.childNodes[0];
		if(TBL.rows.length>5){
			div.style.height = '100px';
			div.style.overflowY = 'scroll';
		}
	}
	else{
		div.style.display = 'none';
		obj.innerHTML = '+';
	}
}

function ShortDate(dt){
	var retDt = String(PadInFront((dt.getMonth() + 1),2) + "/" + PadInFront(dt.getDate(),2) + "/" + dt.getFullYear());
	return retDt;
}

function CancelUseInfo()
{
	if(null != window.opener) window.opener.focus();
	window.close();
}

function UseInfo(id)
{
	var obj=gEBI(String('patron_salutation1_' + id));
	if(null != obj)
	{
	//add values to cart inputs
	salut = returnBlank(obj.value);
	firstnm = returnBlank(gEBI(String('patron_firstname1_' + id)).value);
	lastnm = returnBlank(gEBI(String('patron_lastname1_' + id)).value);
	spousesalut = returnBlank(gEBI(String('patron_salutation2_' + id)).value);
	spousefirstnm = returnBlank(gEBI(String('patron_firstname2_' + id)).value);
	spouselastnm = returnBlank(gEBI(String('patron_lastname2_' + id)).value);
	compny = returnBlank(gEBI(String('patron_company_' + id)).value);
	adr = returnBlank(gEBI(String('patron_address_' + id)).value);
	adr2 = returnBlank(gEBI(String('patron_address2_' + id)).value);
	cit = returnBlank(gEBI(String('patron_city_' + id)).value);
	stat = returnBlank(gEBI(String('patron_state_' + id)).value);
	zipcd = returnBlank(gEBI(String('patron_zip_' + id)).value);
	cntry = returnBlank(gEBI(String('patron_country_' + id)).value);
	regn = returnBlank(gEBI(String('patron_region_' + id)).value);
	phne = returnBlank(gEBI(String('patron_phone_' + id)).value);
	custom1 = returnBlank(gEBI(String('patron_custom1_' + id)).value);
	custom2 = returnBlank(gEBI(String('patron_custom2_' + id)).value);
	custom3 = returnBlank(gEBI(String('patron_custom3_' + id)).value);
	custom4 = returnBlank(gEBI(String('patron_custom4_' + id)).value);
	custom5 = returnBlank(gEBI(String('patron_custom5_' + id)).value);
	custom6 = returnBlank(gEBI(String('patron_custom6_' + id)).value);
	custom7 = returnBlank(gEBI(String('patron_custom7_' + id)).value);
	phnetyp = gEBI(String('patron_phonetypeid_' + id)).value;
	patronid = gEBI(String('patron_id_' + id)).value;
	email = returnBlank(gEBI(String('patron_email_' + id)).value);
	addressid = returnBlank(gEBI('patron_addressid_' + id).value);
	emailtyp = returnBlank(gEBI(String('patron_emailtypeid_' + id)).value);
	}
	if(null != window.opener && !window.opener.closed && null != window.opener.setFormVals)
	{		
		if(null != obj) window.opener.setFormVals(salut,firstnm,lastnm,spousesalut,spousefirstnm,spouselastnm,compny,adr,adr2,cit,stat,zipcd,cntry,regn,phne,phnetyp,email,emailtyp,patronid,addressid,custom1,custom2,custom3,custom4,custom5,custom6,custom7);
		else window.opener.PatronLookUpById(id);
		window.opener.focus();
		window.close();
	}else
	{
		if(null != obj) setFormVals(salut,firstnm,lastnm,spousesalut,spousefirstnm,spouselastnm,compny,adr,adr2,cit,stat,zipcd,cntry,regn,phne,phnetyp,email,emailtyp,patronid,addressid,custom1,custom2,custom3,custom4,custom5,custom6,custom7);
		else window.opener.PatronLookUpById(id);
		CloseAddressLookUp();
	}
}

function setFormVals(salut,firstnm,lastnm,spousesalut,spousefirstnm,spouselastnm,compny,adr,adr2,cit,stat,zipcd,cntry,regn,phne,phnetyp,email,emailtyp,id,addressid,custom1,custom2,custom3,custom4,custom5,custom6,custom7)
{
	if(null !=	gEBI("patron_id") && ("patron"==gAddressFindType || "bill"==gAddressFindType ))
				gEBI("patron_id").value = unescape(id);
				
	if(null !=	gEBI("patron_salutation1"))
	{
				gEBI("patron_salutation1").value = unescape(salut);
				SetCustomCartFields("patron_salutation1",false);
	}
	if(null !=	gEBI("patron_firstname1"))
				gEBI("patron_firstname1").value = unescape(firstnm);
				
	if(null !=	gEBI("patron_lastname1"))
				gEBI("patron_lastname1").value = unescape(lastnm);
				
	if(null !=	gEBI("patron_salutation2"))
	{
				gEBI("patron_salutation2").value = unescape(spousesalut);
				SetCustomCartFields("patron_salutation2",false);
	}			
	if(null !=	gEBI("patron_firstname2"))
				gEBI("patron_firstname2").value = unescape(spousefirstnm);
				
	if(null !=	gEBI("patron_lastname2"))
				gEBI("patron_lastname2").value = unescape(spouselastnm);
				
	if(null !=	gEBI("patron_company"))
				gEBI("patron_company").value = unescape(compny);
				
	if(null !=	gEBI("patron_address"))
				gEBI("patron_address").value = unescape(adr);
				
	if(null !=	gEBI("patron_address2"))
				gEBI("patron_address2").value = unescape(adr2);
				
	if(null !=	gEBI("patron_city"))
				gEBI("patron_city").value = unescape(cit);
	var st = unescape(stat);
	st = st.replace(' ','');
	
	if(null !=	gEBI("patron_state"))
				gEBI('patron_state').value = st;
				
	if(null !=	gEBI("patron_zip"))
				gEBI("patron_zip").value = unescape(zipcd);
		
	if(("bill"==gAddressFindType || "shipp"==gAddressFindType) && "" == Trim(cntry))
		cntry = "USA";
					
	if(null !=	gEBI("patron_country"))
				gEBI("patron_country").value = unescape(cntry);
				
	if(null !=	gEBI("patron_region"))
				gEBI("patron_region").value = unescape(regn);
				
	if(null !=	gEBI("patron_phone"))
				gEBI("patron_phone").value = unescape(phne);

	if(null !=	gEBI("patron_email"))
				gEBI("patron_email").value = unescape(email);
				
	if(null !=	gEBI("patron_phonetype"))
		if(phnetyp != null && phnetyp != "")
			for(var i=0;i<gEBI('patron_phonetype').options.length;i++){
				if(gEBI('patron_phonetype').options[i].value==unescape(phnetyp))
					gEBI('patron_phonetype').selectedIndex = i;
			}
	if(null !=	gEBI("patron_emailtype"))
		if(emailtyp != null && emailtyp != "")
			for(var i=0;i<gEBI('patron_emailtype').options.length;i++){
				if(gEBI('patron_emailtype').options[i].value==unescape(emailtyp))
					gEBI('patron_emailtype').selectedIndex = i;
			}

	if(null != gEBI("patron_custom1"))
	{
		gEBI("patron_custom1").value = custom1;
		SetCustomCartFields("patron_custom1");
	}
	if(null != gEBI("patron_custom2"))
	{
		gEBI("patron_custom2").value = custom2;
		SetCustomCartFields("patron_custom2");
	}
	if(null != gEBI("patron_custom3"))
	{
		gEBI("patron_custom3").value = custom3;
		SetCustomCartFields("patron_custom3");
	}
	if(null != gEBI("patron_custom4"))
	{
		gEBI("patron_custom4").value = custom4;
		SetCustomCartFields("patron_custom4");
	}
	if(null != gEBI("patron_custom5"))
	{
		gEBI("patron_custom5").value = custom5;
		SetCustomCartFields("patron_custom5");
	}
	if(null != gEBI("patron_custom6"))
	{
		gEBI("patron_custom6").value = custom6;
		SetCustomCartFields("patron_custom6");
	}
	if(null != gEBI("patron_custom7"))
	{
		gEBI("patron_custom7").value = custom7;
		SetCustomCartFields("patron_custom7");
	}
	if(""!=id && "0"!=id)
	{
		gEBI("patron_billingaddressid").value = unescape(addressid);
		gEBI("patron_DIVupdateaddress").style.display = "block";
		gEBI("shipp_DIVupdateaddress").style.display = "block";
	}
	else
	{
		gEBI("patron_billingaddressid").value = "0";
		gEBI("patron_DIVupdateaddress").style.display = "none";
		gEBI("shipp_DIVupdateaddress").style.display = "none";
	}
	getPatronCoupons(); //todo: remove comments

	//PayCartComplite();
	SetCountryAndState("patron");
	SetCountryAndState("shipping");
}
function resetAddress()
{
	//clear form
	gEBI('addressForm').reset();

	//clear patron
	//requesting a page
	
	var strUrl = gShoppingCartURL + "?clear=1";
	
	$.ajax({
				type: "POST",
				url: strUrl,
				data: "<a>a</a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	updateTotals();
}

function checkCoupon(obj){
	var strCP = obj.value;
	var arrCP = strCP.split('-');
	var isValid = false;
	
	if(arrCP.length >= 2)
	{
		var rcID = GetIntFromX(arrCP[0]);
		var cpID = GetIntFromX(arrCP[1]);
		getClientCoupon(rcID,cpID);
		for(var r=0;r<gClientCoupons.length;r++){
			if((gClientCoupons[r].ID==rcID)&&(null!=gClientCoupons[r].Coupon)&&(gClientCoupons[r].Coupon.ID==cpID)){
				isValid = true;
				obj.setAttribute('RedeemedCoupon',gClientCoupons[r].ID);
				obj.setAttribute('CouponValue',gClientCoupons[r].Coupon.CouponValue);
			}
		}
	}
	
	

	
	/*if(!isValid){
		obj.select();
		obj.focus();
		obj.value="";
		alert("You have entered an invalid Coupon Code.  Please try again.");
	}*/
}

function getCouponAmount(obj, nPayTypeNumber)
{
	//find coupon amount field input
	var oTable = jQuery(obj).parents("TABLE")[0];
	
	//var obbj = gEBI("pay_" + nPayTypeNumber + "_total");
	var obbj = jQuery(oTable).find("INPUT");
	if(obbj.length > 0)
		obbj = obbj[obbj.length-1]; //last input
	if(null == obbj)
		return;

	if (obj.value=="") 
		return;
		
	ShowProgressbar(0);
	gFunctionXmlHttpRequestAnisochronousComplite = function(strResp){
		
	}
	
	var strUrl = "getCouponAmountByActivationCode.aspx?ac=" + obj.value;
	$.post(strUrl, "<a>a</a>", function(data){
			var strResp = data;
			
			if("" == strResp || null == strResp)
			{
				ShowProgressbar(1);
				return;
			}
			
			var str=strResp.split(";");

			if (isNaN(str[0]) )
			  str[0]="0";
   			if (isNaN(str[1]) )
			  str[1]="0";
			if (isNaN(str[2]) )
			  str[2]="0";
			obbj.value=str[0];
			obbj.setAttribute("limit",str[0]);
			obbj.setAttribute("qty",str[1]);
			gnCoupon=str[1];
			//alert(str[0]+ "     "+str[1]);
			
			obbj.setAttribute("onchange",function(){ChangeCouponAmount(this);});
			CheckCurrency(obbj.value, obbj); CheckTransactionTotals(obbj);
			// check coupon qty if it is more 0
			
			if (str[1]>0 && isWeb && !isBox){ 
				
				CheckVoucherAndTicket();
				gEBI('patron_id').value= str[2];
				PatronLookUpById(str[2]);
			}
			else
			{
				if (str[1]==0 && isWeb && !isBox)
					gEBI('addressForm').reset();
				ShowProgressbar(1);
			}
			
		});
}

function CheckVoucherAndTicket(){
	var ticketquantity = parseInt(gEBI('h_TicketCounts').value);
	if (!isBox && isWeb){
	  if (parseInt(gnCoupon) > 0 && ticketquantity>parseInt(gnCoupon) ){
			alert("You have ordered more tickets than your voucher allows");
			return false;
		}
	  else  return true;
	}
	else
	 return true;
		

}
function ChangeCouponAmount(pTotal){
    if(parseInt(pTotal.value)>parseInt(pTotal.getAttribute("limit")))
		pTotal.value = pTotal.getAttribute("limit");
}

function GetGASeats()
{
	var oGAQuants = gEBI('GAQuantity');
	var oQuants = getChildrenByPartialIdOrName(oGAQuants, 'gapol', true);
	var Limit = -1;

	var count = 0;

	arrSeatInputs = new Array();

	for(var i=0; i<oQuants.length; i++)
	{
		Limit=-1;
		if(oQuants[i].getAttribute('limit') != null) Limit = parseInt(oQuants[i].getAttribute('limit'));
		if(Limit <= 0 && oQuants[i].value!='' && oQuants[i].value>0 )
		   {
				alert("There are no more seats available, please choose seats for a different section or performance");
				gEBI('txtSeats').value = "";
				return false;
		   } 
		if(parseInt(oQuants[i].value) > 0)
		{
			var lObj = new Object();
			lObj.id = oQuants[i].id;
			lObj.seatid = oQuants[i].getAttribute("seatid");
			lObj.value = oQuants[i].value;
			arrSeatInputs[arrSeatInputs.length] = lObj;
		}
		for(var j=parseInt(oQuants[i].value); j>0; j--)
		{
		   //if past limit break;
		   if(Limit != -1 && count >= Limit)
				break;
		   count++;
		   gEBI('txtSeats').value += oQuants[i].getAttribute('seatid') + "GA" + oQuants[i].getAttribute('ttid') + "GA" + Limit +",";
		}
	}
    if(gEBI('txtSeats').value == "")
	{
		alert("Please Select a total of seats.");
		gEBI('txtSeats').value = "";
		return false;
	}
	
	if(isSeason==1){
		isSeasonGA = true;
		ContinueSeats();
		return false;
	}
	else{
		ShowCartContents();
	}
}

function UpdateTotalForWeb(amount)
{
	if(isWeb&&!isBox)
	{
		//update all trans types totals
		var cnt = 0;
		var oTot = gEBI('pay_' + cnt + '_total');
		do{
			if(oTot != null)
				oTot.value = amount;
			
			cnt++;
			oTot = gEBI('pay_' + cnt + '_total');
		}
		while(oTot != null)
	
		
	}
}

function showEventImage(i){
	if(parseInt(arrEvents[i]['GraphicId'])>0)
		gEBI('tdCal').innerHTML = "<img src='" + arrEvents[i]['GraphicPath'] + "'><br/>" + arrEvents[i]['EventDescription'];
}

function hideEventImage(){
	gEBI('tdCal').innerHTML = "";
}

function lookupEvent(ID){
	for(var e=0;e<Events.length;e++){
		var ev = Events[e];
		if(ev.ID==ID){
			return ev;
		}
	}
}

function lookupPerformance(ID){
	for(var e=0;e<Events.length;e++){
		var ev = Events[e];
		for(var p=0;p<ev.Performances.length;p++){
			var prf = ev.Performances[p];
			if(prf.ID==ID){
				return prf;
			}
		}
	}
}
function runClickTab(intCase)
{
	var xmlData = 
	"<cmds>" +
		"<cmd>" +
		"<fn>clickTab</fn>" +
		"<arg>"+intCase+"</arg>" +
		"<arg>"+arguments[1]+"</arg>" +
		"</cmd>" +
	"</cmds>";

	handleMouseClick("clicktab"+intCase,xmlData,"CallBackSALES");
}
function clickTab(intCase){ //arguments[1] - Delete All From Cart Property
		HideScanTabs();
		if(null != gEBI('divNonOrders')) 
			gEBI('divNonOrders').style.display = 'none';
		if(null != gEBI('divOrders')) 
			gEBI('divOrders').style.display = 'block';
		//hide shopping cart DIVs and OrderConfirmation DIVs
		var oDivCart, oDivConfirm;
		oDivCart = gEBI("divCart");
		oDivConfirm = gEBI("divConfirm");
		
		if(null == oDivCart || null == oDivConfirm)
		{
			//alert("clickTab() 'divCart' or 'divConfirm' not found\r\nPlease call technical support.");
			return false;
		}
		oDivCart.style.display = "none";
		oDivConfirm.style.display = "none";
		//END hide shopping cart DIVs and OrderConfirmation DIVs
		gEBI("ulBestAvailable").style.display = 'none';
		HideLegend();
		gEBI("divSection").style.display = "block";
		gEBI("divSection").innerHTML = "";
		gEBI("divImageMap").style.display = "block";
		
		gEBI("divImageMap").innerHTML = "";
		gEBI('scleftlink').style.display='block';
		if (gEBI('divH')) gEBI('divH').innerHTML = "";
		if(gEBI('tabCalendar'))gEBI('tabCalendar').style.display = 'none';
		
	if(intCase==0){
		isSeason=0;
		if(isBox && null!=gEBI('tabCalendar'))
		{
			gEBI('tabCalendar').style.display = 'block';  // olegc block
		}
		gSeasonLightningSeat=false;
		gPerfs = new Array();
		
		// if set defaut performance
		var dt = new Date(GetCookie(gClientId+"sdy"),GetCookie(gClientId+"sdm"),GetCookie(gClientId+"sdd"),GetCookie(gClientId+"sdh"),GetCookie(gClientId+"sdmin"),GetCookie(gClientId+"sds"));
		if(isBox && null != GetCookie(gClientId+"pid") && null != GetCookie(gClientId+"vid") &&	null != GetCookie(gClientId+"lid") && null != dt && null != GetCookie(gClientId+"eid"))
		{
			var dt = new Date(GetCookie(gClientId+"sdy"),GetCookie(gClientId+"sdm"),GetCookie(gClientId+"sdd"),GetCookie(gClientId+"sdh"),GetCookie(gClientId+"sdmin"),GetCookie(gClientId+"sds"));
			GetSections(GetCookie(gClientId+"pid"),GetCookie(gClientId+"vid"),GetCookie(gClientId+"lid"),gClientId ,dt,"","-1","",0);
			
			Events = new Array();
			Events[0] = new Object();
			Events[0].ID = GetCookie(gClientId+"eid");
			Events[0].Name = "";
			Events[0].Description = "";
			Events[0].Performances = new Array();
			Events[0].Performances[0] = new Object();
			Events[0].Performances[0].ID = GetCookie(gClientId+"pid");
			Events[0].Performances[0].Name = "";
			Events[0].Performances[0].DateTime = new Date();
			Events[0].Performances[0].Event = new Object();
			Events[0].Performances[0].Event.ID = GetCookie(gClientId+"eid");
			Events[0].Performances[0].Event.Venue = new Object();
			Events[0].Performances[0].Event.Venue.ID = GetCookie(gClientId+"vid");
			Events[0].Performances[0].PricingOverlay = new Object();
			Events[0].Performances[0].PricingOverlay.ID = 0;
			Events[0].Performances[0].PricingOverlay.LayoutID = GetCookie(gClientId+"lid");
			gEBI('tdCal').style.display = "none";  
			
			return;
		}
		
		if(isBox) 	 gEBI('tdCal').style.display = "block"; 
		if (null!=gEBI("hHideCalendar") && gEBI("hHideCalendar").value==1)				
			{
				 gEBI('tdCal').style.display = "none"; 
				 gEBI('tdCalendarView').style.display = "none"; 
				 gEBI('tdQuickSaleView').style.display = "none"; 
				 
			 }
				   
		 gEBI('divSingle').style.display = "block"; 
		 gEBI('divMulti').style.display = "none";  
		 gEBI('divDontn').style.display = 'none'; 
		 gEBI('divOther').style.display = "none"; 
		 gEBI("divItems").style.display = "none";
 		 if (null!=gEBI('tdList'))
 		 {
			gEBI('tdList').style.display="block";
			
			}

		if(isWeb&&!isBox && Events.length==0)
		{
			var fspUrl = "FillSelectPerformance.aspx?" + GetRandomQSParam() + "&t=0&for=old"+(arguments[1]!=null?'&'+arguments[1]:'');
			if(sPerformanceParameter != "" && sPerformanceParameter != null)
				fspUrl = "FillSelectPerformance.aspx?" + GetRandomQSParam() + "&t=0&for=old&prfId="+sPerformanceParameter+(arguments[1]!=null?'&'+arguments[1]:'');
			
			$.ajax({
				type: "POST",
				url: fspUrl,
				data: "<a></a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					var strResp = data;
					var oSpan = document.createElement("SPAN");
					oSpan.innerHTML = strResp;
					oSpan=getChildByTagName(oSpan,'span',true);
					var lWords = oSpan.innerHTML.split('<!-- Calendar -->');
					oSpan.innerHTML = lWords[0];
					gEBI('divSingle').innerHTML = "";
					gEBI('divSingle').appendChild(oSpan);
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
			
		}
		if(isBox || 36 == gClientId){
			if("CView" == GetCookie("ShowCal"))
			{	
				runShowCalendarPerformances(0,0);
			}
			else if("QSView" == GetCookie("ShowCal"))
			{
				runShowQuickSale()
			}
			else
			{	
				show_calendar(null,arguments[1]);			
				cal.set();
			}
		}
		if(isWeb&&!isBox && 36 != gClientId)
			fillPerformances();
	}
	else if(intCase==1){
		gEBI('divSingle').style.display = 'none'; 
		gEBI('divMulti').style.display = 'block'; 
		gEBI('divDontn').style.display = 'none'; 
		gEBI('divOther').style.display = 'none';  
		gEBI("divItems").style.display = "none";
		gSeasonRunNumber = null;
		gSeasonRunId = null;
		SetCookie("ShowCal", "", null, "/");
		gQuickSaleMode = false;

		if(SeasonPackages.length==0){
			$.ajax({
				type: "POST",
				url: "FillSelectPerformance.aspx?" + GetRandomQSParam() + "&t=1",
				data: "<a></a>",
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					var strResp = data.split('--BREAK HERE FOR JS--');
					eval(strResp[0]);
					var seasonsHTML = strResp[1];
					
					oParentIDHolder["seasonsHTML"] = seasonsHTML;
					gEBI('divMulti').innerHTML = seasonsHTML;	
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
		}
		else
			gEBI('divMulti').innerHTML = oParentIDHolder["seasonsHTML"]
	}
	else if(intCase==2){
		gEBI('divSingle').style.display = 'none'; 
		gEBI('divMulti').style.display = 'none'; 
		gEBI('divDontn').style.display = 'none'; 
		gEBI('divOther').style.display = 'block'; 
		gEBI("divItems").style.display = "none";
	}
	else if(intCase==3){
		gEBI('divSingle').style.display = 'none'; 
		gEBI('divMulti').style.display = 'none'; 
		gEBI('divDontn').style.display = 'block'; 
		gEBI("divOther").style.display = "none";
		gEBI("divItems").style.display = "none";
	}
	
	var CallBackXMLData = GetCookie("CallBackSALES")
	if(gCallBack && null != CallBackXMLData)
	{	gCallBack = false;
		FunctionFactory(CallBackXMLData);
	}
}

function SeasonPackageList(){
alert("OLD SEASON CALL");
return "";
}

function SeasonPackageList2(){
	var strHTML = "<table id='tblPerformanceList' width='635' border=0>";
	for(var s=0;s<SeasonPackages.length;s++){
		var sp = SeasonPackages[s];
		var fShowGetSeats = 1;
		strHTML += "<tr><td id=\"tdSP" + sp.ID + "\" onclick=\"openTable(" + sp.ID + ");\" onmouseover=\"this.style.color='#ef9900';\" onmouseout=\"this.style.color='#333333';\" style=\"cursor: pointer;font: bold 10pt;\">" + unescape(sp.Name);
		strHTML += "<table id=\"tblSP" + sp.ID + "\" name=\"tblSP\" style=\"display: none;\">";
		var layoutID =-1;
		for(var e=0;e<sp.SeasonEvents.length;e++){
			var se = sp.SeasonEvents[e];
			var ev = lookupEvent(se.Event.ID);
				if(null!=ev){
				var ecCell = "";
				if(sp.EventChoices>0){
					ecCell = "<td align=\"right\"><input onclick=\"getChecked(SeasonPackages[" + s + "],this);\" sevt=\"" + se.ID + "\" type=\"checkbox\" id=\"chk" + sp.ID + "_" + e + "\"></td>";
				}
				strHTML += "<tr>" + ecCell + "<td>" + unescape(ev.Name) + "</td><td>";
				if(se.SeasonPerformances.length==0){
					if(ev.Performances.length==1){
						strHTML += ShortDate(ev.Performances[0].DateTime) + " " + ShortTime(ev.Performances[0].DateTime);
						strHTML += "<input type=\"hidden\" name=\"hPerf" + sp.ID + "\" id=\"hPerf" + sp.ID + "_" + se.ID + "\" value=\"" + ev.Performances[0].ID + "\" layout=\"" + ev.Performances[0].PricingOverlay.LayoutID + "\" venue=\"" + ev.Performances[0].Event.Venue.ID + "\"  evt=\"" + ev.ID + "\" datetime=\"" + ev.Performances[0].DateTime + "\" PerformanceName=\"" + ev.Name + "\">";
						
					}
					else{
						strHTML += "<input type=\"hidden\" name=\"hPerf" + sp.ID + "\" id=\"hPerf" + sp.ID + "_" + se.ID + "\" value=\"" + ev.Performances[0].ID + "\" layout=\"" + ev.Performances[0].PricingOverlay.LayoutID + "\" venue=\"" + ev.Performances[0].Event.Venue.ID + "\"  evt=\"" + ev.ID + "\" datetime=\"" + ev.Performances[0].DateTime + "\" PerformanceName=\"" + ev.Name + "\">";
						strHTML += "<select onchange=\"gEBI('hPerf" + sp.ID + "_" + se.ID + "').value=this.value;gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('layout',this.options[this.selectedIndex].getAttribute('layout'));gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('venue',this.options[this.selectedIndex].getAttribute('venue'));gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('datetime',this.options[this.selectedIndex].getAttribute('datetime'));gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('PerformanceName',this.options[this.selectedIndex].getAttribute('PerformanceName'));\">";
						for(var p=0;p<ev.Performances.length;p++){
							strHTML += "<option value=\"" + ev.Performances[p].ID + "\" layout=\"" + ev.Performances[p].PricingOverlay.LayoutID + "\" venue=\"" + ev.Performances[p].Event.Venue.ID + "\" datetime=\"" + ev.Performances[p].DateTime + "\" PerformanceName=\"" + ev.Name + "\">" + ShortDate(ev.Performances[p].DateTime) + " " + ShortTime(ev.Performances[p].DateTime) + "</option>";
						}
						strHTML += "</select>";
					}
					if(layoutID == -1 ) 
							layoutID = ev.Performances[0].PricingOverlay.LayoutID;
					else if(layoutID != ev.Performances[0].PricingOverlay.LayoutID && fShowGetSeats == 1)
							fShowGetSeats = 0;

				}
				else if(se.SeasonPerformances.length==1){
					fShowGetSeats = 0;
					var prf = lookupPerformance(se.SeasonPerformances[0].Performance.ID);
					strHTML += ShortDate(prf.DateTime) + " " + ShortTime(prf.DateTime);
					strHTML += "<input type=\"hidden\" name=\"hPerf" + sp.ID + "\" id=\"hPerf" + sp.ID + "_" + se.ID + "\" value=\"" + prf.ID + "\" layout=\"" + prf.PricingOverlay.LayoutID + "\" venue=\"" + prf.Event.Venue.ID + "\"  evt=\"" + ev.ID + "\" datetime=\"" + prf.DateTime + "\" PerformanceName=\"" + ev.Name + "\">";
				}
				else{
					if(layoutID == -1 ) 
							layoutID = ev.Performances[0].PricingOverlay.LayoutID;
						else if(layoutID != ev.Performances[0].PricingOverlay.LayoutID && fShowGetSeats == 1)
								fShowGetSeats = 0;
						
					strHTML += "<input type=\"hidden\" name=\"hPerf" + sp.ID + "\" id=\"hPerf" + sp.ID + "_" + se.ID + "\" value=\"" + ev.Performances[0].ID + "\" layout=\"" + ev.Performances[0].PricingOverlay.LayoutID + "\" venue=\"" + ev.Performances[0].Event.Venue.ID + "\"  evt=\"" + ev.ID + "\" datetime=\"" + ev.Performances[0].DateTime + "\" PerformanceName=\"" + ev.Name + "\">";
					strHTML += "<select onchange=\"gEBI('hPerf" + sp.ID + "_" + se.ID + "').value=this.value;gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('layout',this.options[this.selectedIndex].getAttribute('layout'));gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('venue',this.options[this.selectedIndex].getAttribute('venue'));gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('datetime',this.options[this.selectedIndex].getAttribute('datetime'));gEBI('hPerf" + sp.ID + "_" + se.ID + "').setAttribute('PerformanceName',this.options[this.selectedIndex].getAttribute('PerformanceName'));\">";
					for(var p=0;p<se.SeasonPerformances.length;p++){
						var prf = lookupPerformance(se.SeasonPerformances[p].Performance.ID);
						strHTML += "<option value=\"" + prf.ID + "\" layout=\"" + prf.PricingOverlay.LayoutID + "\" venue=\"" + prf.Event.Venue.ID + "\" datetime=\"" + prf.DateTime + "\" PerformanceName=\"" + prf.Name + "\">" + ShortDate(prf.DateTime) + " " + ShortTime(prf.DateTime) + "</option>";
					}
					strHTML += "</select>";
				}
				strHTML += "</td><td id=\"tdSeats" + se.ID + "\"></td></tr>";
			}
		}
		var colspan = (ecCell.length>0)?"3":"2";

		if(fShowGetSeats == 0)
			strHTML += "<tr><td align=\"center\" colspan=\"" + colspan + "\"><button title='Get Seats' onclick=\"ViewSeats(SeasonPackages[" + s + "], this, 'multy');\"><img src='images/tortoise.gif'></img></button></td></tr>";
		else
			strHTML += "<tr><td align=\"center\" colspan=\"" + colspan + "\"><button title='Get Seats' onclick=\"ViewSeats(SeasonPackages[" + s + "], this);\"><img src='images/lightning.gif'></img></button><button title='Get Seats' onclick=\"ViewSeats(SeasonPackages[" + s + "], this, 'multy');\"><img src='images/tortoise.gif'></img></button></td></tr>";
		
		strHTML += "</table>";
		strHTML += "</td></tr>";
		
	}
	strHTML += "</table>";
	return strHTML;
}

function openTable(spID, hasPriceDist, decSingleReturn){
	gSeasonPackageId = spID;
	gSeasonPackageHasPriceDistributions = hasPriceDist;
	gSeasonPackageDecrementSingle = decSingleReturn;
	
	var arrTBL = gEBN('tblSP');
	if(arrTBL.length==0){
		arrTBL = new Array();
		var aT = document.getElementsByTagName("TABLE");
		for(var t=0;t<aT.length;t++){
			if(aT[t].id.indexOf("tblSP")>-1)
				arrTBL[arrTBL.length] = aT[t];
		}
	}
	for(var a=0;a<arrTBL.length;a++){
		arrTBL[a].style.display = 'none';
	}

	var oSPTable = gEBI('tblSP' + spID);
	if(null == oSPTable)
		return;
	oSPTable.style.display = 'block';
	
	//check for auto select for season run
	if(gSeasonRunNumber != null)
	{
		var oEventSelects = getChildrenByPartialIdOrName(oSPTable, "sp_PerformanceSelect", true);
		if(oEventSelects != null && oEventSelects.length > 0)
		{
			if(gSeasonRunNumber > oEventSelects[0].length)
				gSeasonRunNumber = oEventSelects[0].length - 1;
			oEventSelects[0].selectedIndex = gSeasonRunNumber;
			oEventSelects[0].onchange();
			
			//disable all lists
			for(var j=0; j<oEventSelects.length; j++)
			{
				oEventSelects[j].disabled = true;
				oEventSelects[j].style.fontWeight = "bold";
				oEventSelects[j].nextSibling.innerHTML = "";
			}
		}
	}
	
	
}

function userNavOnModeChange(oModeSelect)
{
   
	var bIsAgencyMode = (oModeSelect[oModeSelect.selectedIndex].getAttribute("isAgency") == "true")?true:false;
	
	if(!bIsAgencyMode)
	{
		window.location='SelectPerformance.aspx?mid='+oModeSelect.value;
		return;
	}
	else
	{
		//display available agencies
			var strSelectXML = "<envelope><body>" + 
						"<command name=\"Populate\">" + 
						"<class name=\"" + 'Agencys' + "\" />";
	
		strSelectXML += "<param type=\"" + 'Client' + "\">" + 
						"<Client><ID>" + gClientId + "</ID></Client>" + 
						"</param>" +
						"</command>" + 
						"<xslt>UserLeftNav.xslt</xslt>" + 
						"</body></envelope>";
	
		
		$.post(gSOAPListenerURL, strSelectXML, function(data){
			
			var strResp = data;
			
			var oSpan = document.createElement("SPAN");
			oSpan.id = "userLeftNavModeAgency";
			oSpan.innerHTML = strResp;
			oModeSelect.parentNode.appendChild(oSpan);
		});
		
	}
}

function userNavOnModeAgencyChange(oAgencySelect)
{
	var modeId = gEBI("UserModeSelect").value
	var strUrl = "SelectPerformance.aspx?mid=" + modeId + "&agid=" + oAgencySelect.value;
	$.post(strUrl, "<a>a</a>");
}

function setFocus(fldID){
	document.getElementById(fldID).focus();

} 
function clickCategory(oLink,isMember,viewCategory)
{
		var CategoryId=oLink;
		var iItemId;
		if("undefined" != typeof(arguments[2]))
		   iItemId = arguments[2];
		 else
		  iItemId=0;  
		
		var strXML = "<Envelope><Body><Category><ID>" + CategoryId + "</ID><isMember>" + isMember.toLowerCase() + "</isMember><ViewCategory>"+viewCategory+"</ViewCategory></Category>";
		    strXML += "<Item><ID>"+iItemId+"</ID></Item>";
	    strXML += "</Body></Envelope>";
	    
		$("#hCategory").val(CategoryId);
		     
		var strResp = null;
		var strUrl = "SelectItem.aspx?ubegin=" + $("#Begin").val();
		$.ajax({
				type: "POST",
				url: strUrl,
				data: strXML,
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
		
		if ( null!=gEBI("divItems") && null!=strResp )
		{ 
			$("#divItems").html(strResp);

   		   if (iItemId==0 && null!=gEBI("ItemsResult"))  
			{
			   $("#ItemsResult").show();
			   makeDivPagesI();
			}
		   else
				$("#ItemsResult").hide();

			
		   if (null!=gEBI("tblPerformanceList"))
			  gEBI("tblPerformanceList").style.display = 'none';
		   if (null!=gEBI("divNonOrders"))
		      gEBI('divNonOrders').style.display = 'none';
		   if (null!=gEBI("divItems"))
		      gEBI('divItems').style.display = 'block';
		   if (null!=gEBI("tdList"))
		      gEBI('tdList').style.display='none';
		   if (null!=gEBI("ShowListPerf"))
		      gEBI("ShowListPerf").style.display='none';
		   var oDivCart, oDivConfirm;
   		   oDivCart = gEBI("divCart");
		   oDivConfirm = gEBI("divConfirm");

		   if (null!=oDivCart )	
		      oDivCart.style.display = "none";
		   if (null!=oDivConfirm ) 
		      oDivConfirm.style.display = "none";  
		   if(null!=gEBI('tabCalendar'))gEBI('tabCalendar').style.display = 'none';   
			
		      
// 	   gEBI('divSingle').style.display = 'none'; 
		if (null!=gEBI('divMulti'))
			gEBI('divMulti').style.display = 'none'; 
		if (null!=gEBI('divDontn'))
			gEBI('divDontn').style.display = 'none'; 
		if (null!=gEBI('divOther'))
			gEBI('divOther').style.display = 'none';  
	//		gEBI("divItems").style.display = "none";
			if (CategoryId==0){
				setTimeout("document.getElementById('ed"+iItemId+"').focus()", 40); 
			}


		}

}
function myne(iItemId)
{
    
	document.getElementById('edolegc'+iItemId).value=gEBI("divItems").innerHTML;
	document.getElementById('edolegc'+iItemId).focus();
}

//UserControls.js
function InvertObjectVisibility(obj, strShow)
{
	if(arguments[1] != null)
	{
		obj.style.display = strShow;
		return;
	}
	
	obj.style.display = obj.style.display=='none'?'':'none';
}

/*
*
Formats DateTime string in form : 2004-10-31T16:00:00.0000000-06:00
to fit our datetime validation form: 01/04/2005 10:00:00 AM
args:
sLongDate - date in XML format
mode - (optional) 
	not supplied - to return date and time, 
	true - to return date, 
	false - to return time
*
*/
function XMLStringToDate(sLongDate)
{
	var mode = 0;
	if(typeof(arguments[1]) != "undefined")
		mode = arguments[1]?1:2;

	var GMThr = parseInt(sLongDate.substring(11,13));
	var GMTmin = parseInt(sLongDate.substring(14,16));
	var GMTsec = parseInt(sLongDate.substring(17,19));
	var LOChr = parseInt(sLongDate.substring(28,30));
	var LOCmin = parseInt(sLongDate.substr(31));
	var sDay = sLongDate.substring(8,10);
	//alert ("sDay"+sDay)
	var sMonth = sLongDate.substring(5,7);
	var sYear = sLongDate.substring(0,4);
	//alert("sYear"+sYear);

	var dt = new Date(sMonth + "/" + sDay + "/" + sYear);
	
	dt.setHours(GMThr);
	dt.setMinutes(GMTmin);
	dt.setSeconds(GMTsec);
	
	/*if(sLongDate.substring(27,28)=='-'){
		LOChr = 0 - LOChr;
		LOCmin = 0 - LOCmin;
	}
	dt.setHours(dt.getHours() + LOChr);
	dt.setMinutes(dt.getMinutes() + LOCmin);*/
	
	
	var strAMPM = 'AM';
	
	H = dt.getHours();
	
	if(H>11){
		strAMPM = 'PM';
	}
	H = H % 12;
	if(H==0){
		H = 12;
	}
	H = PadInFront(H,2);
	M = PadInFront(dt.getMinutes(),2);
	S = PadInFront(dt.getSeconds(),2);

	var sDate = PadInFront((dt.getMonth() + 1),2) + "/" + PadInFront(dt.getDate(),2) + "/" + dt.getFullYear();
	
	var strTime = H + ":" + M + ":" + S + " " + strAMPM;
	
	var sReturnDateTime = sDate + " " + strTime;
	
	switch(mode)
	{
		case 0: //DateTime
			return sReturnDateTime;
			break;
		case 1: //Date
			return sDate;
			break;
		case 2: //Time
			return strTime;
			break;
		default:
			return sReturnDateTime;
			break;
	}
}

function DateToXMLString(dt, bConvertTime, bToGMT)
{
	bConvertTime = (arguments[1] == null)?true:bConvertTime;
	bToGMT = (arguments[2] == null)?true:bToGMT;
	
	var yr, dy, mon, hrs, mins, secs, offset;
	if(bToGMT){
		yr = dt.getUTCFullYear();
		mon = dt.getUTCMonth() + 1;
		dy = dt.getUTCDate();
		hrs = dt.getUTCHours();
		mins = dt.getUTCMinutes();
		secs = dt.getUTCSeconds();
		offset = dt.getTimezoneOffset();
	}
	else{
		yr = dt.getFullYear();
		mon = dt.getMonth() + 1;
		dy = dt.getDate();
		hrs = dt.getHours();
		mins = dt.getMinutes();
		secs = dt.getSeconds();
		offset = dt.getTimezoneOffset();
	}

	if(!bConvertTime)
		offset = 0;
	
	var strYr, strDy, strMon, strHours, strMins, strSecs, strOffset;
	strYr = PadInFront(yr, 4);
	strMon = PadInFront(mon, 2);
	strDy = PadInFront(dy, 2);
	strHours = PadInFront(hrs, 2);
	strMins = PadInFront(mins, 2);
	strSecs = PadInFront(secs, 2);
	
	var nOffsetHours, nOffsetMinutes, strOffsetSign;
	nOffsetMinutes = offset % 60;
	nOffsetHours = (offset - nOffsetMinutes) / 60;
	
	//find out if we are ahead or behind UTC
	if(nOffsetHours > 0)
		strOffsetSign = "-";
	else
		strOffsetSign = "+";
		
	//Remove Sign
	nOffsetMinutes = Math.abs(nOffsetMinutes);
	nOffsetHours = Math.abs(nOffsetHours);
	
	strOffset = strOffsetSign + PadInFront(nOffsetHours, 2) + PadInFront(nOffsetMinutes, 2);
	
	//assemble the string
	return strYr + "-" + strMon + "-" + strDy + "T" + strHours + ":" + strMins + ":" + strSecs + ".0000000";// + strOffset; //.NET 2 version
	
	//return strYr + "-" + strMon + "-" + strDy + "T" + strHours +  ":" + strMins + ":" + strSecs + ".0000000" + strOffset;
}

function PadInFront(Val, nZeroes)
{
	retVal = "" + Val; //convert to string
	while(retVal.length < nZeroes)
		retVal = "0" + retVal;
		
	return retVal;
}


/*
* Shows Please, Wait... message in a DIV
*/
function ShowPleaseWaitMessage(oDIV)
{
	if(null == oDIV)
		return;
	
	oDIV.innerHTML = "<DIV align=center>"+GetTranslation("Please_wait")+"</DIV>";
}

/*mFormat: Format of month { 0 - Jan ; 1 - January; 2 - J*/
function LongDate(dt, mFormat){
	if(mFormat == null)
		mFormat = 0;
	var MonthsArray = new Array(new Array('Jan','January','J'),new Array('Feb','February','F'),new Array('Mar','March','M'),new Array('Apr','April','A'),new Array('May','May','M'),new Array('Jun','June','J'),new Array('Jul','July','J'),new Array('Aug','August','A'),new Array('Sep','September','S'),new Array('Oct','October','O'),new Array('Nov','November','N'),new Array('Dec','December','D'));
	var DayArray = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');	
	var day = dt.getDate();
	return String(GetTranslation(DayArray[dt.getDay()]+"_full",DayArray[dt.getDay()])  +", " +GetTranslation(MonthsArray[dt.getMonth()][mFormat]) + " " + day + ", "+ dt.getFullYear());
}

function ShortTime(dt){
/*
	var H = dt.getHours();
	var M = dt.getMinutes();
	var strAMPM = 'AM';
	if(H>11){
		strAMPM = 'PM';
	}
	H = H % 12;
	if(H==0){
		H = 12;
	}
	//H = PadInFront(H,2);
	M = PadInFront(M,2);
	return String(H + ":" + M + " " + strAMPM);*/
	var str=dt.toLocaleTimeString( );
	var counter=0;
	for(var i=0;i<str.length;i++)
	{
	if(str.charAt(i)==':')
		{
		counter++;
		if(counter==2)
			{
			str=str.substr(0,i)+str.substr(i+3,str.length-i-3);
			break;
			}
		}
	}
	return str;
}
//END UserControls.js

//CouponSell.js
gOrder["CouponOrders"] = new Array();
gOrder["CouponOrdersXML"] = "";
gOrder["CouponPackageOrders"] = new Array();
gOrder["CouponPackageOrdersXML"] = "";
gOrder["ItemOrders"] = new Array();
gOrder["ItemOrdersXML"] = "";

function checkDonation(oThis,hItemOrder,ItemID)
{
	if(isNaN(parseFloat(oThis.value)) || parseFloat(oThis.value) < 0)
	{
		oThis.value = hItemOrder.getAttribute('ListPrice');
		return;
	}
	oThis.value = parseFloat(oThis.value).toFixed(2);
	hItemOrder.setAttribute('ListPrice',oThis.value);
	for (i=0;i<arrItems.length;i++)
	{
		if (typeof(arrItems[i])!="undefined" && arrItems[i]!=null && arrItems[i]["ID"]==ItemID)
		{
			arrItems[i]["Price"] = oThis.value;
		}
	}
	updateTotals();
}
function AddCoupons_ItemsToCart(){
	HideScanTabs();
	gEBI('divNonOrders').style.display = 'block';
	gOrder["CouponOrders"] = gEBN('txtCoupons');
	gOrder["CouponPackageOrders"] = gEBN('txtCouponPackages');
	gOrder["ItemOrders"] = gEBN('txtItems');
	gOrder["DonationOrders"] = gEBN('txtDonations');
	
	gOrder["CouponOrdersXML"] = '<CouponOrders>';
	for(var i=0;i<gOrder["CouponOrders"].length;i++){
		if((parseInt(gOrder["CouponOrders"][i].getAttribute("CouponTypeId"))==2)&&(parseFloat(gOrder["CouponOrders"][i].value)>0)){
			gOrder["CouponOrdersXML"] += '<CouponOrder><Coupon><ID>' + gOrder["CouponOrders"][i].getAttribute('ObjectId') + '</ID><CouponName>' + gOrder["CouponOrders"][i].getAttribute('displayText') + '</CouponName><IsShortCode>' + gOrder["CouponOrders"][i].getAttribute('IsShortCode') + '</IsShortCode><CouponValue>' + gOrder["CouponOrders"][i].value + '</CouponValue><ListPrice>' + gOrder["CouponOrders"][i].value + '</ListPrice><CouponType><ID>' + gOrder["CouponOrders"][i].getAttribute('CouponTypeId') + '</ID></CouponType></Coupon><Quantity>1</Quantity></CouponOrder>';
		}
		else if(parseInt(gOrder["CouponOrders"][i].value)>0){
			gOrder["CouponOrdersXML"] += '<CouponOrder><Coupon><ID>' + gOrder["CouponOrders"][i].getAttribute('ObjectId') + '</ID><CouponName>' + gOrder["CouponOrders"][i].getAttribute('displayText') + '</CouponName><IsShortCode>' + gOrder["CouponOrders"][i].getAttribute('IsShortCode') + '</IsShortCode><CouponValue>' + gOrder["CouponOrders"][i].getAttribute('CouponValue') + '</CouponValue><ListPrice>' + gOrder["CouponOrders"][i].getAttribute('ListPrice') + '</ListPrice><CouponType><ID>' + gOrder["CouponOrders"][i].getAttribute('CouponTypeId') + '</ID></CouponType></Coupon><Quantity>' + gOrder["CouponOrders"][i].value + '</Quantity></CouponOrder>';
		}
	}
	gOrder["CouponOrdersXML"] += '</CouponOrders>';
	
	gOrder["CouponPackageOrdersXML"] = '<CouponPackageOrders>';
	for(var i=0;i<gOrder["CouponPackageOrders"].length;i++){
		if(parseInt(gOrder["CouponPackageOrders"][i].value)>0)
			gOrder["CouponPackageOrdersXML"] += '<CouponPackageOrder><CouponPackage><ID>' + gOrder["CouponPackageOrders"][i].getAttribute('ObjectId') + '</ID><CouponPackageName>' + gOrder["CouponPackageOrders"][i].getAttribute('displayText') + '</CouponPackageName><PackagePrice>' + gOrder["CouponPackageOrders"][i].getAttribute('PackagePrice') + '</PackagePrice></CouponPackage><Quantity>' + gOrder["CouponPackageOrders"][i].value + '</Quantity></CouponPackageOrder>';
	}
	gOrder["CouponPackageOrdersXML"] += '</CouponPackageOrders>';
	
	gOrder["ItemOrdersXML"] = '<ItemOrders>';
	
	for(var i=0;i<gOrder["ItemOrders"].length;i++){
	
		if(parseInt(gOrder["ItemOrders"][i].value)>0)
		 {	//gOrder["ItemOrdersXML"] += '<ItemOrder><Item><ID>' + gOrder["ItemOrders"][i].getAttribute('ObjectId') + '</ID><Name>' + gOrder["ItemOrders"][i].getAttribute('displayText') + '</Name><ListPrice>' + gOrder["ItemOrders"][i].getAttribute('ListPrice') + '</ListPrice></Item><Quantity>' + gOrder["ItemOrders"][i].value + '</Quantity></ItemOrder>';
			addItemToBasket( parseInt(gOrder["ItemOrders"][i].getAttribute('ObjectId')),gOrder["ItemOrders"][i].getAttribute('displayText'),parseFloat(gOrder["ItemOrders"][i].getAttribute('ListPrice')),gOrder["ItemOrders"][i].getAttribute('IsMembership'),gOrder["ItemOrders"][i].getAttribute('CanSellWithPoints'),gOrder["ItemOrders"][i].getAttribute('Points'),gOrder["ItemOrders"][i].getAttribute('isMemberCategory'),parseInt(gOrder["ItemOrders"][i].value));
  			gOrder["ItemOrders"][i].value=0;
		 }	
	
	}
	
	var chDonations = gEBN('chDonations');
	for(var i=0;i<chDonations.length;i++){
		if(null != gOrder["DonationOrders"][i])
		{	
		 if(chDonations[i].checked)
		  {	
			addItemToBasket( parseInt(gOrder["DonationOrders"][i].getAttribute('ObjectId')),gOrder["DonationOrders"][i].getAttribute('displayText'),parseFloat(gOrder["DonationOrders"][i].value),gOrder["DonationOrders"][i].getAttribute('IsMembership'),gOrder["DonationOrders"][i].getAttribute('CanSellWithPoints'),gOrder["DonationOrders"][i].getAttribute('Points'),gOrder["DonationOrders"][i].getAttribute('isMemberCategory'),parseInt(1),null,gOrder["DonationOrders"][i].getAttribute('CategoryType'));
			chDonations[i].checked = false;
		  }	
		 //gOrder["DonationOrders"][i].value = gOrder["DonationOrders"][i].getAttribute("BaseValue");
		}
	
	}
	for(var i=0;i<arrItems.length;i++)
	 {if (null!=arrItems[i] && null!=arrItems[i]["Price"])
		{ 
            gOrder["ItemOrdersXML"] +="<ItemOrder><Item><ID>" + arrItems[i]["ID"] + "</ID><Name>" + arrItems[i]["Name"] + "</Name><Repeat>false</Repeat>"+"<IsMembership>"+arrItems[i]["IsMembership"]+"</IsMembership>";
            gOrder["ItemOrdersXML"] +="<Points>"+arrItems[i]["Points"]+"</Points>"
            gOrder["ItemOrdersXML"] +="<CanSellWithPoints>"+arrItems[i]["CanSellWithPoints"]+"</CanSellWithPoints>"
            gOrder["ItemOrdersXML"] +="<Category><isMember>"+arrItems[i]["isMemberCategory"]+"</isMember><CategoryType>"+arrItems[i]["CategoryType"]+"</CategoryType></Category>"
            gOrder["ItemOrdersXML"] +="<ListPrice>"+ FormatCurrency(arrItems[i]["Price"],2) + "</ListPrice></Item><Quantity>" + arrItems[i]["Qty"] + "</Quantity></ItemOrder>";
	    } 
     }

	gOrder["ItemOrdersXML"] += '</ItemOrders>';
   	arrItems = new Array();
	strSoapMessage = '<Envelope><Body><Order>' + gOrder["CouponOrdersXML"] + gOrder["CouponPackageOrdersXML"] + gOrder["ItemOrdersXML"] + '</Order></Body></Envelope>';

	gOrder["CouponOrdersXML"]="";
	gOrder["CouponPackageOrdersXML"]="";
	gOrder["ItemOrdersXML"]="";
	
	//hide all DIVs except cart page
	gEBI("divCart").style.display = "block";
	gEBI('divPayCart').style.display='inline';
	
	$("#divSection").hide();
	$("#divImageMap").hide();
	$("#divOrders").hide();
	$("#divItems").hide();
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: gShoppingCartURL,
				data: strSoapMessage,
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	CartInner(strResp);
	
	window.setTimeout(function(){ PayCartComplite();updateTotals();}, 100);
}

function setDefaultPaymentType()
{
	if (null!=gEBI("paymentmethodUniqueId"))
	 {
	    var obj=gEBI(gEBI("paymentmethodUniqueId").value);	
	    for(var i = 0; i<obj.options.length; i++)
	    {
	    if (null!=obj.options[i].getAttribute("PaymenttypesClientId") && null!=obj.options[i].getAttribute("DefaultPaymentTypeId"))
	       if ( obj.options[i].getAttribute("PaymenttypesClientId")==obj.options[i].getAttribute("DefaultPaymentTypeId")
	            && obj.options[i].getAttribute("DefaultPaymentTypeId")>0
	          )
			   { 
			     obj.selectedIndex=i;
			     AddPaymentType(obj.options[i].value,obj);
			     obj.options[i].setAttribute("DefaultPaymentTypeId","");
			   }
			  
	    }
	 }
}
function addOneItemToBasket(itemID)
{
	var str="<Envelope>";
	str+="<Body>";
	str+="<Order>";
	str+="<CouponOrders/>";
	str+="<CouponPackageOrders/>";
	str+="<ItemOrders>";
	str+="<ItemOrder>";
	str+="<Item>";
	str+="<ID>"+itemID+"</ID>";
	str+="<Repeat>false</Repeat>";
	str+="</Item>";
	str+="<Quantity>1</Quantity>";
	str+="</ItemOrder>";
	str+="</ItemOrders>";
	str+="</Order>";
	str+="</Body>";
	str+="</Envelope>";
	
	var strResp = "";
	$.ajax({
				type: "POST",
				url: gShoppingCartURL,
				data: str,
				async: false, 
				contentType: "text/xml; charset=utf-8",
				dataType: "text",
				success: function(data, textStatus) {
					strResp = data;
					return false;
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("error = " + XMLHttpRequest.responseText);
					return false;
				}
			});
	
	CartInner(strResp);
	window.setTimeout(function(){ PayCartComplite();updateTotals();}, 100);
}

function AddRemoveSingleItem(obj,ID,Name,ListPrice,IsMembership,CanSellWithPoints,Points,isMemberCategory){
  if (obj.checked){
	addItemToBasket(ID,Name,ListPrice,IsMembership,CanSellWithPoints,Points,isMemberCategory,1);
	}
  else{
		for (var i=0;i<arrItems.length;i++){
            if (typeof(arrItems[i])!="undefined"){
               if (arrItems[i]!=null && arrItems[i]["ID"]==ID){ 
                  arrItems[i]=null;
                 }
              }
         }
      }
}

function addItemToBasket()
{
  var itemID,itemName,itemPrice,isMemberShip,CanSellWithPoints,Points,isMemberCategory,Qty,isRetail,CategoryType;
  var tempObj = new Object()
  if("undefined" != typeof(arguments[0]))
     itemID=arguments[0];
  if("undefined" != typeof(arguments[1]))
     itemName=arguments[1];
  if("undefined" != typeof(arguments[2]))
     itemPrice=arguments[2];
  
   if("undefined" != typeof(arguments[3]))
		isMemberShip=arguments[3]
    else
		isMemberShip='false';

   if("undefined" != typeof(arguments[4]))
		CanSellWithPoints=arguments[4] 
    else
		CanSellWithPoints='false'; 
		
   if("undefined" != typeof(arguments[5]))
		Points=arguments[5]
    else
		Points=0;
  

   if("undefined" != typeof(arguments[6]))
		isMemberCategory=arguments[6]
   else
      isMemberCategory='false';
              
  if("undefined" != typeof(arguments[7]))
	Qty=arguments[7]
  else
	Qty=gEBI("ed"+itemID).value; 

  if ("undefined" != typeof(arguments[8]) && null!=arguments[8])
      isRetail=arguments[8]
  else
      isRetail=0;
  if ("undefined" != typeof(arguments[9]) && null!=arguments[9])
      CategoryType=arguments[9]
  else
      CategoryType=1;
          
  if (typeof( arrItems[itemID]=="undefined"))
     arrItems[itemID]=null; 
     
  if ( arrItems[itemID]!=null) 
   { 
		if (itemID== arrItems[itemID]["ID"])
		{  
			if (isRetail==0)
				arrItems[itemID]["Qty"]=  parseInt(arrItems[itemID]["Qty"])+parseInt(Qty); 
			else
				arrItems[itemID]["Qty"]=  parseInt(Qty); 
		}
   }
   else
   {   
    tempObj["ID"]=itemID;
    tempObj["Name"]=itemName;   
    tempObj["Price"]=itemPrice;
    tempObj["Qty"]=parseInt(Qty);
    tempObj["IsMembership"]=isMemberShip;
    tempObj["Points"]=Points;
    tempObj["CanSellWithPoints"]=CanSellWithPoints;
    tempObj["isMemberCategory"]=isMemberCategory;
    tempObj["CategoryType"]=CategoryType;
    arrItems[itemID]= tempObj;
     
    }
  //AddCoupons_ItemsToCart();
  //updateTotalItems();


 
}

function updateTotalItems()
{
  var tCount=0
  var tAmount=0; 
  var sCount=0
  var amountAmount=0; 
  
  if("undefined" != typeof(arguments[0]))
      tCount=arguments[0];
  if("undefined" != typeof(arguments[1]))
      tAmount=arguments[1];
  if("undefined" != typeof(arguments[2]))
      sCount=arguments[2];
  if("undefined" != typeof(arguments[3]))
      amountAmount=arguments[3];

  var  itemsCount=0;
  var  itemsAmount=0;
  for(var i=0;i<arrItems.length;i++)
	{
		if (null == arrItems[i])
			continue; 
		
		//itemsCount += parseInt(arrItems[i]["Qty"]);
		//itemsAmount += itemsCount*parseFloat(arrItems[i]["Price"]);
		
		itemsCount += parseInt(arrItems[i]["nTixQty"]);
		itemsAmount += itemsCount*parseFloat(arrItems[i]["nBaseAmount"]);
	}
	   
  var wasPaid=0;
  if ( null!=gEBI('txtWasPaid') )
    wasPaid=parseFloat(gEBI('txtWasPaid').value);
  var grandTotal=0;
  if ( null!=gEBI('txtTotal') )
    grandTotal=parseFloat(gEBI('txtTotal').value);
    
  
  gEBI("itemsCount").innerHTML=itemsCount+" "+GetTranslation("Items");
  gEBI("ticketCount").innerHTML=tCount + " "+GetTranslation("Tickets1");
  gEBI("SeasonCount").innerHTML=sCount + " "+GetTranslation("SeasonTickets");
  gEBI("itemsAmount").innerHTML=GetTranslation("subtotal")+" $ "+FormatCurrency(grandTotal,2);
  //FormatCurrency(itemsAmount+parseFloat(tAmount)+parseFloat(amountAmount)- wasPaid,2);
  //alert(itemsCount+GetTranslation("Items"));
  //alert(GetTranslation("SubTotal")+"_$ "+FormatCurrency(itemsAmount+parseFloat(tAmount)+parseFloat(amountAmount),2));
   if (itemsCount<=0)
    gEBI("itemsCount").style.display="none";
  else
    gEBI("itemsCount").style.display="block";

  if (tCount<=0)
    gEBI("ticketCount").style.display="none";
  else
   { gEBI("ticketCount").style.display="block";
  
   }  
  if (sCount<=0)
    gEBI("SeasonCount").style.display="none";
  else
    gEBI("SeasonCount").style.display="block";
  
  if (FormatCurrency(itemsAmount+parseFloat(tAmount)+parseFloat(amountAmount),2)<=0)
    gEBI("itemsAmount").style.display="none";
  else
    gEBI("itemsAmount").style.display="block";

}

function b_onkeypress()
{
 
 if ((event.keyCode<48)  || (event.keyCode>57))
 {  return false;}
}

function ChangeCountTicketsPerEvent(pTextBox)
{
	var lEvtID = pTextBox.getAttribute("EventID");
	var lArrTxtTicketDiscount = gEBN("txtTicketDiscount"+lEvtID);
	if(0 == lArrTxtTicketDiscount.length) return;
	
	var lOldCountTix = Number(pTextBox.getAttribute("QuantityF"));
	var lCountTix = Number(pTextBox.value);

	var lCntTicketsPerEvent = Number(lArrTxtTicketDiscount[0].getAttribute("cntTicketsPerEvent"))+(lCountTix-lOldCountTix);
	for(var i=0; i<lArrTxtTicketDiscount.length; i++)
	{
		lArrTxtTicketDiscount[i].setAttribute("cntTicketsPerEvent", lCntTicketsPerEvent);
	}
}
function AddGATicketsToSession(pTextBox)
{
	var strRequestXML = "<envelope><body><command name=\"AddGATicketsToSession\"><class name=\"Tickets\"/>"+
		"<param type=\"Ticket\">"+//pTicket
		"<Ticket QuantityF='"+pTextBox.getAttribute("QuantityF")+"'>"+
			"<ID>" + pTextBox.getAttribute("TicketId") + "</ID>"+
			"<Performance><ID>" + pTextBox.getAttribute("PerformanceID") + "</ID></Performance>"+
			"<TicketType><ID>"+pTextBox.getAttribute("TicketTypeID")+"</ID></TicketType>"+
			"<POLevel><ID>"+pTextBox.getAttribute("POLevelID")+"</ID></POLevel>"+
		"</Ticket></param>"+
		"<param type=\"System.Int32\"><int>"+pTextBox.value+"</int></param>"+//pCountTix
		"</command><xslt>ShoppingCart.xslt</xslt></body></envelope>";
	pTextBox.setAttribute("QuantityF",pTextBox.value);
	
	$.post(gSOAPListenerURL, strRequestXML);
}

function Barcode (obj,e)
{
	if(!e) 
		e = window.event; 
	if(e.keyCode==13)
	{
		var strSoapMessage = '<Envelope><Body><Item><BarCode>'+obj.value+'</BarCode></Item></Body></Envelope>';
		
		ShowProgressbar();
		$.post("Sales_LookupItemByBarCode.aspx", strSoapMessage, function(data){
			BarcodeComplete(data, obj);
		});
		
	}
}

function BarcodeComplete(strInnerResp,obj)
{
    obj.value="";
    if("" == strInnerResp)
	{
		ShowProgressbar();
		return;
	}
	
	$.post(gShoppingCartURL, strInnerResp, function(data){
			RefreshCartComplete(data);
		});
}

function RefreshCartComplete(strResp)
{
   CartInner(strResp);
   updateTotals();
   ShowProgressbar();
}

function AutoSelectSeasonEvent(oSelect)
{
	//return;  //do not auto select currently (removed by Justin)
	oSPTable = getParentByPartialId(oSelect, "tblSP");
	if(oSPTable == null)
		return;
		
	oEventSelects = getChildrenByPartialIdOrName(oSPTable, "sp_PerformanceSelect", true);
	
	//only auto change if the first event in list is changed
	if(oEventSelects != null && oEventSelects.length > 0 && oSelect == oEventSelects[0])
	{
		for(var i=1; i<oEventSelects.length; i++)
		{
			if(oSelect.selectedIndex < oEventSelects[i].length)
			{
				oEventSelects[i].selectedIndex = oSelect.selectedIndex;
				oEventSelects[i].onchange();
			}
		}
	}
}
function Membership(itemID,ItemName,ItemPrice,IsMembership,CanSellWithPoints,Points,isMemberCategory,Qty)
{
   addItemToBasket( itemID,ItemName,ItemPrice,IsMembership,CanSellWithPoints,Points,isMemberCategory,Qty);
   AddCoupons_ItemsToCart();
}

function SeasonRunOnClick(runPosition, runName, runId)
{
	gSeasonRunNumber = runPosition;
	gSeasonRunId = runId;
	//toggle view of season elements
	var oTblPerformanceList = gEBI("tblPerformanceList");
	oTblPerformanceList.style.display = "block";
	gEBI("tblSeasonRun").style.display = "none";
	gEBI("SeasonRunTitle").innerText = runName;
	
	var trSeasonPackageRows = oTblPerformanceList.getElementsByTagName("tr"); 
	for(var i=0;i<trSeasonPackageRows.length;i++)
	{
		var oSeasonRun = trSeasonPackageRows[i].getAttribute("seasonrun");
		if(null == oSeasonRun || "" == oSeasonRun)
		{
			trSeasonPackageRows[i].style.display = ""; //show those that have no run
			continue; 
		}
		if(runId == oSeasonRun)
		{
			trSeasonPackageRows[i].style.display = ""; //show those that have current run
			continue; 
		}
		
		trSeasonPackageRows[i].style.display = "none"; //hide all packages with other runs
	}
}
function toggleRightSideDetails()
{
	var lCHSippAddress		= gEBI("chSippAddress");
	var lDIVShipDetails		  = gEBI("divShipDetails");
	
	if(	null == lCHSippAddress || null == lDIVShipDetails ) return;
	
	if(lCHSippAddress.checked)
		lDIVShipDetails.style.display = "block";
	else
		lDIVShipDetails.style.display = "none";
}
function SetShippAddress()
{
	var lSelShippDetails = gEBI("selShippDetails");
	if(null == lSelShippDetails) return false;
	
	var strShippXML = BuildShippingXML();
	if(false == strShippXML) return false;
	
	var lOptionInnerHTML = "";
	
	if(null !=	gEBI("shipping_firstname1"))
		lOptionInnerHTML += gEBI("shipping_firstname1").value;
	
	if(null !=	gEBI("shipping_lastname1"))
		lOptionInnerHTML += " "+ gEBI("shipping_lastname1").value;
	if("" == Trim(lOptionInnerHTML))
		lOptionInnerHTML = "NoName";
		
	var lOption = null;
	if(-1 == lSelShippDetails.selectedIndex)
	{
		lOption = document.createElement("OPTION");
		lSelShippDetails.options.add(lOption);
	}
	else
		lOption = lSelShippDetails.options[lSelShippDetails.selectedIndex];
	
	lOption.innerText = lOptionInnerHTML;
	lOption.selected = true;
	lOption.innerHTML = lOptionInnerHTML;
	lOption.setAttribute('ShippXML',strShippXML);
	lSelShippDetails.disabled = false;
	return true;
}
function AddNewShippAddress()
{
	var lSelShippDetails = gEBI("selShippDetails");
	if(null == lSelShippDetails) return;

	lSelShippDetails.selectedIndex = -1;
	GetShippAddress();
}
function DeleteShippAddress()
{
	var lSelShippDetails = gEBI("selShippDetails");
	if(null == lSelShippDetails) return;

	if(-1 != lSelShippDetails.selectedIndex)
		lSelShippDetails.remove(lSelShippDetails.selectedIndex)
	
	lSelShippDetails.selectedIndex = -1;
	if(0 == lSelShippDetails.options.length)
		lSelShippDetails.disabled = true;
	GetShippAddress();
}

function AddToTPSTransaction(position){
 
  if ( gEBI("hItemOrder_"+position) &&   gEBI("hItemOrder_"+position).getAttribute("CanSellWithPoints")=='true' ){
        if (gEBI("hItemOrder_"+position).getAttribute('AddedToTPSTransaction')=='true'){
           gEBI("hItemOrder_"+position).setAttribute('AddedToTPSTransaction','false');
           gEBI("txtItemOrderFinalPriceTPS_"+position).style.background="none";
         }
     else{
          if ( ReturnAvailableTPS()>= gEBI("hItemOrder_"+position).getAttribute('Points')*
                                      gEBI("hItemOrder_"+position).getAttribute('Quantity') 
             )
            {   
	          gEBI("hItemOrder_"+position).setAttribute('AddedToTPSTransaction','true');
              gEBI("txtItemOrderFinalPriceTPS_"+position).style.background="#F77272";
            }
         }
  }
  updateTotals();
}



function ReturnAvailableTPS(){
    var PatronAccountBalance=gEBI("h_AccountBalance").value;
    var total=0;
    var arrItemOrder = gEBN('hItemOrder');
	for(var i=0;i<arrItemOrder.length;i++){
	if (arrItemOrder[i].getAttribute('CanSellWithPoints')=="true" && arrItemOrder[i].getAttribute('AddedToTPSTransaction')=="true" ){
	        total+=arrItemOrder[i].getAttribute("Points")*arrItemOrder[i].getAttribute("Quantity");
		}
	}
    return PatronAccountBalance-total;
		 
}

function DoPrintAtHome(bpopUp)
{
	if(arguments[0] == null)
		bpopUp = 1;
		
	var sOrderId = String(gCurrentOrderId);
	sOrderId = sOrderId.replace('\n', '');
	sOrderId = sOrderId.replace('\r', '');
	
	if(bpopUp == 1)
		window.open("PrintAtHomeStandard.aspx?oid=" + sOrderId, "_blank","menubar=yes,status=no,location=no,scrollbars=yes,titlebar=yes,top=0,left=0,directories=no");
	else
		window.location.url = "PrintAtHomeStandard.aspx?oid=" + sOrderId ;
}

/*Topaz Signature Pad helper functions*/
function OrderSigPadOnClear(nID)
{
	if(nID != null)
		var SigPlus1 = document.getElementById("pay_" + nID + "_signature");
	else
		var SigPlus1 = document.getElementById("SigPlus1");

   SigPlus1.ClearTablet(); //Clears the signature, in case of error or mistake
}

function OrderSigPadOnStop(nID)
{
	if(nID != null)
		var SigPlus1 = document.getElementById("pay_" + nID + "_signature");

   SigPlus1.TabletState = 0; //Turns tablet off
   SigPlus1.SigString = SigPlus1.SigString;

   //if length is too long sig is a block of scribble
   if( SigPlus1.SigString.length > 25000 )
   {
		OrderSigPadOnClear();
		alert("The signature entered is not a valid signature, please have customer resign.");
		OrderSigPadOnSign();
	}
}

function OrderSigPadOnSign(nID)
{
	if(nID != null)
		var SigPlus1 = document.getElementById("pay_" + nID + "_signature");

	SigPlus1.TabletState = 1; //Turns tablet on
}

function OrderSigPadGetSig(nID)
{
	if(nID != null)
		var SigPlus1 = document.getElementById("pay_" + nID + "_signature");
	if(SigPlus1 != null)
		return SigPlus1.SigString;
	else
		return "";
}
 function EnableorDisable(obj,flag)
 {
	if (obj.value==3)
		isPatron=true;
	checkoutway=obj.value;
	
	if (obj.value==1)
	{
	   if (null!=gEBI("btnPatron"))
		   gEBI("btnPatron").style.display='none';
	}
	else
	{
	   if (null!=gEBI("btnPatron"))
		   gEBI("btnPatron").style.display='block';
	}
	
	if (obj.value==1 || obj.value==3)
	{
	   if (null!=gEBI("divPatronEmail"))
	       gEBI("divPatronEmail").style.display='block';
	   if (null!=gEBI("divPatronEmailInput"))
	       gEBI("divPatronEmailInput").style.display='block';
	    if (null!=gEBI("tdPatronEmail"))
	       gEBI("tdPatronEmail").className="ScPatronLeftP";
	   
	   if (null!=gEBI("divPatronPass"))
	       gEBI("divPatronPass").style.display='block'	;
	   if (null!=gEBI("divPatronPassInput"))
	       gEBI("divPatronPassInput").style.display='block'	;
	       
	   if (null!=gEBI("tdPatronPass"))
	       gEBI("tdPatronPass").className="ScPatronLeftP";
	       
	}
	else
	{
	   if (null!=gEBI("divPatronEmail"))
	       gEBI("divPatronEmail").style.display='none';
	   if (null!=gEBI("divPatronEmailInput"))
	       gEBI("divPatronEmailInput").style.display='none';
	   if (null!=gEBI("divPatronPass"))
	       gEBI("divPatronPass").style.display='none'	;
	   if (null!=gEBI("divPatronPassInput"))
	       gEBI("divPatronPassInput").style.display='none'	;
	   if (null!=gEBI("tdPatronEmail"))
	       gEBI("tdPatronEmail").className="ScPatronLeft";
	   if (null!=gEBI("tdPatronPass"))
	       gEBI("tdPatronPass").className="ScPatronLeft";
	}
	
	if (flag==1)
	{ 
		gEBI("divBillDetails").style.display='block';	
		}
	else
	{
		gEBI("divBillDetails").style.display='none';
	}

 }
 function checkRegisteredpatron()
 {
 	if (checkoutway==1 || checkoutway==3)
	{
		if (null!=gEBI("txtLoginEmail"))
		   if ((gEBI("txtLoginEmail").value).length==0)
		   {
		     alert('Please enter email address');
		      return false;
		   }
	    if (null!=gEBI("txtLoginPassword"))
		   if ((gEBI("txtLoginPassword").value).length==0)
		   {
		      alert('Please enter your password');
		      return false;
		   }
	}
	return true;
	
 }
 
 function Redirect2InventoryRecount(Url)
 {
	window.location.href=Url;
	this.event.returnvalue=false;
 }
 
 function checkTransferAmount(obj,btnId)
 {
   btn=gEBI(btnId);
   if ( obj.value < obj.getAttribute("maxAmount") )
		{  btn.disabled=true;}
    else
      { btn.disabled=false;
      }
 }

 function checkFinalAmount(obj)
 {
	 var a,b;
	 a=b=0;
	 a=parseFloat((obj.value).replace(',','.'));
	 if (null!=obj.getAttribute("Total"))
		b=parseFloat( (obj.getAttribute("Total")).replace(',','.') );
	 else
	 b=-1;
	
	 if ( a.toFixed(2)!=b.toFixed(2) )
	   {
		  obj.style.backgroundColor='red';
	   }
	   else
	   {
		 obj.style.backgroundColor='';
	   }
 }
 
				
function SwapListBoxItems(lbFrom, lbTo, lbNearHiddenFieldToUpdate)
{
	if(null != lbFrom && null != lbTo)
	{
		for(var i=lbFrom.options.length-1;i>=0;i--) 
		{
			var li = lbFrom.options[i];
			if(li.selected)
			{ 
				lbTo.options.add(new Option(li.text, li.value, false, false)); 
				lbTo.options[lbTo.options.length-1].selected = true;
				lbFrom.options.remove(i); 
			}
		}
		
		//after we moved options, remember to update hidden field
		if(null != lbNearHiddenFieldToUpdate)
		{
			var oHidBox = getPreviousSibling(lbNearHiddenFieldToUpdate); 
			if(null != oHidBox)
			{
				var strVal = ""; 
				for(var i=lbNearHiddenFieldToUpdate.options.length-1;i>=0;i--) 
				{
					strVal += lbNearHiddenFieldToUpdate.options[i].value + ","; 
				}
				if(strVal.length > 0)
					strVal = strVal.substr(0, strVal.length - 1); 
				
				oHidBox.value = strVal; 
			}
		}
	}
	
	return false;
}

//---------------------------------:ItemList---------------------------------
function IncrementItem(oImg,oTR)
{
	if(oTR!=null) oImg.style.backgroundColor="blue";
	else oTR=oImg;

	var oInput=getNextSibling(oTR.cells[2].childNodes[0]);
	
	var value=oInput.value;
	if(value=='') value=1;
	else value++;
	oInput.value=value;
	if(oTR!=oImg) oImg.style.backgroundColor="";
}

function DecrementItem(oTR)
{
	var oInput=getNextSibling(oTR.cells[2].childNodes[0]);
	
	var value=oInput.value;
	if(value=='1' || value=='' || value=='0') value='';
	else value--;
	oInput.value=value;
	canInrement=false;
}

function ChangeItem(oTR,event)
{
	if(event==null) event=window.event;
	if (event.button==2) DecrementItem(oTR);
	else IncrementItem(oTR);
}

function AddItemsToBasket(){
 itemsCollection=gEBN('QtyInputItem');
 for (var i=0;i<itemsCollection.length;i++){
   if (itemsCollection[i].value!='' && itemsCollection[i].value>0){
	itemName=itemsCollection[i].getAttribute('ItemName');
	itemId=itemsCollection[i].getAttribute('ItemId');
	listPrice=itemsCollection[i].getAttribute('ListPrice');
	isMembership=itemsCollection[i].getAttribute('IsMembership');
	points=itemsCollection[i].getAttribute('Points');
	canSellWithPoints=itemsCollection[i].getAttribute('CanSellWithPoints');
	isMemberCategory=itemsCollection[i].getAttribute('isMemberCategory');
	isRetail=1; // exclude summ
    addItemToBasket( itemId,itemName,listPrice,isMembership,canSellWithPoints,points,isMemberCategory,itemsCollection[i].value,1);
    
    }
 } 
 AddCoupons_ItemsToCart();
}

function NavigateMoveOverItem(oTR)
{
if(oTR.getAttribute('select')==null)
{
	oTR.style.backgroundColor='#D6D7DE'
}
else
{
	if(oTR.getAttribute('select')=='1') oTR.style.backgroundColor='#16D7DE'
}
}

function NavigateMoveOutItem(oTR)
{
if(oTR.getAttribute('select')==null)
{
	if(oTR.className=='light') oTR.style.backgroundColor='#E8EDF3';
	else oTR.style.backgroundColor='#F5F5F5';
}
else
{
	if(oTR.getAttribute('select')=='1') oTR.style.backgroundColor='#D6DFFE';
}
}

function NavigateMoveOutSection(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='blue';
}
}

function NavigateMoveOverSection(oDiv)
{
if(oDiv.getAttribute('select')==null)
{
	oDiv.style.color='#FF0000'
}
}
//---------------------------------:HoldManager---------------------------------
function SetColor(oTD)
{
	var SampleTD=gEBI("HoldSampleDiv");
	SampleTD.style.backgroundColor=oTD.getAttribute("value");
	SampleTD.setAttribute("value",oTD.getAttribute("value"));
	SetCustomHoldBlock();
}

function More_colorsOver(oSpan)
{
	oSpan.style.color='#000000';
}

function More_colorsOut(oSpan)
{
	oSpan.style.color='Gray';
}

function UpdateHoldSymbol(oInput)
{
	var SampleTD=gEBI("HoldSampleDiv");
	SampleTD.innerText=oInput.value.toUpperCase();
	SetCustomHoldBlock();
}

function SetCustomHoldBlock()
{
	var Hold_Blocks_select= gEBI('HoldBlocks');
	for(var i=0;i<Hold_Blocks_select.options.length;i++)
		{
			if(Hold_Blocks_select.options[i].value=='0')
				{
					Hold_Blocks_select.options[i].selected=true;
					break;
				}
		}
}

function ChangeHoldBlock(oSelect)
{
	var PropStr = oSelect.value;
	if(PropArray!='0')
	{
		var PropArray = PropStr.split('|');
		var Hold_types_select= gEBI('HoldTypes');
		for(var i=0;i<Hold_types_select.options.length;i++)
		{
			if(Hold_types_select.options[i].value==PropArray[0])
				{
					Hold_types_select.options[i].selected=true;
					break;
				}
		}
		
		//check for undefined values (mainly on custom option)
		PropArray[1] = (PropArray[1] == undefined)?"":PropArray[1];
		PropArray[2] = (PropArray[2] == undefined)?"":PropArray[2];
		PropArray[3] = (PropArray[3] == undefined)?"#ffffff":PropArray[3];
		
		gEBI('HoldSymbol').value=PropArray[2];
		gEBI("HoldSampleDiv").innerText=PropArray[2];
		//UpdateHoldSymbol(gEBI('HoldSymbol'));
		gEBI('HoldName').value=PropArray[1];
		gEBI("HoldSampleDiv").style.backgroundColor=PropArray[3];
		gEBI("HoldSampleDiv").setAttribute("value",PropArray[3]);
	}
}

function SetHolds(oSpan)
{
	var SeatsId_sstr;
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	if(arguments[1]!=null && arguments[2]!=null) 
	{
		SeatsId_sstr=arguments[1];
		var currentRequest= arguments[2];
	}
	var CountPerRequest=8000;
	
	if("" == SeatsIdsstr)
		return;
	
	
	if(SeatsIdsstr.length>CountPerRequest && arguments[1]==null) SeatsId_sstr=PartialSeatString(SeatsIdsstr,0,CountPerRequest/8);
	else if(arguments[1]==null) SeatsId_sstr = SeatsIdsstr;	
	//build xml for HoldBlock
	var PropStr= gEBI('HoldBlocks').value;	
	var HoldBlockXML = "";
	if(PropStr=='0') // custom
		{
			HoldBlockXML = "<HoldBlock>";
			HoldBlockXML += "<HoldType><ID>"+gEBI('HoldTypes').value+"</ID></HoldType>";
			HoldBlockXML += "<HoldColor>"+gEBI('HoldSampleDiv').getAttribute("value")+"</HoldColor>";
			HoldBlockXML += "<DisplayCharacter>"+gEBI('HoldSymbol').value+"</DisplayCharacter>";
			HoldBlockXML += "<Name>"+gEBI('HoldName').value+"</Name>";
			HoldBlockXML += "</HoldBlock>";
		}
	else //not custom(only ID is needed)
		{
			var PropArray = PropStr.split('|');
			HoldBlockXML = "<HoldBlock><ID>"+PropArray[4]+"</ID></HoldBlock>";
		}
	

	//build xml for performances
	var sPerfList = "";
	
	var sPerfList = "";
	var lCurrPerfs = GetCurrSeasonPerformanceList(gPerfs, gCurrentPerformanceId);
	for(var i = 0; i < lCurrPerfs.length; i++)
	{
		sPerfList +=lCurrPerfs[i][0]+";";
	}
	if(sPerfList=="") sPerfList = "<param type=\"Performance\"><Performance><ID>" + gCurrentPerformanceId + "</ID></Performance></param>";
	else sPerfList= "<param type=\"System.String\"><string>"+sPerfList+"</string></param>"; 
		
	//build request XML
	var strRequestXML = "<envelope><body>" +
						"<command name=\"InsertSingleHolds\">" +
						"<class name=\"" + 'HoldBlocks' + "\" />";

	strRequestXML += "<param type=\"" + "HoldBlock" + "\">" + HoldBlockXML + "</param>";
	strRequestXML += sPerfList;

	strRequestXML += "<param type=\"System.String\"><string>" + SeatsId_sstr + "</string></param>"; 
	strRequestXML += 	"</command>" +
						"<xslt>BuyTickets.xslt</xslt>" +
						"</body></envelope>";
	
	if(arguments[1]==null) 
	{
		ShowProgressbar();
	}
	if(SeatsIdsstr.length>CountPerRequest && SeatsId_sstr.split(';').length==CountPerRequest/8+1)
	{
		if(arguments[2]==null) var currentRequest= 1; 
		else currentRequest++;
		SeatsId_sstr=PartialSeatString(SeatsIdsstr,currentRequest,CountPerRequest/8);
		if(SeatsId_sstr!="") 
		{
			$.post(gSOAPListenerURL + "?rand=" + GetRandomQSParam(), strRequestXML, function(data){
				SetHolds(oSpan, SeatsId_sstr, currentRequest);
			});	
			return;
		}
	}

	$.post(gSOAPListenerURL + "?rand=" + GetRandomQSParam(), strRequestXML, function(data){
		FillHoldsOnMap(data);
	});	
}

function min(val1,val2)
{
	if(val1>val2) return val2;
	return val1;
}

function PartialSeatString(SeatsIdsstr,NumberofPartial,CountInPartial)
{
	var arrSeats = SeatsIdsstr.split(';');
	var result="";
	if(NumberofPartial*CountInPartial > arrSeats.length) return result;
	for(var i=NumberofPartial*CountInPartial;i<min((NumberofPartial+1)*CountInPartial,arrSeats.length);i++)
		{
			result+=arrSeats[i]+";";
		}
	return result;
}

function ReleaseHolds(oSpan)
{
	var SeatsId_sstr;
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	if(arguments[1]!=null && arguments[2]!=null) 
	{
		SeatsId_sstr=arguments[1];
		var currentRequest= arguments[2];
	}
	var CountPerRequest=8000;
	
	if("" == SeatsIdsstr)
		return;
	
	
	if(SeatsIdsstr.length>CountPerRequest && arguments[1]==null) SeatsId_sstr=PartialSeatString(SeatsIdsstr,0,CountPerRequest/8);
	else if(arguments[1]==null) SeatsId_sstr = SeatsIdsstr;	

	//build xml for performances
	var sPerfList = "";
    var lCurrPerfs = GetCurrSeasonPerformanceList(gPerfs, gCurrentPerformanceId);
    for(var i = 0; i < lCurrPerfs.length; i++)
    {
		sPerfList +=lCurrPerfs[i][0]+";";
    }
    if(sPerfList=="") sPerfList = "<param type=\"Performance\"><Performance><ID>" + gCurrentPerformanceId + "</ID></Performance></param>";
	else sPerfList= "<param type=\"System.String\"><string>"+sPerfList+"</string></param>"; 
		
	//build request XML
	var strRequestXML = "<envelope><body>" +
						"<command name=\"Release\">" +
						"<class name=\"" + 'Holds' + "\" />";

	strRequestXML += sPerfList;

	strRequestXML += "<param type=\"System.String\"><string>" + SeatsId_sstr + "</string></param>"; 
	strRequestXML += 	"</command>" +
						"<xslt>BuyTickets.xslt</xslt>" +
						"</body></envelope>";

	if(arguments[1]==null) ShowProgressbar();
	if(SeatsIdsstr.length>CountPerRequest && SeatsId_sstr.split(';').length==CountPerRequest/8+1)
	{
		if(arguments[2]==null) var currentRequest= 1; 
		else currentRequest++;
		SeatsId_sstr=PartialSeatString(SeatsIdsstr,currentRequest,CountPerRequest/8);
		
		
		if(SeatsId_sstr!="") 
		{
			$.post(gSOAPListenerURL, strRequestXML, function(data){
				ReleaseHolds(oSpan, SeatsId_sstr, currentRequest);
			});	
			return;
		}
	}

	$.post(gSOAPListenerURL, strRequestXML, function(data){
		ReleaseHoldsOnMap(data);
	});	
	
}

function ReleaseHoldsOnMap(strResp)
{
	if( strResp == "") 
	{	
	ShowProgressbar();
	return false;
	}
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	var SeatsIds = oInput.value.split(';');
	for(var i = 0; i < SeatsIds.length; i++)
	{
		//test if the seatids are preceeded with 'st'
		var strSeatId = SeatsIds[i];
		if(SeatsIds[i]=="") continue;
		var oTD = document.getElementById(strSeatId);

		//get holds form inputs
		oColor = oTD.getAttribute("POLvlColor");

		oTD.setAttribute("defCol",oColor);
		oTD.style.backgroundColor = oColor;
		oTD.setAttribute("isSelected","0");
		//oTD.setAttribute("hold", "1");

		//change display character
		var oTextDiv = getChildByTagName(oTD, "DIV")
		if(oTextDiv != null)
		{
			oTextDiv.innerHTML = "";
		}
	}
	oInput.value="";
	ShowProgressbar();
}

function FillHoldsOnMap(strResp)
{
	if( strResp == "") 
	{
	ShowProgressbar();
	return false;	
	}
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	var SeatsIdsstr=oInput.value;
	var SeatsIds = oInput.value.split(';');
	for(var i = 0; i < SeatsIds.length; i++)
	{		
		//test if the seatids are preceeded with 'st'
		var strSeatId = SeatsIds[i];
		if(SeatsIds[i]=="") continue;
		var oTD = document.getElementById(strSeatId);

		//get holds form inputs
		oColor = gEBI('HoldSampleDiv').getAttribute("value");
		oCharInput = gEBI('HoldSymbol').value;
		
		oTD.setAttribute("isSelected","0");
		oTD.setAttribute("POLvlColor", getStyle(oTD,"background-color"));
		oTD.setAttribute("defCol",oColor);
		oTD.style.backgroundColor = oColor;
		//oTD.setAttribute("hold", "1");

		//change display character
		var oTextDiv = getChildByTagName(oTD, "DIV")
		if(oTextDiv != null)
		{
			oTextDiv.innerHTML = oCharInput;

			oTD.style.fontSize = "10px";
		}
	}
	oInput.value="";
	
	ShowProgressbar();	
}

//------------------------------------------------------------------------


//---------------------------------:Sections----------------------------------------
function SelectSeats(oTD,SeatId, ticketId, vPerformanceId, bSoldSeatInformation)
{
	if(bSoldSeatInformation == null) bSoldSeatInformation = true;
	
	var oDiv=gEBI('divSeatsIds');
	var oInput=oDiv.childNodes[0];
	if(oInput==null) oInput=oDiv.childNodes[1];
	if(oTD.getAttribute("hold") == "1")
	{
		if(oTD.getAttribute("shopping_cart") == "1") Ticket_In_Shopping_Cart(oTD,vPerformanceId,SeatId);
		else if(isBox && bSoldSeatInformation)
			BuildDivTicketDetails(oTD,ticketId, vPerformanceId, SeatId);
	}
	else
	{
	if(oTD.getAttribute("isSelected") == "0")
	{
		oTD.style.backgroundColor = gClientIncartColor;
		oTD.setAttribute("isSelected","1");
		if(oTD.getAttribute("InHoldBlock") == "1") 
		{
			var countinblock=parseInt(oInput.getAttribute("InHoldBlock"));
			countinblock++;
			oInput.setAttribute("InHoldBlock",countinblock);
		}
		oInput.value += SeatId+';';
	}
	else
	{
		oTD.style.backgroundColor = oTD.getAttribute("defCol")!=null?oTD.getAttribute("defCol"):'';
		oTD.setAttribute("isSelected","0");
		var lWords = oInput.value.split(";");
		var newSeat='';
		for(var i=0; i<lWords.length-1; i++)
		{
			if(SeatId!=lWords[i]) newSeat+=lWords[i]+';';
		}
		if(oTD.getAttribute("InHoldBlock") == "1") 
		{
			var countinblock=parseInt(oInput.getAttribute("InHoldBlock"));
			countinblock--;
			oInput.setAttribute("InHoldBlock",countinblock);
		}
		oInput.value= newSeat;
	}
	CloseDivTicketDetails();
	}
	var oLImg = getChildByIdOrName(oTD, "large");
	var oSImg = getChildByIdOrName(oTD, "small");
	if(oSImg != null && oSImg.getAttribute("imagetype") == 'graphic')
		{
			InvertObjectVisibility(oLImg);
			InvertObjectVisibility(oSImg);
		}
	if(gEBI("divCountOfSelectedSeats")!=null) gEBI("divCountOfSelectedSeats").innerHTML = oInput.value.split(";").length-1;
}

function TryEnterShopingCart(oInput, spID, strDlgId)
{
	var oDiv=gEBI('divSeatsIds');
	var oInputSeats=oDiv.childNodes[0];
	if(oInputSeats==null) oInputSeats=oDiv.childNodes[1];
	var countinblock=parseInt(oInputSeats.getAttribute("InHoldBlock"));
	if(countinblock!=0)
	{
		modaldialogfromdiv(strDlgId, 280, "auto", false, GetTranslation("capl_please_confirm"), false);
	}
	else 
	{
		NewShowCartContents(oInputSeats,spID);
	}
	
	return false;
}

function NewShowCartContents(oInputSeats)
{
	var spID = "";
	if("undefined" != typeof(arguments[1]) && null != arguments[1])
		spID = arguments[1];
		
	var strDlgId = "";
	if("undefined" != typeof(arguments[2]) && null != arguments[2])
	{
		strDlgId = arguments[2];
		$("#"+strDlgId).dialog("close");
		$("#"+strDlgId).hide();
	}


	//if coming from subscription seat selection
	if((isSeason==1)&&(iLayout<=gPerfs.length)&&((iLayout-1)>=0)){
			RunContinueSeats2(false,oInputSeats,";");
			return;
	}
	else{
		var str = String(oInputSeats.value);
		if (str.substr(str.length-1) == ";")
			str = str.substr(0, str.length-1);

		var arrSeats = str.split(";");
		var strTicketsXML;
		if((null!=gOrder["TicketsXML"])&&(gOrder["TicketsXML"].length>0))
		{
			strTicketsXML = gOrder["TicketsXML"].replace("</Tickets>","");
		}
		else{
			strTicketsXML = "<Tickets>";
		 }

		if(arrSeats.length > 0 && arrSeats[0] != "")
			for(var st=0;st<arrSeats.length;st++){
				arrSeats[st] = arrSeats[st].replace("st","");
				var prf = lookupPerformance(gCurrentPerformanceId);
				strTicketsXML += "<Ticket><Seat><ID>" + arrSeats[st] + "</ID></Seat><Performance><ID>" + gCurrentPerformanceId + "</ID>";
				if((prf!=null)&&(prf.Event!=null)&&(prf.Event.Venue!=null))	strTicketsXML +="<Event><ID>" + prf.Event.ID + "</ID><Venue><ID>" + prf.Event.Venue.ID + "</ID></Venue></Event>";
				strTicketsXML += "</Performance></Ticket>";
			}
		strTicketsXML += "</Tickets>";
	}

	gOrder["TicketsXML"] = strTicketsXML;

	runShowShoppingCart();
}

//gPerf[x][0] = perfid
//gPerf[x][1] = layoutid
//gPerf[x][2] = venueid
//gPerf[x][3] = seasoneventid
//gPerf[x][7] = seats
//gPerf[x][4] = eventid
//gPerf[x][5] = datetime
//gPerf[x][6] = perfname
//gLayouts[x][0] = layoutid
//gLayouts[x][1][x] = gPerfIndex
function ContinueSeats(isGAOverride){
	var oInput = null;
	if("undefined" != typeof(arguments[1]))
		oInput = arguments[1];
	else
		oInput = gEBI('txtSeats');
	var Separator = ",";
	if("undefined" != typeof(arguments[2]))
		Separator = arguments[2];
	if(oInput.value.indexOf("GA") >= 0)
		isSeasonGA = true;
	else 
		isSeasonGA = false;
	if(isGAOverride != null)
		isSeasonGA = isGAOverride
	
	RunContinueSeats2(isSeasonGA,oInput,",");
}

//gPerf[x][0] = perfid
//gPerf[x][1] = layoutid
//gPerf[x][2] = venueid
//gPerf[x][3] = seasoneventid
//gPerf[x][7] = seats
//gPerf[x][4] = eventid
//gPerf[x][5] = datetime
//gPerf[x][6] = perfname
//gLayouts[x][0] = layoutid
//gLayouts[x][1][x] = gPerfIndex

/*
isSeasonGA - true in case we have GA seats in season?
oInput - text field that contains all currently selected seats as string separated by ... 
Separator - string separator
isAutoCall - true if it's called from RunContinueSeats2, i.e. if it is used to autoselect seats
*/
function RunContinueSeats2(isSeasonGA, 
	oInput, 
	Separator, 
	isAutoCall)
{
	var strSelectedSeatsForRestore = oInput.value; //used in case we want to go back
	
	//parse seat string
	var str = String(oInput.value);
		if (str.substr(str.length-1) == Separator)
			str = str.substr(0, str.length-1);
	
	//put seats string into array
	var arrSeats = new Array(); 
	if("" != str)
	{
		arrSeats = str.split(Separator);
		
		for(var st=0;st<arrSeats.length;st++)
		{
			arrSeats[st] = arrSeats[st].replace("st","");
		}
	}
		
	//iLayout - layout or performance index inside the season package
	gIsSeason = true;
		
	//check if the same number of seats is chosen as for previous performance
	if(iLayout > 1
		&& true != isAutoCall 
		&& (arrSeats.length!=gPerfs[0][7].length))
	{
		alert("Please Select a total of " + gPerfs[0][7].length + " seats.");
		
		//reload page without increasing iLayout
		return false;
	}

	//if seats have not already been defined
	if(gPerfs[iLayout-1][7] == null)
		gPerfs[iLayout-1][7] = arrSeats;
	if(iLayout<gPerfs.length)
	{
		//set local variables for next performance data, used in GetSections call!!!
		//iLayout always points to next performance
		var perfid = gPerfs[iLayout][0];
		var venueid = gPerfs[iLayout][2];
		var layoutid = gPerfs[iLayout][1];
		var seasoneventid = gPerfs[iLayout][3];
		var clientid = gEBI('hClientId').value;
		var perfdatetime = gPerfs[iLayout][5];
		var perfname = gPerfs[iLayout][6];
		var vDefaultSectionId = gPerfs[iLayout][8];
		
		oInput.value = "";
		//gEBI('tdSeats' + seasoneventid).parentNode.childNodes[0].style.color = '#ff0000';
	
		var bManualSeats = true; //when we set it to true, it means we need to load next performance for manual seat selection
		var lSeasonPackageId =-1;
		var lgSeasonPackageId = null;
		if(gSeasonLightningSeat)
		{
			//if we are in lightning mode 
			bManualSeats = false; //then we should not select seats manually
			
			//first thing is to add previous performance's layout to gLayouts array 
			var bNewLayout = true
			for(var z=0; z < gLayouts.length; z++)
			{
				if(gPerfs[iLayout-1][1] == gLayouts[z][0])
				{
					bNewLayout = false;
					break;
				}
			}
			if(bNewLayout)
			{
				var arrLayouts = new Array();
				arrLayouts.push(gPerfs[iLayout-1][1]);
				arrLayouts.push(gPerfs[iLayout-1][7]);
				gLayouts.push(arrLayouts);
			}
			
			//second - check if the next performance's layout 
			//is already one of the current or previous performance's layouts
			//if so get the same seats in next performance as in the first one 
			var bNewLayout = true
			for(var z=0; z < gLayouts.length; z++)
			{
				if(gPerfs[iLayout][1] == gLayouts[z][0])
				{
					bNewLayout = false;
					gPerfs[iLayout][7] = gLayouts[z][1]; //here we copy the seats from previous performance
					iLayout++;
					
					//run the function again to really get the seats 
					RunContinueSeats2(isSeasonGA, oInput, Separator, true);
					return; //exit this function here
				}
			}
		
			if(bNewLayout) 
			{
				//if we got here, it means we have a new layout and new seats should be taken in lightning mode
				bManualSeats = true; 
				lgSeasonPackageId=gSeasonPackageId;
			}			
		}
		
		if(bManualSeats)
		{
			//if we are here it means we are either in turtle mode
			//or we found a new layout in lightning mode
			//and thus need to get seats manually
			
			if(isSeasonGA)
				vDefaultSectionId = null; //reset default section in case it's a GA perf
		
			//reload page 
			GetSections(perfid, venueid, layoutid, clientid, perfdatetime, perfname, (lgSeasonPackageId==null?gSeasonPackageId:lgSeasonPackageId), gSeasonPackageName, vDefaultSectionId);
			iLayout++;	//increase iLayout
			return false;
		}

	}
	
	//if we got here, 
	//it means all seat selection for season is done and we are ready to build XML for shopping cart
	//do it now
	
	var strSubscriptionsXML = "";
		
	if((null!=gOrder["SubscriptionsXML"])&&(gOrder["SubscriptionsXML"].length>0))
	{
		strSubscriptionsXML = gOrder["SubscriptionsXML"].replace("</Subscriptions>","");
	}
	else{
		strSubscriptionsXML = "<Subscriptions>";
	}
	if("undefined" == typeof(gSeasonPackageDecrementSingle))
		gSeasonPackageDecrementSingle = "false";

	//loop for each seat selected in first performance of season 
	//subsequent performances must have the same number of seats
	for(var s=0;s<gPerfs[0][7].length;s++) 
	{
		strSubscriptionsXML += "<Subscription><SeasonPackage><ID>" + gSeasonPackageId + "</ID><Name>" + gSeasonPackageName + "</Name><HasPriceDistributions>" + gSeasonPackageHasPriceDistributions + "</HasPriceDistributions><DecrementSingleReturn>" + gSeasonPackageDecrementSingle + "</DecrementSingleReturn></SeasonPackage><SeasonTickets>";
			
		//loop for each performance of season 
		for(var p=0;p<gPerfs.length;p++)
		{
			var seats = gPerfs[p][7][s];
			strSubscriptionsXML += "<SeasonTicket>";
			
			var arr = seats.split("GA");
			//alert(p + ":::" + arr.join("-"));
			//gPerfs[p][7][s] = arr[0];
			if(arr[1] != null)	//if this is null then its not a GA ticket
				strSubscriptionsXML += "<Ticket GA='true'><TicketType><ID>" + arr[1] + "</ID></TicketType><Seat><ID>" + arr[0] + "</ID></Seat><Performance><ID>" + gPerfs[p][0] + "</ID><Event><ID>" + gPerfs[p][4] + "</ID><Venue><ID>" + gPerfs[p][2] + "</ID></Venue></Event></Performance></Ticket>";
			else
				strSubscriptionsXML += "<Ticket><Seat><ID>" + gPerfs[p][7][s] + "</ID></Seat><Performance><ID>" + gPerfs[p][0] + "</ID><Event><ID>" + gPerfs[p][4] + "</ID><Venue><ID>" + gPerfs[p][2] + "</ID></Venue></Event></Performance></Ticket>";
						
			strSubscriptionsXML += "</SeasonTicket>";
		}
		strSubscriptionsXML += "</SeasonTickets></Subscription>";
		
	}
	
	strSubscriptionsXML += "</Subscriptions>";
	gOrder["SubscriptionsXML"] = strSubscriptionsXML;
	ShowShoppingCart();
}

//----------------------------------------------------------------------------------

//---------------------------------:Progress_bar---------------------------------
function Progressbar_Visibility(oSpan)
{
var Progressbar=gEBI(oSpan);
if(Progressbar != null)
{
	if(Progressbar.style.display=='none')
{
	Progressbar.style.display = 'block';
	gEBI("Progress_Bar_Image_Td").innerHTML='<img src="images/progress2.gif"/>';
}
else
{
	Progressbar.style.display = 'none';
}
}
}
//----------------------------------------------------------------------------------

function HtmlDecode(s)
{
	var out = "";
	if (s==null) return;
	var l = s.length;
	for (var i=0; i<l; i++)
	{
		var ch = s.charAt(i);
		if (ch == '&')
		{
			var semicolonIndex = s.indexOf(';', i+1);
			if (semicolonIndex > 0)
			{
				var entity = s.substring(i + 1, semicolonIndex);
				if (entity.length > 1 && entity.charAt(0) == '#')
				{
					if (entity.charAt(1) == 'x' || entity.charAt(1) == 'X')
						ch = String.fromCharCode(eval('0'+entity.substring(1)));
					else
						ch = String.fromCharCode(eval(entity.substring(1)));
				}
				else
				{
					switch (entity)
					{
						case 'quot': ch = String.fromCharCode(0x0022); break;
						case 'amp': ch = String.fromCharCode(0x0026); break;
						case 'lt': ch = String.fromCharCode(0x003c); break;
						case 'gt': ch = String.fromCharCode(0x003e); break;
						case 'nbsp': ch = String.fromCharCode(0x00a0); break;
						case 'iexcl': ch = String.fromCharCode(0x00a1); break;
						case 'cent': ch = String.fromCharCode(0x00a2); break;
						case 'pound': ch = String.fromCharCode(0x00a3); break;
						case 'curren': ch = String.fromCharCode(0x00a4); break;
						case 'yen': ch = String.fromCharCode(0x00a5); break;
						case 'brvbar': ch = String.fromCharCode(0x00a6); break;
						case 'sect': ch = String.fromCharCode(0x00a7); break;
						case 'uml': ch = String.fromCharCode(0x00a8); break;
						case 'copy': ch = String.fromCharCode(0x00a9); break;
						case 'ordf': ch = String.fromCharCode(0x00aa); break;
						case 'laquo': ch = String.fromCharCode(0x00ab); break;
						case 'not': ch = String.fromCharCode(0x00ac); break;
						case 'shy': ch = String.fromCharCode(0x00ad); break;
						case 'reg': ch = String.fromCharCode(0x00ae); break;
						case 'macr': ch = String.fromCharCode(0x00af); break;
						case 'deg': ch = String.fromCharCode(0x00b0); break;
						case 'plusmn': ch = String.fromCharCode(0x00b1); break;
						case 'sup2': ch = String.fromCharCode(0x00b2); break;
						case 'sup3': ch = String.fromCharCode(0x00b3); break;
						case 'acute': ch = String.fromCharCode(0x00b4); break;
						case 'micro': ch = String.fromCharCode(0x00b5); break;
						case 'para': ch = String.fromCharCode(0x00b6); break;
						case 'middot': ch = String.fromCharCode(0x00b7); break;
						case 'cedil': ch = String.fromCharCode(0x00b8); break;
						case 'sup1': ch = String.fromCharCode(0x00b9); break;
						case 'ordm': ch = String.fromCharCode(0x00ba); break;
						case 'raquo': ch = String.fromCharCode(0x00bb); break;
						case 'frac14': ch = String.fromCharCode(0x00bc); break;
						case 'frac12': ch = String.fromCharCode(0x00bd); break;
						case 'frac34': ch = String.fromCharCode(0x00be); break;
						case 'iquest': ch = String.fromCharCode(0x00bf); break;
						case 'Agrave': ch = String.fromCharCode(0x00c0); break;
						case 'Aacute': ch = String.fromCharCode(0x00c1); break;
						case 'Acirc': ch = String.fromCharCode(0x00c2); break;
						case 'Atilde': ch = String.fromCharCode(0x00c3); break;
						case 'Auml': ch = String.fromCharCode(0x00c4); break;
						case 'Aring': ch = String.fromCharCode(0x00c5); break;
						case 'AElig': ch = String.fromCharCode(0x00c6); break;
						case 'Ccedil': ch = String.fromCharCode(0x00c7); break;
						case 'Egrave': ch = String.fromCharCode(0x00c8); break;
						case 'Eacute': ch = String.fromCharCode(0x00c9); break;
						case 'Ecirc': ch = String.fromCharCode(0x00ca); break;
						case 'Euml': ch = String.fromCharCode(0x00cb); break;
						case 'Igrave': ch = String.fromCharCode(0x00cc); break;
						case 'Iacute': ch = String.fromCharCode(0x00cd); break;
						case 'Icirc': ch = String.fromCharCode(0x00ce ); break;
						case 'Iuml': ch = String.fromCharCode(0x00cf); break;
						case 'ETH': ch = String.fromCharCode(0x00d0); break;
						case 'Ntilde': ch = String.fromCharCode(0x00d1); break;
						case 'Ograve': ch = String.fromCharCode(0x00d2); break;
						case 'Oacute': ch = String.fromCharCode(0x00d3); break;
						case 'Ocirc': ch = String.fromCharCode(0x00d4); break;
						case 'Otilde': ch = String.fromCharCode(0x00d5); break;
						case 'Ouml': ch = String.fromCharCode(0x00d6); break;
						case 'times': ch = String.fromCharCode(0x00d7); break;
						case 'Oslash': ch = String.fromCharCode(0x00d8); break;
						case 'Ugrave': ch = String.fromCharCode(0x00d9); break;
						case 'Uacute': ch = String.fromCharCode(0x00da); break;
						case 'Ucirc': ch = String.fromCharCode(0x00db); break;
						case 'Uuml': ch = String.fromCharCode(0x00dc); break;
						case 'Yacute': ch = String.fromCharCode(0x00dd); break;
						case 'THORN': ch = String.fromCharCode(0x00de); break;
						case 'szlig': ch = String.fromCharCode(0x00df); break;
						case 'agrave': ch = String.fromCharCode(0x00e0); break;
						case 'aacute': ch = String.fromCharCode(0x00e1); break;
						case 'acirc': ch = String.fromCharCode(0x00e2); break;
						case 'atilde': ch = String.fromCharCode(0x00e3); break;
						case 'auml': ch = String.fromCharCode(0x00e4); break;
						case 'aring': ch = String.fromCharCode(0x00e5); break;
						case 'aelig': ch = String.fromCharCode(0x00e6); break;
						case 'ccedil': ch = String.fromCharCode(0x00e7); break;
						case 'egrave': ch = String.fromCharCode(0x00e8); break;
						case 'eacute': ch = String.fromCharCode(0x00e9); break;
						case 'ecirc': ch = String.fromCharCode(0x00ea); break;
						case 'euml': ch = String.fromCharCode(0x00eb); break;
						case 'igrave': ch = String.fromCharCode(0x00ec); break;
						case 'iacute': ch = String.fromCharCode(0x00ed); break;
						case 'icirc': ch = String.fromCharCode(0x00ee); break;
						case 'iuml': ch = String.fromCharCode(0x00ef); break;
						case 'eth': ch = String.fromCharCode(0x00f0); break;
						case 'ntilde': ch = String.fromCharCode(0x00f1); break;
						case 'ograve': ch = String.fromCharCode(0x00f2); break;
						case 'oacute': ch = String.fromCharCode(0x00f3); break;
						case 'ocirc': ch = String.fromCharCode(0x00f4); break;
						case 'otilde': ch = String.fromCharCode(0x00f5); break;
						case 'ouml': ch = String.fromCharCode(0x00f6); break;
						case 'divide': ch = String.fromCharCode(0x00f7); break;
						case 'oslash': ch = String.fromCharCode(0x00f8); break;
						case 'ugrave': ch = String.fromCharCode(0x00f9); break;
						case 'uacute': ch = String.fromCharCode(0x00fa); break;
						case 'ucirc': ch = String.fromCharCode(0x00fb); break;
						case 'uuml': ch = String.fromCharCode(0x00fc); break;
						case 'yacute': ch = String.fromCharCode(0x00fd); break;
						case 'thorn': ch = String.fromCharCode(0x00fe); break;
						case 'yuml': ch = String.fromCharCode(0x00ff); break;
						case 'OElig': ch = String.fromCharCode(0x0152); break;
						case 'oelig': ch = String.fromCharCode(0x0153); break;
						case 'Scaron': ch = String.fromCharCode(0x0160); break;
						case 'scaron': ch = String.fromCharCode(0x0161); break;
						case 'Yuml': ch = String.fromCharCode(0x0178); break;
						case 'fnof': ch = String.fromCharCode(0x0192); break;
						case 'circ': ch = String.fromCharCode(0x02c6); break;
						case 'tilde': ch = String.fromCharCode(0x02dc); break;
						case 'Alpha': ch = String.fromCharCode(0x0391); break;
						case 'Beta': ch = String.fromCharCode(0x0392); break;
						case 'Gamma': ch = String.fromCharCode(0x0393); break;
						case 'Delta': ch = String.fromCharCode(0x0394); break;
						case 'Epsilon': ch = String.fromCharCode(0x0395); break;
						case 'Zeta': ch = String.fromCharCode(0x0396); break;
						case 'Eta': ch = String.fromCharCode(0x0397); break;
						case 'Theta': ch = String.fromCharCode(0x0398); break;
						case 'Iota': ch = String.fromCharCode(0x0399); break;
						case 'Kappa': ch = String.fromCharCode(0x039a); break;
						case 'Lambda': ch = String.fromCharCode(0x039b); break;
						case 'Mu': ch = String.fromCharCode(0x039c); break;
						case 'Nu': ch = String.fromCharCode(0x039d); break;
						case 'Xi': ch = String.fromCharCode(0x039e); break;
						case 'Omicron': ch = String.fromCharCode(0x039f); break;
						case 'Pi': ch = String.fromCharCode(0x03a0); break;
						case ' Rho ': ch = String.fromCharCode(0x03a1); break;
						case 'Sigma': ch = String.fromCharCode(0x03a3); break;
						case 'Tau': ch = String.fromCharCode(0x03a4); break;
						case 'Upsilon': ch = String.fromCharCode(0x03a5); break;
						case 'Phi': ch = String.fromCharCode(0x03a6); break;
						case 'Chi': ch = String.fromCharCode(0x03a7); break;
						case 'Psi': ch = String.fromCharCode(0x03a8); break;
						case 'Omega': ch = String.fromCharCode(0x03a9); break;
						case 'alpha': ch = String.fromCharCode(0x03b1); break;
						case 'beta': ch = String.fromCharCode(0x03b2); break;
						case 'gamma': ch = String.fromCharCode(0x03b3); break;
						case 'delta': ch = String.fromCharCode(0x03b4); break;
						case 'epsilon': ch = String.fromCharCode(0x03b5); break;
						case 'zeta': ch = String.fromCharCode(0x03b6); break;
						case 'eta': ch = String.fromCharCode(0x03b7); break;
						case 'theta': ch = String.fromCharCode(0x03b8); break;
						case 'iota': ch = String.fromCharCode(0x03b9); break;
						case 'kappa': ch = String.fromCharCode(0x03ba); break;
						case 'lambda': ch = String.fromCharCode(0x03bb); break;
						case 'mu': ch = String.fromCharCode(0x03bc); break;
						case 'nu': ch = String.fromCharCode(0x03bd); break;
						case 'xi': ch = String.fromCharCode(0x03be); break;
						case 'omicron': ch = String.fromCharCode(0x03bf); break;
						case 'pi': ch = String.fromCharCode(0x03c0); break;
						case 'rho': ch = String.fromCharCode(0x03c1); break;
						case 'sigmaf': ch = String.fromCharCode(0x03c2); break;
						case 'sigma': ch = String.fromCharCode(0x03c3); break;
						case 'tau': ch = String.fromCharCode(0x03c4); break;
						case 'upsilon': ch = String.fromCharCode(0x03c5); break;
						case 'phi': ch = String.fromCharCode(0x03c6); break;
						case 'chi': ch = String.fromCharCode(0x03c7); break;
						case 'psi': ch = String.fromCharCode(0x03c8); break;
						case 'omega': ch = String.fromCharCode(0x03c9); break;
						case 'thetasym': ch = String.fromCharCode(0x03d1); break;
						case 'upsih': ch = String.fromCharCode(0x03d2); break;
						case 'piv': ch = String.fromCharCode(0x03d6); break;
						case 'ensp': ch = String.fromCharCode(0x2002); break;
						case 'emsp': ch = String.fromCharCode(0x2003); break;
						case 'thinsp': ch = String.fromCharCode(0x2009); break;
						case 'zwnj': ch = String.fromCharCode(0x200c); break;
						case 'zwj': ch = String.fromCharCode(0x200d); break;
						case 'lrm': ch = String.fromCharCode(0x200e); break;
						case 'rlm': ch = String.fromCharCode(0x200f); break;
						case 'ndash': ch = String.fromCharCode(0x2013); break;
						case 'mdash': ch = String.fromCharCode(0x2014); break;
						case 'lsquo': ch = String.fromCharCode(0x2018); break;
						case 'rsquo': ch = String.fromCharCode(0x2019); break;
						case 'sbquo': ch = String.fromCharCode(0x201a); break;
						case 'ldquo': ch = String.fromCharCode(0x201c); break;
						case 'rdquo': ch = String.fromCharCode(0x201d); break;
						case 'bdquo': ch = String.fromCharCode(0x201e); break;
						case 'dagger': ch = String.fromCharCode(0x2020); break;
						case 'Dagger': ch = String.fromCharCode(0x2021); break;
						case 'bull': ch = String.fromCharCode(0x2022); break;
						case 'hellip': ch = String.fromCharCode(0x2026); break;
						case 'permil': ch = String.fromCharCode(0x2030); break;
						case 'prime': ch = String.fromCharCode(0x2032); break;
						case 'Prime': ch = String.fromCharCode(0x2033); break;
						case 'lsaquo': ch = String.fromCharCode(0x2039); break;
						case 'rsaquo': ch = String.fromCharCode(0x203a); break;
						case 'oline': ch = String.fromCharCode(0x203e); break;
						case 'frasl': ch = String.fromCharCode(0x2044); break;
						case 'euro': ch = String.fromCharCode(0x20ac); break;
						case 'image': ch = String.fromCharCode(0x2111); break;
						case 'weierp': ch = String.fromCharCode(0x2118); break;
						case 'real': ch = String.fromCharCode(0x211c); break;
						case 'trade': ch = String.fromCharCode(0x2122); break;
						case 'alefsym': ch = String.fromCharCode(0x2135); break;
						case 'larr': ch = String.fromCharCode(0x2190); break;
						case 'uarr': ch = String.fromCharCode(0x2191); break;
						case 'rarr': ch = String.fromCharCode(0x2192); break;
						case 'darr': ch = String.fromCharCode(0x2193); break;
						case 'harr': ch = String.fromCharCode(0x2194); break;
						case 'crarr': ch = String.fromCharCode(0x21b5); break;
						case 'lArr': ch = String.fromCharCode(0x21d0); break;
						case 'uArr': ch = String.fromCharCode(0x21d1); break;
						case 'rArr': ch = String.fromCharCode(0x21d2); break;
						case 'dArr': ch = String.fromCharCode(0x21d3); break;
						case 'hArr': ch = String.fromCharCode(0x21d4); break;
						case 'forall': ch = String.fromCharCode(0x2200); break;
						case 'part': ch = String.fromCharCode(0x2202); break;
						case 'exist': ch = String.fromCharCode(0x2203); break;
						case 'empty': ch = String.fromCharCode(0x2205); break;
						case 'nabla': ch = String.fromCharCode(0x2207); break;
						case 'isin': ch = String.fromCharCode(0x2208); break;
						case 'notin': ch = String.fromCharCode(0x2209); break;
						case 'ni': ch = String.fromCharCode(0x220b); break;
						case 'prod': ch = String.fromCharCode(0x220f); break;
						case 'sum': ch = String.fromCharCode(0x2211); break;
						case 'minus': ch = String.fromCharCode(0x2212); break;
						case 'lowast': ch = String.fromCharCode(0x2217); break;
						case 'radic': ch = String.fromCharCode(0x221a); break;
						case 'prop': ch = String.fromCharCode(0x221d); break;
						case 'infin': ch = String.fromCharCode(0x221e); break;
						case 'ang': ch = String.fromCharCode(0x2220); break;
						case 'and': ch = String.fromCharCode(0x2227); break;
						case 'or': ch = String.fromCharCode(0x2228); break;
						case 'cap': ch = String.fromCharCode(0x2229); break;
						case 'cup': ch = String.fromCharCode(0x222a); break;
						case 'int': ch = String.fromCharCode(0x222b); break;
						case 'there4': ch = String.fromCharCode(0x2234); break;
						case 'sim': ch = String.fromCharCode(0x223c); break;
						case 'cong': ch = String.fromCharCode(0x2245); break;
						case 'asymp': ch = String.fromCharCode(0x2248); break;
						case 'ne': ch = String.fromCharCode(0x2260); break;
						case 'equiv': ch = String.fromCharCode(0x2261); break;
						case 'le': ch = String.fromCharCode(0x2264); break;
						case 'ge': ch = String.fromCharCode(0x2265); break;
						case 'sub': ch = String.fromCharCode(0x2282); break;
						case 'sup': ch = String.fromCharCode(0x2283); break;
						case 'nsub': ch = String.fromCharCode(0x2284); break;
						case 'sube': ch = String.fromCharCode(0x2286); break;
						case 'supe': ch = String.fromCharCode(0x2287); break;
						case 'oplus': ch = String.fromCharCode(0x2295); break;
						case 'otimes': ch = String.fromCharCode(0x2297); break;
						case 'perp': ch = String.fromCharCode(0x22a5); break;
						case 'sdot': ch = String.fromCharCode(0x22c5); break;
						case 'lceil': ch = String.fromCharCode(0x2308); break;
						case 'rceil': ch = String.fromCharCode(0x2309); break;
						case 'lfloor': ch = String.fromCharCode(0x230a); break;
						case 'rfloor': ch = String.fromCharCode(0x230b); break;
						case 'lang': ch = String.fromCharCode(0x2329); break;
						case 'rang': ch = String.fromCharCode(0x232a); break;
						case 'loz': ch = String.fromCharCode(0x25ca); break;
						case 'spades': ch = String.fromCharCode(0x2660); break;
						case 'clubs': ch = String.fromCharCode(0x2663); break;
						case 'hearts': ch = String.fromCharCode(0x2665); break;
						case 'diams': ch = String.fromCharCode(0x2666); break;
						default: ch = ''; break;
					}
				}
				i = semicolonIndex;
			}
		}
		out += ch;
	}
	return out;
}


function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function InspectMinQty(pInput,pobjInput,MinValue)
{
	if(MinValue!=0)	
	{
		var value=pInput.value;
		if(value!=''&& value!='0' && value<MinValue) value=MinValue;
		pInput.value=value;
	}
	pobjInput.setAttribute('Quantity',pInput.value)
}

