var purchase_visible = false;

var toggle_purchase_req;
var total_selected_quantity = 0;

var venueImagePathStart = ROOT + "/lib/images/venues/V";
var venueImagePathEnd = ".jpg";
var img_seating_chart = document.getElementById("img_seating_chart");
var currentVenueId = -1;
var pricetypes = [];
// items used by the animate.open and animate.close calls
var mousepos;
var zoomrect;
var zone_no = -1;
var priceTypeQty = [];
var iprod_season_no = 0;
var iperf_no = 0;

var jump_to_cart = true; // when true, after succesful call to reserve tickets, we'll
						//  redirect to the cart page.

function showPricing(i,j)
{
	var x = "" + (mouseX - 15) + "px";
	var y = "" + (mouseY - 15) + "px";
	$('#img_loading').css("left", x);
	$('#img_loading').css("top", y );
	$('#img_loading').show();
	iprod_season_no = i;
	iperf_no =j;
	toggle_purchase('show');
}


function checkEnableSubmitPurchase()
{
	total_selected_quantity = 0;
	$('select.ddlzoneqty').each(
		function(i)
		{
			total_selected_quantity += parseInt( this.options[this.selectedIndex].value );
		}
	);
	if (zone_no > -1 && total_selected_quantity > 0)
		$('#btn_purchase_submit').show();
	else
		$('#btn_purchase_submit').hide();
	
}

function selectZone(iZoneNo,caller,perf_no)
{
    zone_no = iZoneNo;
    
    if (img_seating_chart == null)
        img_seating_chart = document.getElementById("img_seating_chart");
    	
	// do any manipulation of the seating chart here.
	if (img_seating_chart)
	{
		if (iZoneNo > 0)
			img_seating_chart.src = venueImagePathStart + currentVenueId + "_" + iZoneNo + venueImagePathEnd;
		else
			img_seating_chart.src = venueImagePathStart + currentVenueId + venueImagePathEnd;
    
	}
	checkEnableSubmitPurchase();
	if (typeof selectZonePostHandler == "function")
		selectZonePostHandler(iZoneNo, caller, perf_no);
}

function selectPriceTypeQty(iPriceType, iQty)
{
	priceTypeQty[iPriceType] = parseInt(iQty);
	checkEnableSubmitPurchase();
}

var GetPerformancePricingResponse;

function showPurchaseTicketsWindow( oPerformancePricing, dst )
{
	if ( oPerformancePricing )
	{
		var rslt = oPerformancePricing;
		pricetypes = rslt.PriceTypes;
		$(dst).html(rslt.PerformanceSummary + rslt.TicketPriceGrid + rslt.ZoneQuantitySelector);
		// dst.innerHTML = req.responseText;
		swidth = document.documentElement ? document.documentElement.clientWidth : self.innerWidth;
		sheight = document.documentElement ? document.documentElement.clientHeight : self.innerHeight;
		var holder = document.getElementById("reserveTicket_holder");   //$('#reserveTicket_holder').get(0);
		if (holder)
		{
			if (img_seating_chart)
				img_seating_chart.src = venueImagePathStart + rslt.VenueID + venueImagePathEnd;
			currentVenueId = rslt.VenueID;
			$('#btn_purchase_submit').hide();

			var st = getscrolltop();
			holder.style.left = "" + ((swidth / 2) - (700/2)) + "px";
			holder.style.top = "" + (st.y + (sheight / 2) - (560/2)) + "px"; // 2008-07-24 added st
			$('#img_loading').hide(); // show started in showPricing()
			mousepos = {x: mouseX, y:mouseY};
//			var reserveTicket_form = document.getElementById("reserveTicket_form");
//			if (reserveTicket_form)
//			{
//				reserveTicket_formW = parseInt(reserveTicket_form.style.width);
//				reserveTicket_formH = parseInt(reserveTicket_form.style.height);
//				zoomrect = { left:  ((swidth / 2) - (400/2)), top: ((sheight / 2) - (360/2)), width: reserveTicket_formW, height: reserveTicket_formH };
//			}
//			else
//			    zoomrect = { left: ((swidth / 2) - (400 / 2)), top: ((sheight / 2) - (360 / 2)), width: 400, height: 360 };

			zoomrect = { left: ((swidth / 2) - (400 / 2)), top: ((sheight / 2) - (360 / 2)), width: 700, height: 572 };
			animate.open(document.getElementById("reserveTicket_holder"), function() { $('#reserveTicket_holder').show(); }, document.getElementById("drawingdiv"), mousepos, zoomrect); 
		}
		$('#iprod_season_no').html("" + iprod_season_no );
		$('#iperf_no').html("" + iperf_no );
		purchase_visible = true;
		if ( document.getElementById("single_zone_marker"))
		{
			// if we find a div named like this, that means there's only 1 zone
			// so set the first to be checked.
			$('#zone-row-1').attr('checked', 'true');
		}
		// document.getElementById("btn_purchase_submit").disabled= true;
		total_selected_quantity = 0;
	}
}

function toggle_purchase(i)
{
	if (i=="show" && purchase_visible)
		return;
	
	var req;
	
	this.handler = function ()
	{
		if ( req.readyState == 4)
		{
			var dst = document.getElementById("reserveTicket_results");
			if(dst)
			{
				// alert(req.responseText);
				img_seating_chart = document.getElementById("img_seating_chart");
				var rslt = JSON.parse(req.responseText);
				try
				{
					rslt = rslt.d;
				}
				catch(Error) { /* ignore */ }
				GetPerformancePricingResponse = rslt;
				showPurchaseTicketsWindow(rslt, dst);
			}
		}
	}

	
	if (i=="show")
	{

		show_veil();
		try
		{
			req = getreq();
			req.open("POST", (  srvr + ROOT + WEBSERVICE + "GetPerformancePricing"), true);
			req.setRequestHeader("Content-Type", "application/json");
			req.onreadystatechange = this.handler;
			var qs = "{perf_no:" + iperf_no + "}";
			req.send(qs);
		}
		catch(err) 
		{
			alert(err.description?err.description:err );
		}
	}
	if(i=="hide")
	{
		animate.close($('#reserveTicket_holder').get(0), null, null, mousepos, zoomrect);
		$('#reserveTicket_holder').hide();
		hide_veil();
		purchase_visible = false;
		zone_no = -1;
		priceTypeQty = []; // create new array
	}
}

function getPurchaseQueryString()
{
	var seatQuantity = 0;
	var priceTypeToSubmit = "";
	// var o = document.getElementById("pricetype_list");
	// var ptlist = o.value;
	// var ptlistarr = ptlist.split(",");
	// alert(typeof pricetypes);
	for (x=0; x< pricetypes.length; x++ )
	{
		var i = pricetypes[x];
		if ( i > 0 )
		{
			var ptmenu = document.getElementById("pricetype_" + i );
			if (ptmenu && ptmenu.selectedIndex > 0 )
			{
				howmany = parseInt(ptmenu.options[ptmenu.selectedIndex].value);
				seatQuantity += howmany;
				for (y=0; y<howmany; y++ )
				{
					if ( priceTypeToSubmit.length > 0 )
						priceTypeToSubmit += ",";
					priceTypeToSubmit = priceTypeToSubmit + i;
				}
			}
		}
	}
	
	var zone = 0;
	// $('input[@name=\'zone_no\']').each(function() {
	// 	if (this.checked)
	// 			zone = this.value;
	// });

	// 2007-08-14: available zones now a drop down menu PAG	
	// zone = get_menu_val(document.getElementById("zone_no"));
	
	var reserveTicketRequest = {};
	reserveTicketRequest.perf_no = iperf_no;
	reserveTicketRequest.quantity = seatQuantity;
	reserveTicketRequest.pricetype = priceTypeToSubmit;
	reserveTicketRequest.zone = zone_no;
	reserveTicketRequest.specialRequests = "";
	var max_contiguous_seats = document.getElementById("max_contiguous_seats");
	if (max_contiguous_seats)
	{
		if ( max_contiguous_seats.selectedIndex > 0 )
		{
			reserveTicketRequest.specialRequests="ContiguousSeats=" + max_contiguous_seats.options[max_contiguous_seats.selectedIndex].value;
		}
	}
	
	// var qs = "price_type=" + priceTypeToSubmit + "&qty=" + seatQuantity + "&perf_no=" + iperf_no + "&zone_no=" + zone_no;
	return JSON.serialize(reserveTicketRequest);
}

function doPurchase()
{
	var req = getreq();
	this.handler = function()
	{
		if ( req.readyState < 4)
			return;
		
		// $('#img_loading2').hide();

		//alert(req.responseText);
		var result = JSON.parse(req.responseText);
		try
		{
			result = result.d;
		}
		catch(Error) { /* ignore */ }
		if ( result.Success )
		{
			// toggle_purchase('hide');
			location.href= ROOT + "/Tickets/Cart.aspx";
		}
		else if ( result == "LOGIN" )
			location.href = "/account/index.aspx";
		else 
		{
			$('#img_loading2').hide();
			toggle_purchase('hide');
			if ( result == "FAILED" )
			{
				try
				{
					ErrorMessage(ticket_request_failed); // defined in messages.js
				}
				catch(err)
				{
					ErrorMessage("We don't have the number of consecutive seats available in the section you selected. Please choose a lower quantity of seats or a different section.");
				}
			}
			else
			{
			    alert("We don't have the number of consecutive seats available in the section you selected. Please choose a lower quantity of seats or a different section.");
				//Notification("Your request could not be made. Your cart or session has expired.");
			}
		}
	
	}
	try
	{
		$('#btn_purchase_submit').hide();
		$('#img_loading2').show();
		req.open("POST", ( srvr + ROOT + WEBSERVICE + "ReserveTickets"), true);
		req.setRequestHeader("Content-Type", "application/json");
		req.onreadystatechange = this.handler;
		var qs = getPurchaseQueryString();
		// alert(qs);
		req.send(qs);
		
	}
	catch(err)
	{
		alert(err.description?err.description : err );
	}	
}


var update_pricing_req;

function update_pricing_complete()
{

}

function update_pricing(psn,perf_no)
{
	try
	{
		update_pricing_req = getreq();
		update_pricing_req.open("POST", ( srvr + "/lib/ajax/purchase/contribution.aspx"), true);
		update_pricing_req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		update_pricing_req.onreadystatechange = update_pricing_complete;
		var qs = "amt=" + escape(document.getElementById("tbx_contrib_amt").value);
		submit_contribution_req.send(qs);
	}
	catch(err)
	{
		alert(err.description?err.description:err);
	}	
}