/**
* 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,season,newLocation,variation) {

	if (year === null){
		year  = $('year').getValue();
		month = $('month').getValue();
		season = $('season').getValue();
	} else {
		$('year').setValue(year);
		$('month').setValue(month);
		$('season').setValue(season);
	}
	
	$('location').setValue(newLocation);
	$('calendarContainer').hide();
	$('calendarLoadingMessage').show();
	
	$$('.calNavMonth').each(function(item){item.removeClassName('tCalTabNavOn');});
	if ($('calNavMonth_' + year + "_" + month)) {
		$('calNavMonth_' + year + "_" + month).addClassName('tCalTabNavOn');
	}
	
	calendarPath = null;
	
	if (variation == 'Mini') {
		calendarPath = '/h/tessitura/ShowCalendarMini';
	} else {
		calendarPath = '/h/tessitura/ShowCalendar';
	}
	
	new Ajax.Updater('calendarContainer', calendarPath, 
    { 	evalScripts: false, 
        method: 'get', 
        parameters: {nonav:'1',year:year,month:month,season:season,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));
		}
	});	
}

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(element){
  
  //var element = $(genID);
  var displayTitle = element.innerHTML;
	var audioSrc = element.readAttribute("href");
	
	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(element){
  var displayTitle = element.innerHTML;
	var videoId = element.readAttribute("href");
	
	showYouTubePlayerDialog(videoId, displayTitle);
}

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:475,
		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 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(){
	// 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/showLoginDialog', 
		{
			evalScripts: true,
			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() {
	$('tShowNFSPackageFormDetails').appear();
	$('tShowNFSPackageFormPerformances').appear();
	new Effect.SlideUp('tShowNFSPackagePriceTypes');
	
	new Ajax.Updater('tShowNFSPackagePriceTypes', '/h/tessitura/ShowNFSPackageSummary', 
	{ 	
		evalScripts: true, 
        method: 'get', 
        parameters: $('NFSPriceTypes').serialize(true),
		onSuccess: function(response){
		
		}, 
		onComplete: function() {
			globalDialog.close();
		}
	});
}

// NFS-related
var okToReserve = true;

function showNFSPackagePriceTypes() {
	new Effect.SlideUp('tShowNFSPackagePriceTypesLoading');
	new Effect.SlideDown('tShowNFSPackagePriceTypes');
}

function addNFSPerformance(perfno) {
	if (okToReserve === true) {
		okToReserve = false;
		var form = $('buyTix'+perfno);
		var perfNoToBuy = form['perfno'];
		var perfGroupNoToBuy = form['perfgroupno'];
		var zoneIDToBuy = form['zoneid'];
		$('perfno').setValue($F(perfNoToBuy));
		$('perfgroupno').setValue($F(perfGroupNoToBuy));
		$('zoneid').setValue($F(zoneIDToBuy));
		
		// new Effect.SlideDown('tShowNFSPackageFormPerformanceContainer'+perfno+'Loading');
		// new Effect.SlideUp('tShowNFSPackageFormPerformanceContainer'+perfno);
		new Effect.SlideUp('tShowNFSPackageFormPerformanceAdd'+perfno);

		new Effect.SlideDown('tShowNFSPackagePriceTypesLoading');
		new Effect.SlideUp('tShowNFSPackagePriceTypes');

		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.SlideDown('tShowNFSPackageFormPerformanceContainer'+perfno+'Loading');
//	new Effect.SlideUp('tShowNFSPackageFormPerformanceContainer'+perfno);
	new Effect.SlideUp('tShowNFSPackageFormPerformanceAdd'+perfno);
	
	new Effect.SlideDown('tShowNFSPackagePriceTypesLoading');
	new Effect.SlideUp('tShowNFSPackagePriceTypes');
	
	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;
		}
	});
}

function showWaitingDialog() {
	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 setting up your package.</div>'
	});
	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() {
	$('tAJAXState').innerHTML = 'Please wait...';
	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("donationSetAmount") !== "") {
        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 toggleSAAG(idnum) {
  $('saagt_' + idnum).toggleClassName('open');
  $('sagphd_' + idnum).toggleClassName('open');
}

function toggleSAAGTabs(id) {
  getOnTab = $$('.saagtabon');
  
  for (i = 0; i < getOnTab.length; i++) {
    getOnTab[i].removeClassName('saagtabon');
  }
  
  $('tab_' + id).toggleClassName('saagtabon');
  $('saagSeason_' + id).toggleClassName('saagtabon');
}

function toggleSPD(idnum) {
  $('spdt_' + idnum).toggleClassName('open');
  $('spdhd_' + idnum).toggleClassName('open');
}

function toggleSO(idnum) {
  $('sot_' + idnum).toggleClassName('open');
  $('sohd_' + idnum).toggleClassName('open');
}

function toggleMO(idnum) {
  var wasOpen = $('mot_' + idnum).hasClassName('open');

  $$('.moHiddenData').each(function(item){item.removeClassName('open');});
  $$('.moToggler').each(function(item){item.removeClassName('open');});

  if (! wasOpen) {
	$('mot_' + idnum).toggleClassName('open');
	$('mohd_' + idnum).toggleClassName('open');
  }
}


function showRoundupDialog() {
	globalDialog = new  Dialog({
		title:'Make a Donation',
		opacity:0.50,
		width:400,
		height:105,
		padding:0,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},
		content:'<div id="roundupDiv"></div>'
	});

	globalDialog.open();

	new Ajax.Updater('roundupDiv', '/h/tessitura/showRoundupDialog', 
    { 	evalScripts: false, 
        method: 'get'
	});	
}

function submitDonationForm(cartURL) {
	var donationType = $RF("donateOnline","donationType");
	var index = donationType.indexOf('_');
	var method = donationType.substr(0,index);
	var id = donationType.substr(index+1);
	
	if (method == "onaccount") {
		$('fundid').setValue(0);
		$('accountmethod').setValue(id);
	}	
	else {
		$('accountmethod').setValue(0);
		$('fundid').setValue(id);
	}
	
	new Ajax.Request('/h/tessitura/SubmitDonationFormCSI',
	{ 	evalScripts: false, 
		method: 'get', 
		parameters: $('donateOnline').serialize(true),
		onSuccess: function(response){
			new Ajax.Request( '/h/tessitura/UpdateContribution',
			{	evalScripts: false,
				method: 'get',
				parameters: $('donateOnline').serialize(true),
				onSuccess: function(response) {
					location.href=cartURL;
				}
			});
		}
	});
	
	return false;
}

function redosIFRreplacement() {
sIFR.replace(franklingothicstd, {
  selector: 'h2',
  css: {
    '.sIFR-root': { 'color': '#717172'}
  },
  wmode: 'transparent'
});
}

function submitMembershipStepOne() {

	setAmount = $RF("donateOnline","donationSetAmount");
	enteredAmount = $('donationEnterAmountPreview').value;
	
	if ((setAmount === "0") && (enteredAmount === "")) {
		globalDialog = new  Dialog({
		title:'Enter a valid amount',
		opacity:0.50,
		width:400,
		height:105,
		padding:0,
		margin:0,
		background:["#000000", "#ffffcd"],
		close:{link:true,esc:true,overlay:false},  
		content:'<div id="roundupDiv" class="ml20">Please enter a valid amount in the "Other Amount" field.</div>'
		});

		globalDialog.open();
	
		return false;
	}

	($RF('donateOnline','donationSetAmount') === '0') ? $('donationEnterAmount').setValue($('donationEnterAmountPreview').value) :  $('donationEnterAmount').setValue($RF('donateOnline','donationSetAmount'));
	
	new Ajax.Request('/h/tessitura/getLoginStatus', 
    { 	evalScripts: false, 
        method: 'get', 
		onSuccess: function(response){
			if (response.responseText.match('LOGGEDIN')) {
				$('mainDonationStepOne').hide();
				$('mainDonationStepTwo').show();
				redosIFRreplacement();
			} else {
				globalDialog = new Dialog({
				title:'Please Login',
				opacity:0.50,
				width:400,
				height:300,
				padding:0,
				margin:0,
				background:["#000000", "#ffffcd"],
				close:{link:true,esc:true,overlay:false},
				content:'<div id="loginDiv"></div>'
				});

				globalDialog.open();

				new Ajax.Updater('loginDiv', '/h/tessitura/showLoginDialog', 
				{ 	evalScripts: false, 
					method: 'get',
					parameters: {onComplete:'showMembershipNextStep',initialize:'true'}
				});	
			}
		}
	});
	return false;
}

function submitLeagueMembership() {
	new Ajax.Request('/h/tessitura/getLoginStatus', 
    { 	evalScripts: false, 
        method: 'get', 
		onSuccess: function(response){
			if (response.responseText.match('LOGGEDIN')) {
				// trigger membership dialog
				globalDialog = new  Dialog({
				title:'',
				opacity:0.50,
				width:400,
				height:155,
				padding:0,
				margin:0,
				background:["#000000", "#ffffcd"],
				close:{link:true,esc:true,overlay:false},
				content:'<div id="membershipDiv"></div>'
				});

				globalDialog.open();

				new Ajax.Updater('membershipDiv', '/h/tessitura/showMembershipDialog', 
				{ 	evalScripts: true, 
					method: 'get',
					parameters: $('leagueMembership').serialize(true)
				});					
			} else {
				globalDialog = new Dialog({
				title:'Please Login',
				opacity:0.50,
				width:400,
				height:300,
				padding:0,
				margin:0,
				background:["#000000", "#ffffcd"],
				close:{link:true,esc:true,overlay:false},
				content:'<div id="loginDiv"></div>'
				});

				globalDialog.open();

				new Ajax.Updater('loginDiv', '/h/tessitura/showLoginDialog', 
				{ 	evalScripts: false, 
					method: 'get',
					parameters: {onComplete:'showMembershipDialog',initialize:'true',accountmethod:$('accountmethod').value,donationSetAmount:$RF('leagueMembership')}
				});		
			}
		}
	});	
	return false;
}

function submitMembershipDetails(cartURL) {
	var donationSetAmount = $RF('leagueMembership');
	var secondmembername = null;
	
	if ($('secondmembername')) {
		secondmembername = $('secondmembername').value;
	} 
	
	if ($('firstmembername').value === '') {
		new Ajax.Updater('membershipDiv', '/h/tessitura/showMembershipDialog', 
		{ 	evalScripts: false, 
			method: 'get',
			parameters: { donationSetAmount:donationSetAmount, hasError:'true',firstmembername:$('firstmembername').value, secondmembername:secondmembername }
		});
		return false;
	}
	
	new Ajax.Request('/h/tessitura/SubmitMembershipDetails',
	{ 	evalScripts: false, 
		method: 'get', 
		parameters: {
			firstmembername:$('firstmembername').value,
			secondmembername:secondmembername
		},
		onSuccess: function(response){
			new Ajax.Request( '/h/tessitura/UpdateContribution',
			{	evalScripts: false,
				method: 'get',
				parameters: $('leagueMembership').serialize(true),
				onSuccess: function(response) {
					location.href=cartURL;
				}
			});
		}
	});
	
	return false;
}
