function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

function searchCalendar(year,month,newLocation) {

	if (year === null){
		year  = $('year').getValue();
		month = $('month').getValue();
	} else {
		$('year').setValue(year);
		$('month').setValue(month);
	}
	
	$('location').setValue(newLocation);
	$('calendarContainer').hide();
	$('calendarLoadingMessage').show();
	
	$$('.calNavMonth').each(function(item){item.removeClassName('tCalTabNavOn');});
	if (month < 10) {
		$('calNavMonth_' + year + "_" + month).addClassName('tCalTabNavOn');
	} else {
		$('calNavMonth_' + year + "_" + month).addClassName('tCalTabNavOn');
	}
	
//	$$('.calNavYear').each(function(item){item.removeClassName('tCalYearTabNavOn');});
//	$('calNavYear' + year).addClassName('tCalYearTabNavOn');	
	
//	$$('.calNavLocation').each(function(item){item.removeClassName('tCalLocationTabNavOn');});
//	$('calNavLocation' + newLocation).addClassName('tCalLocationTabNavOn');	
	
	
	new Ajax.Updater('calendarContainer', '/h/tessitura/ShowCalendar', 
    { 	evalScripts: false, 
        method: 'get', 
        parameters: {nonav:'1',year:year,month:month,location:newLocation},
		onSuccess: function(response){
			$('calendarLoadingMessage').hide();
			$('calendarContainer').show();
			// Create a date object on the 5th to avoid timezone related issues
			var d = new Date(year,month-1,5);
			$('calNavCurrentMonthLabel').update(formatDateForNavTab(d));
		}
	});
	$('dropdownMenu').hide();
}

function formatDateForNavTab(d){
	var monthname=new Array(7);
	monthname[0]="January";
	monthname[1]="Februrary";
	monthname[2]="March";
	monthname[3]="April";
	monthname[4]="May";
	monthname[5]="June";
	monthname[6]="July";	
	monthname[7]="August";	
	monthname[8]="September";	
	monthname[9]="October";	
	monthname[10]="November";	
	monthname[11]="December";	

	var monthNum = d.getUTCMonth();
	var yearNum  = d.getUTCFullYear();
	return monthname[monthNum] + " " + yearNum;
}

function getThisMonth(year,month) {
	if (year === null){
		year  = $('year').getValue();
		month = $('month').getValue();
	} else {
		$('year').setValue(year);
		$('month').setValue(month);
	}
	
	keyword = $('keyword').getValue();
	
	$('calendarMonthContainer').hide();
	$('calendarLoadingMessage').show();
	$$('.calNavMonth').each(function(item){item.removeClassName('calNavMonthCurrent');});
	if (month < 10) {
		$('calNavMonth_' + year + '_0' + month).addClassName('calNavMonthCurrent');	
	} else {
		$('calNavMonth_' + year + '_' + month).addClassName('calNavMonthCurrent');	
	}
	new Ajax.Updater('calendarMonthContainer', '/h/tessitura/ShowCalendar', 
	{ 	evalScripts: false, 
			method: 'get', 
			parameters: {nonav:'1',year:year,month:month,keyword:keyword,view:'list'},
	onSuccess: function(response){
		$('calendarLoadingMessage').hide();
		$('calendarMonthContainer').show();
		var d = new Date(year,month-1,5);
		$('calNavCurrentMonthLabel').update(formatDateForNavTab(d));
	}
});
}

var globalDialog = null;
var globalDialog2 = null;

function dialogOpenTest(){
	globalDialog = new  Dialog({
			title:"dialogOpenTest",
			opacity:0.50,
			width:400,
			height:300,
			padding:0,
			margin:0,
			background:["#000000", "#ffffcd"],
			close:{link:true,esc:true,overlay:false},
			content:'Hello World'
	});
	globalDialog.open();
}

function showAudioPlayerDialog(title, filename){
  
	//var element = $(genID);
	var displayTitle = decodeURI(title);
	var audioSrc = filename;
	
	globalDialog = new  Dialog({
		title:displayTitle,
		opacity:0.50,
		width:363,
		height:57,
		padding:10,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="audioPlayerDiv"></div>'
	});
	
	globalDialog.open();
	
	var flashvars = {audioSrc: audioSrc};
	var params = {};
	var attributes = {};
	swfobject.embedSWF("/res/audioPlayer.swf", "audioPlayerDiv", "363", "37", "9.0.0", false, flashvars, params, attributes);
	
}

function showYouTubePlayerDialog(videoId, displayTitle){
  
  videoId = videoId.split(".")[0];
  
  var contentString = '\
  <object width="560" height="340">\
    <param name="movie" value="http://www.youtube.com/v/' + videoId +'?fs=1&amp;hl=en_US"></param>\
    <param name="allowFullScreen" value="true"></param>\
    <param name="allowscriptaccess" value="always"></param>\
    <embed src="http://www.youtube.com/v/' + videoId +'?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed>\
  </object>';
  
	globalDialog = new Dialog({
		title:displayTitle,
		opacity:0.50,
		width:560,
		height:340,
		padding:10,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},
		content:contentString
	});
	
	globalDialog.open();	
}


function showYouTubePlayerDialogEventDetail(title, id){
	showYouTubePlayerDialog(id, decodeURI(title));
}

function showSYOSDialog(houseid,type,id){
	globalDialog2 = new  Dialog({
			title:"Select Your Own Seat",
			opacity:0.50,
			width:860,
			height:571,
			padding:10,
			margin:0,
			background:["#000000", "#ffffcd"],
			close:{link:true,esc:true,overlay:false},
			content:'<div id="syosDialog"></div>',
			afterOpen:function(){
			new Ajax.Updater(
				'syosDialog', 
				'/h/tessitura/SYOSTool', { evalScripts: true,
											method: 'get',
											parameters: {
											houseid:houseid,
											type:type,
											id:id}
											});
			}
	});
	globalDialog2.open();
}

function showChooseSeatsDialog(perfid) {
	globalDialog = new Dialog({
		title:"Book Tickets - Seating Options",
		opacity:0.50,
		width:600,
		height:520,
		padding:0,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="chooseSeatsDialog">Loading...</div><div id="chooseSeatsDialogLoading" class="ml20 mr20 mb20" style="display: none;">Loading...</div>',
		afterOpen:function(){
		new Ajax.Updater(
			'chooseSeatsDialog', 
			'/h/tessitura/showChooseSeats', { evalScripts: true,
										method: 'get',
										parameters: {perfid:perfid}
										});
		}	});
	globalDialog.open();
}

function showFixedPackageSeating(pkgno) {
	globalDialog = new Dialog({
		title:"Package - Seating Options",
		opacity:0.50,
		width:600,
		height:520,
		padding:0,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="chooseSeatsDialog">Loading...</div><div id="chooseSeatsDialogLoading" class="ml20 mr20 mb20" style="display: none;">Loading...</div>',
		afterOpen:function(){
		new Ajax.Updater(
			'chooseSeatsDialog', 
			'/h/tessitura/showChooseSeatsPackage', { evalScripts: true,
										method: 'get',
										parameters: {pkgno:pkgno}
										});
		}	});
	globalDialog.open();
}


function showGiftCertOptionsDialog(gcno) {
	globalDialog = new Dialog({
		title:"Gift Voucher Delivery Options",
		opacity:0.50,
		width:600,
		height:700,
		padding:0,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="gcOptionsDialog">Loading...</div>',
		afterOpen:function(){
		new Ajax.Updater(
			'gcOptionsDialog', 
			'/h/tessitura/showGiftCertOptions', { evalScripts: true,
										method: 'get',
										parameters: {gcno:gcno}
										});
		}	});	
	globalDialog.open();
}

function fadeGCButton(gcno) {
	$('deliveryBtn' + gcno).fade();
}

function updateArtists(perfno) {
	if (!$('content_artists').visible()) {
		toggleObject('artists');
	}
	new Effect.SlideDown('artistsContentLoading');
	new Effect.SlideUp('artistsContent');
	new Ajax.Updater('artistsContent','/h/tessitura/GetArtists',
	{
		method: 'get',
		parameters: {perfno:perfno},
		evalScripts: false,
		onSuccess: function(response) {
			new Effect.SlideUp('artistsContentLoading');
			new Effect.SlideDown('artistsContent');
		}
	});
	return false;
}

function submitPostGiftCert() {
	new Ajax.Updater('gcOptionsDialog','/h/tessitura/PostGiftCertificate', 
	{
		method: 'get',
		parameters: $('postDetailsForm').serialize(true),
		evalScripts: true
	});	
	return false;
}

function submitEmailGiftCert() {
	new Ajax.Updater('gcOptionsDialog','/h/tessitura/EmailGiftCertificate', 
	{
		method: 'get',
		parameters: $('emailDetailsForm').serialize(true),
		evalScripts: true
	});	
	return false;
}

function showZonePricing(){
	return false;
	
	// Get the selected zoneid
	// var zoneid = $('zoneid').getValue();
	// if (zoneid === "") {
		// zoneid = "All";
	// }

	// Hide all of the zonePricing nodes
	// $$('.zonePricing').each(function(item){item.hide();});
	
	// Show all of the zonePricing nodes for the selected zone
	// $$('.zonePricingForZone' + zoneid).each(function(item){
	// item.show();
	// new Effect.Highlight(item)
	// });
	
	// $('zonePricingInitial').hide();
	// $('zonePricingMessage').show();
}

function showShippingMethodsDialog() {
	globalDialog = new  Dialog({
		title:"Add a new shipping address",
		opacity:0.50,
		width:300,
		height:400,
		padding:0,
		margin:0,
		background:["#000000", "#ffffff"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="shippingMethodsDialog" style="padding: 15px 25px;"></div>',
		afterOpen:function(){
			new Ajax.Updater(
			'shippingMethodsDialog', 
			'/h/tessitura/ShippingMethodsDialog', { evalScripts: true, method: 'get'}
			);
		}
	});
	globalDialog.open();  
}

function submitLoginDialog(sourceDivID) {
	new Ajax.Updater(sourceDivID, '/h/tessitura/LoginDialog', 
		{
			parameters : $('login').serialize(true),
			method : 'post'
		});
}

// toggleTab for Event Detail pages
var prevTabID = 'Description';

function toggleTab(TabID) {
  $('tab' + prevTabID).className = 'option';
  $('eventDetail' + prevTabID).className = 'displayNone';


  //APPLY THE ACTIVE STYLE TO THE SELECTED TAB
  $('tab' + TabID).className = 'optionOn';
  $('eventDetail' + TabID).className = 'displayBlock';

  prevTabID = TabID;
}


// Toggle layer
function toggleLayer(prefix, id) {
	if ($(prefix + 'Layer_' + id).readAttribute('style').include('display: none')) {
		$(prefix + 'Layer_' + id).show();
		$(prefix + 'Toggler_' + id).writeAttribute('src', $(prefix + 'Toggler_' + id).readAttribute('src').sub('open', 'close'));
		$(prefix + 'Toggler_' + id).writeAttribute('alt', 'Close');
	} else {
		$(prefix + 'Layer_' + id).hide();
		$(prefix + 'Toggler_' + id).writeAttribute('src', $(prefix + 'Toggler_' + id).readAttribute('src').sub('close', 'open'));
		$(prefix + 'Toggler_' + id).writeAttribute('alt', 'Open');
	}
}

// Submit Finalize
function submitFinalizeForm() {
	if ( $F('wassubmitted') == '1' ) {
		alert("Please be patient while we process your transaction.");
	}
	$('wassubmitted').setValue('1');
	$('finalize').submit();
}

// Submit Login
function submitLoginForm() {
	$('loginform').submit();
}

// Submit Brochure Request Form
function submitRequestBrochuresForm() {
	$('RequestBrochures').submit();
}

// Submit Change Password
function submitChgPWForm() {
	$('ChangePassword').submit();
}

function submitAddShipping() {
	new Ajax.Updater('shippingMethodsDialog','/h/tessitura/AddShippingAddressAJAX', 
	{
		method: 'get',
		parameters: $('addShippingAddressForm').serialize(true),
		evalScripts: true
	});	
	return false;
}

function CheckTicketQtyAndSubmitBuyTix() {
	
	var numValidPriceTypes = $$('.ticketQtySelect').any( function(n) {return n.getValue() > 0;} );
	if (numValidPriceTypes) {
		$('selectNumberSeats').hide();
		$('seatingOptions').hide();
		$('seatingOptionsLoading').show();
		new Ajax.Updater('chooseSeatsDialog','/h/tessitura/BuyTix',
		{
			method: 'get',
			parameters: $('buyTix').serialize(),
			evalScripts: true
		});
	} else {
		$('selectNumberSeats').show();
	}
}

function updateShippingMethods(shippingmethod) {
	new Ajax.Updater('tAJAXshippingmethods','/h/tessitura/shippingMethods', 
	{
		method: 'get',
		evalScripts: false,
		parameters: {shippingmethod:shippingmethod}
	});
}

function changeShippingMethod() {
	shippingMethodId = $F('shippingMethodField');
	container = $('collectingCustomerContainer');
	
	if ( shippingMethodId.startsWith('-1;') ) {
		container.show();
	} else {
		container.hide();
	}
	
	
}

function updateFieldValue(field,amt) {
document.getElementById(field).value = amt;
}

function resetRadios(name) {
var radios = document.getElementById(name);
if (radios) {
  var inputs = radios.getElementsByTagName ('input');
  if (inputs) {
    for (var i = 0; i < inputs.length; ++i) {
     inputs[i].checked=false;
    }
  }
}
}
	
function updateAddedSecondSubscribers() {
	new Ajax.Updater('tAJAXaddedsecondsubscribers','/h/tessitura/ShowAddedSubscribers', 
	{
		method: 'get',
		evalScripts: false
	});
}

function textCounter( field, countfield, maxlimit ) {
  if ( field.value.length > maxlimit )
  {
    field.value = field.value.substring( 0, maxlimit );
    alert( 'Comments value can only be 255 characters in length.' );
    return false;
  }
  else
  {
    countfield.value = maxlimit - field.value.length;
	return false;
  }
}

function hide_selector(url)
{
 document.getElementById('tEventDetailChooseSeats').style.display = 'none';
 document.getElementById('tEventDetailChooseSeatsSearching').style.display = 'block';
 if (url !== '')
 {
  location.href = url;
 }
}
function show_seatchart()
{
 document.getElementById('tEventDetailChooseSeatsSeatMapWrapper').style.display = '';
 document.getElementById('tEventDetailChooseSeatsSeatMapWrapperBackground').style.display = '';
 document.getElementById('tEventDetailChooseSeatsForm').style.display = 'none';
}
function hide_seatchart()
{
 document.getElementById('tEventDetailChooseSeatsSeatMapWrapper').style.display = 'none';
 document.getElementById('tEventDetailChooseSeatsSeatMapWrapperBackground').style.display = 'none';
 document.getElementById('tEventDetailChooseSeatsForm').style.display = '';
}

function toggleBestAvailable() {
  document.getElementById('chooseSeatingOptions').className = 'displayNone';
  document.getElementById('chooseBestAvailable').className = 'displayBlock';
}

function toggleSubscriptionInfo(tagId) {
  if (tagId == 'subscriptionPerformancePkg') {
    $('tabseatingOptions').className = '';
    $('tabsubscriptionPerformancePkg').className = 'on';
    $('seatingOptions').hide();
    $('subscriptionPerformancePkg').show();
  } else {
    $('tabsubscriptionPerformancePkg').className = '';
    $('tabseatingOptions').className = 'on';
    $('subscriptionPerformancePkg').hide();
    $('seatingOptions').show();
  }
}

function loadSeasonOverview(season, category, location) {
	$('seasonListingContent').hide();
	$('seasonListingLoading').show();
	new Ajax.Updater(
		'seasonListingDiv', 
		'/h/tessitura/seasonOverviewList', { evalScripts: true, method: 'get', parameters: {season: season, category: category, location: location} }
	);
}

function changeSeason(oldSeason, newSeason) {
	$(oldSeason + '_btn').src = '/img/btn_' + oldSeason + '.gif';
	$(newSeason + '_btn').src = '/img/btn_' + newSeason + '_on.gif';
	$('seasonCategories_' + oldSeason).hide();
	$('seasonCategories_' + newSeason).show();
	$('season').setValue(newSeason);
	$$('.on').each(function(item){item.removeClassName('on');});
	$(newSeason + '_Main company_link').addClassName('on');
	$('category').setValue('Main company');
	$('location').setValue('');

}

function changeEventDetailPage(newPage) {
	if (newPage !== '') {
		if (newPage.indexOf('perf') > -1) {
			location.href = '/whats_on/event_detail?perfid=' + newPage.substring(4);
		} else {
			location.href = '/whats_on/event_detail?prodid=' + newPage.substring(4);
		}
	}
}

function loadURL(element_id) {
	location.href = $F(element_id);
}

function changeCategory(newCategory) {
	$$('.on').each(function(item){item.removeClassName('on');});
	var season = $('season').value;
	$(season + "_" + newCategory + "_link").addClassName('on');
	$('category').setValue(newCategory);
	$('location').setValue('');
	loadSeasonOverview(season, newCategory, $('location').value);
}

function changeLocation(newLocation) {
	$('location').setValue(newLocation);
	loadSeasonOverview($('season').value, $('category').value, newLocation);
}


// Event Detail Slideshow Start
var _currSlideshowImageIndex = 0;
var _slideshowButtons; // array;
var _slideshowTimer;

function initSlideshow() {
  
  var detailSlideshowImages = $$(".detailSlideshowImage");
  
  if (detailSlideshowImages.length) {
    
    $("detailSlideshowContainer").setStyle({display:"block"});
    
    detailSlideshowImages[0].appear({duration: 0.3});
    
    if (detailSlideshowImages.length > 1) {
      
      _slideshowButtons = [];
      
      $("detailSlideshowControlBarBackgroundWhite").setOpacity(0.25);
      $("detailSlideshowControlBarBackgroundBlack").setOpacity(0.5);
      
      $("detailSlideshowControlBar").setStyle({display:'block'});
      
      var detailSlideshowControls = $("detailSlideshowControls");
      
      for (var i=0; i < detailSlideshowImages.length; i++) {
        var button = new Element("div").addClassName("detailSlideshowControl").update(i + 1);
        detailSlideshowControls.insert({top:button});
        button.observe("click", doSlideshowButtonClick.curry(i));
        _slideshowButtons.push(button);
        
        if (i === 0) button.addClassName("detailSlideshowControlCurrent");
      }
      
      _slideshowTimer = setInterval(doSlideshowTimer, 6000);
    }
  }
}

function doSlideshowButtonClick(index, event) {
  if (index != _currSlideshowImageIndex) {
    showSlideshowImage(index);
    _currSlideshowImageIndex = index;
    clearInterval(_slideshowTimer);
  }
}

function showSlideshowImage(index) {
  var images = $$(".detailSlideshowImage");
  
  _slideshowButtons[_currSlideshowImageIndex].toggleClassName("detailSlideshowControlCurrent");
  _slideshowButtons[index].toggleClassName("detailSlideshowControlCurrent");
  
  fadeOutImage(images[_currSlideshowImageIndex]);
  fadeInImage(images[index]);
}

function fadeOutImage(element) {
  element.fade({ duration: 0.3 });
}

function fadeInImage(element) {
  element.appear({duration: 0.3, delay: 0.3});
}

function doSlideshowTimer() {
  var newIndex = _currSlideshowImageIndex + 1;
  if (newIndex > _slideshowButtons.length - 1) newIndex = 0;
  showSlideshowImage(newIndex);
  _currSlideshowImageIndex = newIndex;
}

function showTabAJAXMyAccount(tab) {
	$('sectionContainer').innerHTML="";
	$('sectionLoadingMessage').show();
	new Ajax.Updater('sectionContainer', '/h/tessitura/Show' + tab, 
    { 	evalScripts: false, 
        method: 'get', 
        parameters: {},
		onSuccess: function(response){
			$('sectionLoadingMessage').hide();
		}, 
		onComplete: function() {
		}
	});
}

function toggleTab(prefix, id) {
	$$('.' + prefix + '_layer').each(function(item){item.hide();});
	if ($(prefix + 'l_' + id)) {
		$(prefix + 'l_' + id).show();
	}

	$$('.' + prefix).each(function(item){item.removeClassName('thisTabOn');});
	$(prefix + 't_' + id).addClassName('thisTabOn');
}

// Event Detail Slideshow End

function submitPriceTypes(automaticallyTriggered) {
	//$('tShowNFSPackageFormDetails').appear();
	//$('tShowNFSPackageFormPerformances').appear();
	//new Effect.SlideUp('tShowNFSPackagePriceTypes');
	
	var serializedForm = $H($('NFSPriceTypes').serialize(true));
	
	var userCanProceed = false;
	serializedForm.each(function(pair){
	  if (pair.key.include("tixqty")) {
	    if (pair.value != '0') userCanProceed = true;
	  }
	}, this);
	
	if (userCanProceed) {
	  
	  if (automaticallyTriggered) {
  	  $('tShowNFSPackageFormDetails').show();
    	$('tShowNFSPackageFormPerformances').show();
    	$('tShowNFSPackagePriceTypes').hide();
	  } else {
	    $('tShowNFSPackagePriceTypesSettingUp').show();
	  }

  	new Ajax.Updater('tShowNFSPackagePriceTypes', '/h/tessitura/ShowNFSPackageSummary', 
  	{ 	
  		evalScripts: true, 
          method: 'get', 
          parameters: serializedForm,
  		onSuccess: function(response){

  		}, 
  		onComplete: function() {
    	  $('tShowNFSPackageFormDetails').show();
      	$('tShowNFSPackageFormPerformances').show();
      	$('tShowNFSPackagePriceTypes').hide();
      	$('tShowNFSPackagePriceTypesSettingUp').remove();
  			globalDialog.close();
  		}
  	});
	  
	}
	
	return false;
}

// NFS-related
var okToReserve = true;

function showNFSPackagePriceTypes() {
	//new Effect.SlideUp('tShowNFSPackagePriceTypesLoading');
	//new Effect.SlideDown('tShowNFSPackagePriceTypes');
	$('tShowNFSPackagePriceTypesLoading').hide();
	$('tShowNFSPackagePriceTypes').show();
}

function addNFSPerformance(perfno) {
	if (okToReserve === true) {
		var form = $('buyTix'+perfno);
		var perfNoToBuy = form['perfno'];
		var perfGroupNoToBuy = form['perfgroupno'];
		var zoneIDToBuy = form['zoneid'];
		
		if ($F(zoneIDToBuy) == '') return;
    
		okToReserve = false;
		$("tShowNFSPackageFormPerformanceAdding" + perfno).show();
		
		$('perfno').setValue($F(perfNoToBuy));
		$('perfgroupno').setValue($F(perfGroupNoToBuy));
		$('zoneid').setValue($F(zoneIDToBuy));
		
		//new Effect.SlideUp('tShowNFSPackageFormPerformanceAdd'+perfno);
		//new Effect.SlideDown('tShowNFSPackagePriceTypesLoading');
		//new Effect.SlideUp('tShowNFSPackagePriceTypes');
		$('tShowNFSPackageFormPerformanceAdd'+perfno).hide();
		$('tShowNFSPackagePriceTypesLoading').show();
		//$('tShowNFSPackagePriceTypes').hide();

		new Ajax.Updater('tShowNFSPackageFormPerformance'+perfno, '/h/tessitura/BuyTix',
		{
			evalScripts: true, 
			method: 'get', 
			parameters: $('NFSPriceTypes').serialize(true),
			onSuccess: function(response){

			}, 
			onComplete: function() {
				new Effect.Highlight('tShowNFSPackageFormPerformance'+perfno);
			}
		});
	} else {
	globalDialog = new  Dialog({
		title:"Please Wait...",
		opacity:0.50,
		padding: 0,
		margin: 0,
		background:["#000000", "#ffffff"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="waitingDialog" style="padding: 15px 25px;">We are still reserving your previous tickets.</div>'
	});
	globalDialog.open();  
	}
}

function removeNFSPerformance(nfspkgno, perfno, perfLIID) {
  
	//new Effect.SlideUp('tShowNFSPackageFormPerformanceAdd'+perfno);
	//new Effect.SlideDown('tShowNFSPackagePriceTypesLoading');
	//new Effect.SlideUp('tShowNFSPackagePriceTypes');
	$('tShowNFSPackageFormPerformanceAdd'+perfno).hide();
	$('tShowNFSPackagePriceTypesLoading').show();
	//$('tShowNFSPackagePriceTypes').hide();
	
	new Ajax.Updater('tShowNFSPackageFormPerformance'+perfno, '/h/tessitura/RemoveNFSPackageItem',
	{
		evalScripts: true,
		method: 'get',
		parameters: {nfspkgno: nfspkgno, perfno:perfno, performanceLineItemID:perfLIID },
		onSuccess: function() {
			new Ajax.Updater('tShowNFSPackagePriceTypes', '/h/tessitura/ShowNFSPackageSummary', 
			{ 	
				evalScripts: true, 
				method: 'get', 
				parameters: $('NFSPriceTypes').serialize(true),
				onSuccess: function(response){
				
				}, 
				onComplete: function() {
				}
			});
			new Effect.Highlight('tShowNFSPackageFormPerformance'+perfno);
		}
	});
}

function refreshSummary() {
	new Ajax.Updater('tShowNFSPackagePriceTypes', '/h/tessitura/ShowNFSPackageSummary', 
	{ 	
		evalScripts: true, 
		method: 'get', 
		parameters: $('NFSPriceTypes').serialize(true),
		onSuccess: function(response){
      
		}, 
		onComplete: function() {
			okToReserve = true;
			new Effect.Highlight('tShowNFSPackagePriceTypes', { startcolor: '#ffff99', endcolor: '#EFEFEF' });
		}
	});
}

function showWaitingDialog() {
	globalDialog = new  Dialog({
		title:"Please Wait...",
		opacity:0.50,
		padding: 0,
		margin: 0,
		background:["#000000", "#ffffff"],
		close:{link:false,esc:false,overlay:false},
		content:'<div id="waitingDialog" style="padding: 15px 25px;">We are setting up your package.</div>'
	});
	//console.log(globalDialog);
	globalDialog.open();  
}

function hideFundDescriptions() {
  $$(".fund_description").each(function(item){item.hide();});
}

function showCVVDialog() {
	globalDialog = new  Dialog({
		title:"CVV Help",
		opacity:0.50,
		padding: 0,
		margin: 0,
		background:["#000000", "#ffffff"],
		close:{link:true,esc:true,overlay:false},
		target: {id:"cvvDescription"}
	});
	globalDialog.open();  
}

function submitPromoCode(eventid) {
	$('chooseSeatsDialog').toggle();
	$('chooseSeatsDialogLoading').toggle();
	new Ajax.Updater('chooseSeatsDialog', '/h/tessitura/EnterPromoCode',
	{
		evalScripts: true,
		method: 'get',
		parameters: $('PromoCodeForm').serialize(true),
		onSuccess: function() {}, 
		onComplete: function() {
			$('chooseSeatsDialog').toggle();
			$('chooseSeatsDialogLoading').toggle();
		}
	});
}

function updateStateList() {
	var loadingMessage = new Element('p', {'class':'formlabel'}).update("Please Wait<br/>State Choices Are Loading...");
	$('tAJAXState').update(loadingMessage);
	
	'Please Wait<br/>Loading New State Options...';
	new Ajax.Updater('tAJAXState', '/h/tessitura/States', { evalScripts: true, method: 'get', parameters: { CountryID: $F('country')} });
}


function donationReminderChoiceSelected(element) {
  
  var elementParent = $(element).up(2);
  var addDonation = elementParent.identify() == "buttonAddDonation";
  
  chgLabel(element.up(1).identify());
  $("dialog-close").remove(); // disable closing the dialog once user made a choice
  
  var otherButton;
  if (addDonation) {
    //otherButton = $("buttonDontAddDonation").down(2); //cant 'getElementById' here since this whole chunk is a clone of the source still on the page
    otherButton = elementParent.next().down(2);
  } else {
    //otherButton = $("buttonAddDonation").down(2);
    otherButton = elementParent.previous().down(2);
  }
  
  otherButton.setStyle({"backgroundColor":"#CCCCCC"});
  otherButton.removeAttribute("href");
  otherButton.removeAttribute("onclick");
  
  if (addDonation) {
    $('DonateForm').submit();
  } else {
    window.location.href = _cartURL;
  }
  
}

var _cartURL;
function checkDonationStatusOnCartSubmit(cartURL) {
  
  _cartURL = cartURL;
  
  var donationFound = false;
  
  if ($("DonateForm")) {
    
    donationFound = ($F("donationEnterAmount") !== "");
    
    if (!donationFound) {
      
      if ($F("donationAmount25") || $F("donationAmount50") || $F("donationAmount75") || $F("donationAmount100")) {
        donationFound = true;
      } 
    }
    
    if (donationFound) {
            
      var content = $('donationReminderContainer').clone(true).setStyle({"display": "block"});
      
      globalDialog = new  Dialog({
        title:"Donation",
        opacity:0.50,
        padding: 0,
        margin: 0,
        width: 400,
        height: 100,
        background:["#000000", "#ffffff"],
        close:{link:true,esc:false,overlay:false},
        content:content
      });
      globalDialog.open();
      
    } else {
      
      window.location.href = _cartURL;
    }
    
  } else {
    
    window.location.href = _cartURL;
  }
}

function SubmitPaymentFormValidator(){
	smfield = $('shippingMethodField');
	if (smfield == null) {
		$('SubmitPayment').submit();	
	} else {
		sm = $F('shippingMethodField');		
		if (sm == ''){
			alert('Please select a shipping method before proceeding.');	
		} else {
			$('SubmitPayment').submit();
		}	
	}
}

function checkDonationMinimum() {
	donationEnterAmount = $('donationEnterAmount').value.replace(/,/g,'');
	
	if (donationEnterAmount === "") {
			globalDialog = new  Dialog({
			title:"Donation",
			opacity:0.50,
			padding: 0,
			margin: 0,
			width: 400,
			height: 100,
			background:["#000000", "#ffffff"],
			close:{link:true,esc:false,overlay:false},
			content:"<div class='ml20'>Please select a level to continue.</div>"
		});
		globalDialog.open();		
		return false;
	}
	
	donationSetAmount = $RF('donateOnline','donationSetAmount');
	if (donationEnterAmount < donationSetAmount)  {
		globalDialog = new  Dialog({
			title:"Donation",
			opacity:0.50,
			padding: 0,
			margin: 0,
			width: 400,
			height: 100,
			background:["#000000", "#ffffff"],
			close:{link:true,esc:false,overlay:false},
			content:"<div class='ml20'>Please enter an amount equal to or above " + $RF('donateOnline','donationSetAmount') + ".</div>"
		});
		globalDialog.open();		
		return false;
	}
	return true;
}
