/*
		Event Booking Application Form Utilities - Benjamin Dry
*/

var	ticketTypesArray=new Array();	
var	ticketTypesData=new Array();	
var postageTypes = new Array();

// Main Switch to move between steps

function completeStep(stepNo){
	formObj = document.bookingForm;
	
	if(stepNo==1){
		venueId = formObj.venueId.value;
		eventId = formObj.eventId.value;
		if(venueId!=""){
			// Make a call to the AJAX Utilities
			url = "ajaxBookings.cfm?action=getDatesForVenue&venueId="+venueId+"&eventId="+eventId;
			//document.getElementById("debug").innerHTML = url;
			loadXMLDoc(url,"parseDateData")
		}
		clearSteps(stepNo);
	}

	if(stepNo==2){
		performanceDateTime = formObj.performanceDateTime.value;
		if(performanceDateTime!=""){
			venueId = formObj.venueId.value;
			eventId = formObj.eventId.value;
			// Make a call to the AJAX Utilities
			url = "ajaxBookings.cfm?action=getTicketTypes&venueId="+venueId+"&eventId="+eventId+"&performanceDateTime="+performanceDateTime;
		//	document.getElementById("debug").innerHTML = url;
			loadXMLDoc(url,"parseTicketTypesData")
		}
		clearSteps(stepNo);
	}

	if(stepNo==3){
		performanceDateTime = formObj.performanceDateTime.value;
		if(performanceDateTime!=""){
			venueId = formObj.venueId.value;
			eventId = formObj.eventId.value;
			// Make a call to the AJAX Utilities
			url = "ajaxBookings.cfm?action=getTicketTypes&venueId="+venueId+"&eventId="+eventId+"&performanceDateTime="+performanceDateTime;
		//	document.getElementById("debug").innerHTML = url;
			loadXMLDoc(url,"parseTicketTypesData")
		}
		clearSteps(stepNo);
	}
	
	if(stepNo==4){
		performanceDateTime = formObj.performanceDateTime.value;
		eventId = formObj.eventId.value;
		// Make a call to the AJAX Utilities
		if(bNoTickets==0){
			url = "ajaxBookings.cfm?action=getPostageTypes&eventId="+eventId;
			//	document.getElementById("debug").innerHTML = url;
			loadXMLDoc(url,"parsePostageTypesData")
			clearSteps(stepNo);
		} else {
			noTicketDisplay();
		}
	}

	if(stepNo==5){
		checkOutOptions();
		// Make a call to the AJAX Utilities
		//url = "ajaxBookings.cfm?action=getPostageTypes";
		//	document.getElementById("debug").innerHTML = url;
		//loadXMLDoc(url,"parsePostageTypesData")
		clearSteps(stepNo);
	}
		
}

function clearSteps(stepNo){
	stepDivs = 5;
	for(i=1;i<stepDivs+1;i++){
		if(i>stepNo){
			document.getElementById("step"+i+"Container").innerHTML = "";
		}
	}
	document.getElementById("bookingProgressImg").src = "wsimages/eventTicketPurchaseStep"+stepNo+".gif";
}

// Step 1 to Step 2 - parse the XML returned containing the available dates for the venue

function parseDateData(){
	// get parent node to read
	xmlDoc = xmlhttp.responseXML;
	var htmlStr = "";
	optionsStr = "";
	datesToLoop=xmlDoc.getElementsByTagName('date').length;
	datesNode=xmlDoc.getElementsByTagName('eventDates')[0];
	for(i=0;i<datesToLoop;i++){
		dateDisplay = getElementTextNS("", "date", datesNode, i);
		dateValue = getAttributeTextNS("", "date", datesNode, i,"val");
		optionsStr = optionsStr+"<option value=\""+dateValue+"\">"+dateDisplay+"</option>";
	}
	htmlStr = htmlStr+"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"bookingFormElement\" >";
	htmlStr = htmlStr+"<tr><td valign=\"top\"><img src=\"wsimages\/eventTicketPurchaseStep2Red.gif\" alt=\"Step 2\"><\/td>";
	htmlStr = htmlStr+"<td class=\"bookingFormField\" valign=\"top\"><h4>Choose a Date...<\/h4>";
 	htmlStr = htmlStr+"<select name=\"performanceDateTime\" size=\"1\" onchange=\"completeStep\(2\)\">";
 	htmlStr = htmlStr+"<option value=\"\"><\/option>"+optionsStr+"<\/select><\/td><\/tr><\/table>";

 	document.getElementById("step2Container").innerHTML = htmlStr;
 	document.getElementById("bookingProgressImg").src = "wsimages/eventTicketPurchaseStep2.gif";
}

// Step 2 to Step 3 - parse the XML returned containing the available dates for the venue

function parseTicketTypesData(){
	// get parent node to read
	xmlDoc = xmlhttp.responseXML;
	var htmlStr = "";
	optionsStr = "";

	
	ticketsToLoop=xmlDoc.getElementsByTagName('ticket').length;
	ticketsNode=xmlDoc.getElementsByTagName('tickets')[0];
	
	// Work out the ticket types available, it's a bit long winded but the way the data
	// is constructed we need to drill deep to get the tyoes first and kind of work backwards....
	// and yes it uses three nested loops but the amount of data is negligable...

	ticketTypesArray=new Array();	
	ticketTypesData=new Array();
	for(i=0;i<ticketsToLoop;i++){
		ticketNode=ticketsNode.getElementsByTagName('ticket')[i];
		ticketTypesLen = ticketNode.getElementsByTagName('type').length;
	
		for(j=0;j<ticketTypesLen;j++){
			ticketTypeId = getAttributeTextNS("", "type", ticketNode, j,"id");
			ticketTypeName = getElementTextNS("", "type", ticketNode, j);
			ticketTypePrice = getAttributeTextNS("", "type", ticketNode, j,"price");
			className = getAttributeTextNS("", "ticket", ticketsNode, i,"class");
			maxPurchaseAmount = getAttributeTextNS("", "ticket", ticketsNode, i,"maxPurchaseAmount");
			ticketsLeft = getAttributeTextNS("", "ticket", ticketsNode, i,"ticketsLeft");
								
			addType = 1;

			// Loop over array to find the existence of the type already there.
			
			for(k=0;k<ticketTypesArray.length;k++){
				if(ticketTypesArray[k]==ticketTypeName){
					addType = 0;
				}
			}
			
			// If the type is not already in the array then add it!
		
			if(addType==1){
				ticketTypesArray[ticketTypesArray.length] = ticketTypeName;				
			}
			
			// Add data to main ticketTypeData array
			newArrayPos = ticketTypesData.length;
			ticketTypesData[newArrayPos] = new Array(3);
			ticketTypesData[newArrayPos][1] = ticketTypeId;
			ticketTypesData[newArrayPos][2] = ticketTypeName;
			ticketTypesData[newArrayPos][3] = ticketTypePrice;
			ticketTypesData[newArrayPos][4] = className;
			ticketTypesData[newArrayPos][5] = maxPurchaseAmount;
			ticketTypesData[newArrayPos][6] = ticketsLeft;
		}
	}
	
	ticketsToLoop=xmlDoc.getElementsByTagName('ticket').length;
	dataStr = "<table class=\"ticketTypesContainer\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><th colspan=\"2\">Choose Ticket Types...</th><th class=\"ticketTypesHeadCenter\">Qty.</th><th class=\"ticketTypesHeadCenter\">Price</th><th class=\"ticketTypesHeadCenter\">Available</th></tr>";

	// Sort the ticket names array.
	ticketTypesArray.sort();
	
	for(k=0;k<ticketTypesArray.length;k++){
	
			ticketTypeName = ticketTypesArray[k];
			ticketsLeft = 1;
			
			for(m=0;m<ticketTypesData.length;m++){
				if(ticketTypesData[m][2] == ticketTypeName){
					ticketTypeId = ticketTypesData[m][1];
					break;
				}
			}
			
			dataStr = dataStr+"<tr><td><b>"+ticketTypeName+":</b></td><td><input type=\"hidden\" name=\"ticketTypeIds\" value=\""+ticketTypeId+"\"/> <select onchange=\"populateTicketQty(this.name);checkSelectedTicket();\" class=\"ticketType\" name=\"ticketType_"+ticketTypeId+"\"><option></option>";
			foundCurrSelTicket = 0;
			for(i=0;i<ticketsToLoop;i++){
				
				
				ticketNode=ticketsNode.getElementsByTagName('ticket')[i];
				ticketTypesLen = ticketNode.getElementsByTagName('type').length;
				foundTicketData = 0;

				for(j=0;j<ticketTypesLen;j++){
					if(ticketTypeName==getElementTextNS("", "type", ticketNode, j)){
						ticketTypeId = getAttributeTextNS("", "type", ticketNode, j,"id");
						ticketTypePrice = getAttributeTextNS("", "type", ticketNode, j,"price");			
						foundTicketData = 1;
						break;
					}
				}
				if(foundTicketData==1){
										
					className = getAttributeTextNS("", "ticket", ticketsNode, i,"class");
					maxPurchaseAmount = getAttributeTextNS("", "ticket", ticketsNode, i,"maxPurchaseAmount");
					ticketsLeft = getAttributeTextNS("", "ticket", ticketsNode, i,"ticketsLeft");
					dataStr=dataStr+"<option value=\""+className+"\">"+className+" - $"+ticketTypePrice+"</option>";
				}
			}
			dataStr = dataStr+"</select></td>";
			
			dataStr = dataStr+"<td id=\"ticketQtyContainer_"+ticketTypeId+"\"><select disabled=\"1\" class=\"ticketQty\" name=\"ticketQty_"+ticketTypeId+"\"><option></option></select></td><td id=\"ticketPriceContainer_"+ticketTypeId+"\">&nbsp;</td>";
			dataStr = dataStr+"<td class=\"ticketTypesTdCenter\"><img id=\"ticketAvailIcon_"+ticketTypeId+"\" src=\"wsimages/eventNullAvailIcon.gif\" alt=\"ticket availablity\" /></td></tr>";
	}
	dataStr = 	dataStr+"</table>";

	htmlStr = htmlStr+"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"bookingFormElement\" >";
	htmlStr = htmlStr+"<tr><td valign=\"top\"><img src=\"wsimages\/eventTicketPurchaseStep3Red.gif\" alt=\"Step 3\"><\/td>";
	htmlStr = htmlStr+"<td class=\"bookingFormField\" valign=\"top\">";
 	htmlStr = htmlStr+dataStr+"<\/td><\/tr><\/table>";

	//debug(htmlStr);
 	document.getElementById("step3Container").innerHTML = htmlStr;
 	document.getElementById("bookingProgressImg").src = "wsimages/eventTicketPurchaseStep3.gif";
}

// Step 3 to Step 4 - parse the XML returned containing the available postage types

function parsePostageTypesData(){
	// get parent node to read
	xmlDoc = xmlhttp.responseXML;
	var htmlStr = "";
	optionsStr = "";
	
	typesToLoop=xmlDoc.getElementsByTagName('type').length;
	typesNode=xmlDoc.getElementsByTagName('postageTypes')[0];
	postageTypes = new Array();
	
	for(i=0;i<typesToLoop;i++){
		eventPostageDescription = getElementTextNS("", "type", typesNode, i);
		eventPostageObjectId = getAttributeTextNS("", "type", typesNode, i,"id");
		eventPostagePrice = getAttributeTextNS("", "type", typesNode, i,"price");
		eventPostageName = getAttributeTextNS("", "type", typesNode, i,"name");
		
		optionsStr = optionsStr+"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"deliveryOption\"><tr><td valign=\"top\">";
		optionsStr = optionsStr+"<input onclick=\"completeStep(5)\" type=\"radio\" name=\"eventPostageObjectId\" value=\""+eventPostageObjectId+"\" /></td><td class=\"deliveryOptionData\" valign=\"top\">";
		optionsStr = optionsStr+"<h5>"+eventPostageName+" ($ "+eventPostagePrice+")"+"</h5>"+eventPostageDescription+"</td></tr></table>";
		postageTypes[i] = new Array();
		postageTypes[i][1] = eventPostageObjectId;
		postageTypes[i][2] = eventPostageName;		
		postageTypes[i][3] = eventPostagePrice;
	}
	
	htmlStr = htmlStr+"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"bookingFormElement\" >";
	htmlStr = htmlStr+"<tr><td valign=\"top\"><img src=\"wsimages\/eventTicketPurchaseStep4Red.gif\" alt=\"Step 4\"><\/td>";
	htmlStr = htmlStr+"<td class=\"bookingFormField\" valign=\"top\"><h4>Choose Delivery Options...<\/h4>";
 	htmlStr = htmlStr+optionsStr;
 	htmlStr = htmlStr+"<div class=\"furtherDeliveryOptions\"><a href=\""+deliveryInfoURL+"\" target=\"_blank\">Click here for further Delivery / Collection details</a></div>";
 	htmlStr = htmlStr+"<\/td><\/tr><\/table>";

 	document.getElementById("step4Container").innerHTML = htmlStr;
 	document.getElementById("bookingProgressImg").src = "wsimages/eventTicketPurchaseStep4.gif";
}

function noTicketDisplay(){

	var htmlStr = "";
	optionsStr = "";
	
	htmlStr = htmlStr+"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"bookingFormElement\" >";
	htmlStr = htmlStr+"<tr><td valign=\"top\"><img src=\"wsimages\/eventTicketPurchaseStep4Red.gif\" alt=\"Step 4\"><\/td>";
	htmlStr = htmlStr+"<td class=\"bookingFormField\" valign=\"top\">";
 	htmlStr = htmlStr+"<div class=\"furtherDeliveryOptions\">"+noTicketsMessage+"</div>";
 	htmlStr = htmlStr+"<\/td><\/tr><\/table>";

 	document.getElementById("step4Container").innerHTML = htmlStr;
 	document.getElementById("bookingProgressImg").src = "wsimages/eventTicketPurchaseStep4.gif";
 	completeStep(5);
}

// Populate the ticket quantity select for the selected ticket type and class, also show the correct image....	
function populateTicketQty(selObj){
	//alert(selObj);
	selectedTicketClass = eval("document.bookingForm."+selObj+".value");
	ticketTypeParts = selObj.split("_");
	ticketTypeId = ticketTypeParts[1];
	if(selectedTicketClass==""){
		document.getElementById("ticketAvailIcon_"+ticketTypeId).src = "wsimages/eventNullAvailIcon.gif";
		document.getElementById("ticketQtyContainer_"+ticketTypeId).innerHTML = drawQtySel(0,ticketTypeId);
	} else {
		for(i=0;i<ticketTypesData.length;i++){	
			if(ticketTypeId == ticketTypesData[i][1]){
			//	alert(ticketTypeId+"\n"+ticketTypesData[i][1]);
				if(selectedTicketClass == ticketTypesData[i][4]){
				//	alert(selectedTicketClass+"\n"+ticketTypesData[i][4]);
					maxPurchase = ticketTypesData[i][5];
					ticketsLeft = ticketTypesData[i][6];
					if(ticketsLeft>0){
						if(parseInt(ticketsLeft)<parseInt(maxPurchase)){
							maxPurchase = ticketsLeft;
						}
						document.getElementById("ticketQtyContainer_"+ticketTypeId).innerHTML = drawQtySel(maxPurchase,ticketTypeId);
						document.getElementById("ticketAvailIcon_"+ticketTypeId).src = "wsimages/eventAvailIcon.gif";
						document.getElementById("ticketAvailIcon_"+ticketTypeId).disabled = "0";
						calcPriceForType("ticketQty_"+ticketTypeId);
					}else{
						document.getElementById("ticketQtyContainer_"+ticketTypeId).innerHTML = drawQtySel(0,ticketTypeId);
						document.getElementById("ticketAvailIcon_"+ticketTypeId).src = "wsimages/eventNotAvailIcon.gif";
						document.getElementById("ticketAvailIcon_"+ticketTypeId).disabled = "1";
					}
					break;
				}
			}
		}
	}	
}

// build the HTML string for the populateTicketQty function.	
function drawQtySel(maxPurchase,ticketTypeId){
	maxPurchaseSel = "";

	for(n=1;n<parseInt(maxPurchase)+1;n++){
		sel="";
		if(n==1){
			sel="selected=\"1\" ";
		}
		maxPurchaseSel = maxPurchaseSel+"<option "+sel+" value=\""+n+"\">"+n+"</option>";
	}
	disabledSel = "";
	if(maxPurchaseSel==0){
		disabledSel = " disabled=\"1\" ";
	}
	return htmlStr="<select onchange=\"calcPriceForType(this.name);checkSelectedTicket();\" "+disabledSel+" class=\"ticketQty\" name=\"ticketQty_"+ticketTypeId+"\"><option>&nbsp;</option>"+maxPurchaseSel+"</select>";
}

function calcPriceForType(selObj){
	ticketQtyParts = selObj.split("_");
	selectedTicketTypeId = ticketQtyParts[1];
	selectedTicketQty = eval("document.bookingForm."+selObj+".value");
	selectedTicketClass = eval("document.bookingForm.ticketType_"+selectedTicketTypeId+".value");	
	if(selectedTicketQty!=""){
		for(i=0;i<ticketTypesData.length;i++){
			
			if(selectedTicketTypeId == ticketTypesData[i][1]){
				if(selectedTicketClass == ticketTypesData[i][4]){

					ticketPrice = ticketTypesData[i][3];
	
					totalPrice = ticketPrice*parseInt(selectedTicketQty);
					document.getElementById("ticketPriceContainer_"+selectedTicketTypeId).innerHTML = "$"+dollarFormat(totalPrice);
				}
			}
		}
	}else{
		document.getElementById("ticketPriceContainer_"+selectedTicketTypeId).innerHTML = "";
	}
}
			
// Check to see if some tickets have been selected and if so then call the next step, otherwise call the step clearing function.
function checkSelectedTicket(){
	formObj = document.bookingForm;
	// kind of crappy but need to get the individual id by looping over the unique names
	// and then looping over the ticket data to get the id after finding a match...

	for(k=0;k<ticketTypesArray.length;k++){
	
		ticketTypeName = ticketTypesArray[k];
		ticketsLeft = 1;
		openStep = 0;
		
		for(m=0;m<ticketTypesData.length;m++){
			if(ticketTypesData[m][2] == ticketTypeName){
				ticketTypeId = ticketTypesData[m][1];
				break;
			}
		}
		ticketQty = eval("formObj.ticketQty_"+ticketTypeId+".value");
		ticketType = eval("formObj.ticketType_"+ticketTypeId+".value");
		if(ticketType!=""){
			if(ticketQty!=""){
				openStep = 1;
				break;
			} else {
				openStep = 0;
			}
		} else {
			openStep = 0;
		}
	}
	
	if(openStep==1){
		completeStep(4);
	} else {
		clearSteps(4);	
	}
}

// Total the selected tickets and present the cart/checkout options
function checkOutOptions(){
	formObj = document.bookingForm;
	performanceDateTime = formObj.performanceDateTime.value;
	venueId = formObj.venueId.value;
	eventId = formObj.eventId.value;
	var htmlStr = "";
	var totalPrice = 0;
	// Get the total of the selected tickets
	
	for(k=0;k<ticketTypesArray.length;k++){
	
		ticketTypeName = ticketTypesArray[k];
		for(m=0;m<ticketTypesData.length;m++){
			if(ticketTypesData[m][2] == ticketTypeName){
				ticketTypeId = ticketTypesData[m][1];
				break;
			}
		}
		ticketQty = eval("formObj.ticketQty_"+ticketTypeId+".value");
		ticketClass = eval("formObj.ticketType_"+ticketTypeId+".value");
		
		if(ticketQty!=""){
			for(i=0;i<ticketTypesData.length;i++){
				if(ticketTypeId == ticketTypesData[i][1]){
					if(ticketClass == ticketTypesData[i][4]){
						ticketPrice = ticketTypesData[i][3];
						totalPrice = totalPrice+(ticketPrice*parseInt(ticketQty));
					}
				}
			}
		}
	}
	
	// Get the postage
	postageCost = 0;
	if(bNoTickets==0){
		for(j=0;j<formObj.eventPostageObjectId.length;j++){
			if(formObj.eventPostageObjectId[j].checked==true){
				postageTypeId = formObj.eventPostageObjectId[j].value;
				
				for(m=0;m<postageTypes.length;m++){
					if(postageTypes[m][1] == postageTypeId){
						postageCost = postageTypes[m][3];
						postageCost = postageCost*1;
						break;
					}
				}
				break;
			}
		}
	}
	
	totalPrice = totalPrice+postageCost;
	totalPrice = dollarFormat(totalPrice);
	
	htmlStr = htmlStr+"<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"bookingFormElement\" >";
	htmlStr = htmlStr+"<tr><td valign=\"top\"><img src=\"wsimages\/eventTicketPurchaseStep5Red.gif\" alt=\"Step 5\"><\/td>";
	htmlStr = htmlStr+"<td class=\"bookingFormField\" valign=\"top\"><h4>Go to Checkout or Add Booking/s to Your Shopping Cart...<\/h4>";
	htmlStr = htmlStr+"<h5>Total Event Cost $"+totalPrice+"</h5>";
	htmlStr = htmlStr+"<div><a href=\"javascript:cartAction('checkout');\"><img src=\"wsimages\/eventTicketChkOutBtn.gif\" border=\"0\" alt=\"Check Out\" align=\"absmiddle\"></a>";
	htmlStr = htmlStr+"&nbsp;&nbsp;<b>or</b>&nbsp;&nbsp;<a href=\"javascript:cartAction('addToCart');\"><img src=\"wsimages/eventTicketAddToCartBtn.gif\" border=\"0\"alt=\"Add to Cart\"  align=\"absmiddle\"></a></div>";
//	htmlStr = htmlStr+"<div><b>Note:</b> Booked items in Shopping Cart will automatically be removed after 15 minutes of inactivity.</div>";
 	htmlStr = htmlStr+"<\/td><\/tr><\/table>";

	//debug(htmlStr);
 	document.getElementById("step5Container").innerHTML = htmlStr;
 	document.getElementById("bookingProgressImg").src = "wsimages/eventTicketPurchaseStep5.gif";
}

function dollarFormat(numb){

  if (parseFloat(numb)){
    if (numb== Math.round(numb)){
      return ( numb + ".00")
    }
    else {
      numb=(numb + "0");
      return (numb.substring(0,(numb.indexOf(".")+3)))
    }
  }
  else{
    return "0.00"
  }
}

function cartAction(action){
	formObj = document.bookingForm;
	if(action=="checkout"){
		formObj.action = checkOutURL;
	}
	formObj.submit();
}

function debug(str){
	document.getElementById("debug").innerHTML = "<xmp>"+str+"</xmp>";

}




