/* site specific jquery */
var EIBF_TRACK_FILETYPES = /\.(zip|pdf|doc*|xls*|ppt*|mp3)$/i;

$(function()
{
	/* add the carousel controls container */
	var controls = $('<ul></ul>')
		.addClass('controls')
		.insertAfter($('#carousel ul.images'));
	
	/* set up the jQuery cycle plugin */
	$('#carousel ul.images')
		.cycle({
			fx: 'fade',
			pause: 0,
			speed: 600,
			fx: 'fade',
			timeout: 5000,
			pager: '#carousel ul.controls',
			pagerAnchorBuilder: function(idx, slide)
			{
				return '<li><a href="#">'+ (idx + 1) +'</a></li>'; 
			},
			activePagerClass: 'active'
		});
		
	/* apply jquery.uniform to all form fields */
	$("select").uniform();
	
	/* prevents ie's unique rendering mood swings with lists & display:block! */
	if(jQuery.browser.msie)
	{
		$('#left .sub-nav *').css({zoom: 1});
	}
	
	$('a').each(function(){
		var href = $(this).attr('href');
		if (!href || !(typeof pageTracker == 'function')) return;
		if ((href.match(/^https?\:/i)) && (!href.match(document.domain))){
		    $(this).click(function() {
		        var extLink = href.replace(/^https?\:\/\//i, '');
		        pageTracker._trackEvent('External', 'Click', extLink);
		    });
		}
		else if (href.match(/^mailto\:/i)){
		    $(this).click(function() {
		        var mailLink = href.replace(/^mailto\:/i, '');
		        pageTracker._trackEvent('Email', 'Click', mailLink);
		    });
		}
		else if (href.match(EIBF_TRACK_FILETYPES)){
		    $(this).click(function() {
		        var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
		        var filePath = href.replace(/^https?\:\/\/(www.)edbookfest\.co\.uk\//i, '');
		        pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
		    });
		}
	});
	
	
	
	var _this;
	var calendarText;
	var s;
	
	/* add a span to each anchor */
	$('.calendar table').find('td a').each(function()
	{
		_this = $(this);
		
		calendarText = _this.text();
		
		_this
			.text('');
		
		s = $('<span />')
			.appendTo(_this);
			
		s.text(calendarText);
	});
	
	/* custom dropdown modifications */
	var selector = $('div.selector');
	
	var o = selector
		.find('select')
		.css({
			 width: '100%',
			 /* required to allow even the text to be clicked */
			 position: 'relative'
		});
	
	/* set the selector height and give it relative position */
	selector
		.height(o.height() + 'px')
		.css({position: 'relative'});
	
	/* position the span */
	selector
		.find('span')
		.css({
			position: 'absolute',
			top: 0,
			left: 0,
			height: selector.height() + 'px',
			lineHeight: selector.height() + 'px',
			paddingLeft: '8px'
		});	
		
	/* reversed z-index throughout the document - fixes some of the usual stacking issues in <=ie7 */
      var run_z_index = true;
      $("div[id=dm_tool_bar]").each(function() {
       run_z_index = false;
      });

      
      if(run_z_index) {
        var zIndexNumber = 9000;
        $('div').each(function() {
          $(this).css('zIndex', zIndexNumber);
          zIndexNumber -= 10;
        });
      }
    });

/* enable sIFR */
var font = { src: '/sifr.swf' };
sIFR.activate(font);
sIFR.replace(font,
{
	selector: 'h1.sIFR',
	css: ['.sIFR-root { text-transform: uppercase; color: #555555; leading: -7 }', 
		  '.sIFR em { background-color: transparent; color: #007fc5; font-style: normal; }'],
	repaintOnResize: false,
	wmode: 'transparent'
});

function add_AddThis()
{
	// ie6 see's a syntax error in the external script, so we'll exclude it from ie6
	if(!($.browser.msie && parseInt(jQuery.browser.version) <= 6))
	{
		$.getScript('http://s7.addthis.com/js/250/addthis_widget.js#username=xa-4be82fce56f90321&domready=1');		   
	}
}

$(function()
{
  //setTimeout("add_AddThis()", 50);
});

$(function() 
{
	/* iterate through each select and do some magic to allow the options to overflow (particularly IE related) */
	$('div.selector').each(function() 
	{
		var _this = $(this);
		
		$('span', this)
			.css({
				/* div.selector width - padding - dropdown arrow width */
				width: _this.width() - parseInt($(this).css('padding-left')) - 35 + 'px',
				overflow: 'hidden'
			});
		
		
		/* force the select options to 'overflow' in IE :( */
		if($.browser.msie)
		{
			/* grab the select element that belongs to div.selector */
			var select = $('select', this);
			
			/* create a temp clone and apply css to render off page */
			var temp = select.clone().css({width: 'auto', position: 'absolute', top: '-1000px', left: 0});
			
			/* append to the body */
			$('body').append(temp);
			
			/* get the width of the select element & apply it to the original select element */
			if(temp.width() >= select.width())
			{
				select.width(temp.width());
			}
			
			/* remove the temporary cloned element */
			temp.remove();
		}
	});
});

$(function()
{
	// render the buy now's as images
	if($.browser.msie && parseInt(jQuery.browser.version) <= 6)
	{
		$('#content p.btn-1 a').each(function()
		{
			var image = $(this).css('background-image');
			$(this).css({backgroundImage: 'none'});
			$(this).css({textIndent: 0});
			image = image.replace(/url\(\"/g, '');
			image = image.replace(/\"\)/, '');
			
			$(this).html('');
			$(this).append($('<img src="' + image + '" />'));
		});
	}
});

/* search refine form */
$(document).ready(function()
{
	/* only applies to gecko/webkit/ie8+.... */
	if(!($.browser.msie && parseInt(jQuery.browser.version) < 8))
	{
		var isOpen = true;

		/* requires 'submitted' class to be appended to #search-animate */
		if($('.form #search-animate').hasClass('submitted'))
		{
			isOpen = false;

			/* if isOpen == false, hide the form by default */
			$('.form #search-animate').hide();
			$('.overview .search.refine .form h2 span').addClass('down');
		}

		

		$(function()
		{
			var isSubmitted;

			var ele = $('.form #search-animate');

			$('form', ele).submit(function(e)
			{
				e.preventDefault();

				$(this).slideUp(500, function()
				{
					$('.overview .search.refine .form h2 span').addClass('down');

					$('form', ele).unbind('submit').submit();
				});
			});

			ele.parent()
			.find('h2')
			.css({cursor: 'pointer'})
			.click(function()
			{
				if(!isOpen)
				{
					ele.slideDown(500, function() {
						isOpen = true;
						$('.overview .search.refine .form h2 span').removeClass('down');
					});
				}
				else
				{
					ele.slideUp(500, function() {
						isOpen = false;
						$('.overview .search.refine .form h2 span').addClass('down');
					});
				}
			});
		});
	}

	$('form')
		.submit(function()
		{
			/* if submitted with 'Keywords' still in field, clear it */
				if($('#event_search_form_keywords').val() == 'Keywords')
					$('#event_search_form_keywords').val('');
		});

	/* render some text in empty search fields */
	$('#event_search_form_keywords').each(function()
	{
		var _this = $(this);
		var fText = 'Keywords';
		
		if(_this.val() == '')
			_this.val(fText);

		_this
			.focus(function()
			{
				if(_this.val() == fText)
					_this.val('');
			})
			.blur(function() {
				if(_this.val() == '')
					_this.val(fText);
			});
	});
});


/**
 * Edit your details show/hide functionality
 */
(function($)
{
	$(document).ready(function()
	{
		var form = $('.page_dmUser_checkoutYourDetails form');
		
		var delivery_select = $('select#order_address_form_ticket_delivery', form);
		var address_radio = $('#address-select input[type=radio]', form);

    
		delivery_select.change(function()
		{
			if($(this).val() == 1) // collection
			{
				$('#tickets-collect').hide();
				$('#tickets-deliver').show();
			}
			else
			{
        $('#tickets-collect').show();
				$('#tickets-deliver').hide();				
			}
		})
		.change();
		
		address_radio.change(_radio);
		
		function _radio()
		{
			if(address_radio.length > 0) {
				if(address_radio[1].checked)
				{
					$('.anotherAddress', form).show();
				}
				else
				{
					$('.anotherAddress', form).hide();
				}
			}
		}
		
		_radio();
		
	});
})
(jQuery);

/**
 * Add to basket overlay
 */
(function($)
{
	var overlay;
	var content;
	var underlay;
	
	$(document).ready(function()
	{
		$('#bookingEvent .goto-checkout-btn, #bookingEvent .search-for-event-btn').hide();
		
		overlay = $('<div />')
			.addClass('modal-overlay')
			.attr('id', 'modal-overlay')
			.css({
				display: 'none'
			});
			
		content = $('<div class="modal-overlay-inner" />')
			.appendTo(overlay);
			
		underlay = $('<div />')
			.attr('id', 'modal-underlay')
			.css({
				width: '100%',
				height: $(document).height() + 'px',
				display: 'none'
			});
			
		$(window).resize(function()
		{
			// reposition overlay
			_recalcOverlay();
		});
		
		$('.event_display_buy_tickets form').submit(function(e)
		{
			var _form = $(this);
			
			e.preventDefault();
			
			_addToBasket();
			
			$.ajax({
				type: 'GET',
				dataType: 'json',
				data: _form.serialize(),
				cache: false,
				url: '/ajax_add_to_basket',
        timeout: (300 * 1000),
				success: function(data)
				{
					_setContent(data.message);
					_updateHeaderBasket(data);
					_showBasketLinks(data);
				},
        error: function(data)
				{
					_setContent('<p>Our system is currently very busy. You may continue to browse events, but please try again later to purchase tickets.</p>');
					_showBasketLinks(data);
				}
			})
		});
		
		// display logout popup warning
		$('#header .links li.logout a').click(function(e)
		{
			e.preventDefault();
			
			var logout_link = $(this).attr('href');
			
			// beautiful
			var basket_count = $(this).parentsUntil('.links')
				.find('.basket span')
				.text()
				.replace('(', '')
				.split(' ')[0];
			
			if(basket_count > 0)
			{
        $.ajax({
          type: 'GET',
          url: '/ajax_snippet/get/logout_items_in_basket',
          success: function(data)
          {
            content.html(data);
            _showOverlay();
            
            var y = $('<a />')
              .text('Yes')
              .addClass('bigbtnanchor')
              .attr('href', '#')
              .attr('id', 'confirm-yes')
              .click(function(e)
              {
                e.preventDefault();
                window.location.href = logout_link;
              });

            var n = $('<a />')
              .text('No')
              .addClass('bigbtnanchor')
              .attr('href', '#')
              .attr('id', 'confirm-no')
              .click(function(e)
              {
                e.preventDefault();
                _hideOverlay();
              });

            content.append(y);
            content.append(n);
         }
        })
			}
			else
			{
				window.location.href = logout_link;
			}
		});
		
		function _showBasketLinks(data)
		{
			if(data.success == 'notice')
			{
				$('#bookingEvent .goto-checkout-btn, #bookingEvent .search-for-event-btn').show();
				
				overlay.find('a:last').focus();
			}
		}
		
		function _updateHeaderBasket(data)
		{
			try
			{			
				var numItems = 0;
				var basketTotal = parseFloat(data.basket_total).toFixed(2);
				
				for(var i in data.basket)
				{
					numItems = data.items_in_basket;
				}
				
				$('#header li.basket span').html('(' + numItems + ' items &pound;' + basketTotal + ')');
			}
			catch(e)
			{}
		}
		
		function _setContent(msg)
		{
			content.html('');
			
			content.append(msg);
			
			
			var close = $('<a />')
				.attr('href', '#')
				.addClass('bigbtnanchor')
				.text('OK')
				.click(function(e)
				{
					e.preventDefault();
				
					_hideOverlay();
				})
				.focus();

			content.append(close);
		}
		
		function _showOverlay()
		{
			
			
			underlay.fadeTo(400, 0.6, function()
			{
				/* move off screen and show to allow height detection */
				overlay.css({
					top: '-9999px'
				}).show();
				
				_recalcOverlay();
				
				/* hide again, now we've got the dimensions */
				overlay.css({
					top: '50%'
				}).hide();
				
				overlay.fadeIn(300, function()
				{
					overlay.find('a:last').focus();
					
				});
			});
		}
		
		function _recalcOverlay()
		{
			overlay.css({
				marginTop: (overlay.outerHeight() / 2) * -1
			})
		}
		
		function _hideOverlay()
		{
			overlay.fadeOut(300, function()
			{
				underlay.fadeTo(400, 0, function() 
				{
					underlay.hide();
				});
			});
		}
		
		/* populate with 'adding' content, and trigger _showOverlay */
		function _addToBasket()
		{
			content.html('');
			
			$('<p class="spinner"><img src="/theme/images/spinner.gif" alt="adding..." /></p>')
				.appendTo(content);
			
			$('<span />')
				.addClass('adding-to-basket')
				.text('Adding')
				.appendTo(content);
				
			_showOverlay();
		}


		// close on esc keypress
		$(document).keyup(function(e)
		{
			if(e.keyCode == 27)
				_hideOverlay();
		});

    $('a.overlay_message').click(function() {
      _setContent($('div#' + $(this).attr('id') + '_help_text').html());
      _showOverlay();
      return false;
    });

			
		underlay.appendTo('body')
		overlay.appendTo('body')
	});
})
(jQuery);

(function($)
{
	$(document).ready(function()
	{
    if(typeof $('input#selected_membership_tier').val() != 'undefined') {
      var _form = $('#addingMembership');

      var _toggle = _form.find('#membership-donation');
      var $val = $('input#selected_membership_tier').val().split('_');

      if(typeof $val[1] == 'undefined' || $val[1] == 0)
      {
        $('div.without-donation').hide();
        $('div.with-donation').show();
      }
      else
      {
        $('div.without-donation').show();
        $('div.with-donation').hide();
      }

      /* change the table contents based on what link was clicked */
      _toggle.find('a[class^=ajax-]').live('click', function(e)
      {
        e.preventDefault();

        $('div.with-donation').toggle();
        $('div.without-donation').toggle();

      });
    }
	});
})
(jQuery);


(function($) {
	$(document).ready(function() {

    // SET EVENT SEARCH HAS JS TO YES
    if(typeof($('#event_search_has_js').val()) != 'undefined') {
      $('#event_search_has_js').val('yes');
    }

    if(typeof($('#booking_has_js').val()) != 'undefined') {
      $('#booking_has_js').val('yes');
    }

    if(typeof($('#my_red61_via_payment_form_has_js').val()) != 'undefined') {
      $('#my_red61_via_payment_form_has_js').val('yes');
    }
  });
})
(jQuery);

(function($)
{
	$(window).ready(function()
	{
		var _bb = $('#basket-bottom');
		
		if(_bb.find('.apply_gift_voucher').length)
		{
			var elements = _bb.find('> div');
			var max_height = 0;
			var max_outer_height = 0;
			
			elements.each(function()
			{
				if($(this).height() > max_height)
				{
					max_height = $(this).height();
				}
			});
			
			elements.height(max_height);

		}
	});
})
(jQuery);
