(function($){
	$.fn.cycle.transitions.scrollVert2 = function($cont, $slides, opts) {
		$cont.css('overflow','hidden');
		opts.before.push(function(curr, next, opts, fwd) {
			$.fn.cycle.commonReset(curr,next,opts);
			opts.cssBefore.top = fwd ? (next.cycleH-1) : (1-next.cycleH);
			opts.animOut.top = fwd ? -curr.cycleH : curr.cycleH;
		});
		opts.cssFirst = { top: 0 };
		opts.cssBefore= { left: 0 };
		opts.animIn   = { top: 0 };
		opts.animOut  = { left: 0 };
	};
})(jQuery);
Shadowbox.init({adapter:'jquery',handleOversize:'drag',useSizzle:false});
jQuery(document).ready(function($){
// EVERY PAGE : main menu...
  //apply superfish & sub-menu dropdowns...
	$('ul.sf-menu').supersubs({
            minWidth:    12,   // minimum width of sub-menus in em units
            maxWidth:    27,   // maximum width of sub-menus in em units
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over
                               // due to slight rounding differences and font-family
        }).superfish({dropShadows:false, autoArrows:false, speed:'fast'}).find('ul').bgIframe({opacity:true});
  //button links...
  $('.info_box_action').hover( function(){ $(this).addClass('info_box_hover'); }
                             , function(){ $(this).removeClass('info_box_hover'); }
                             )
    .find('.info_box_type').css({padding:0,width:'100%',height:'100%'})
    .find('a').each(function(){ $(this).html('<span style="padding-left:10px">'+$(this).text()+'</span>'); })
      .css({display:'block', width:'100%', paddingTop:1});
	$('.hoverAndShow').hover(function(ev){
			$('.showOnHover', this)[ev.type === 'mouseout' || ev.type === 'mouseleave' ? 'hide' : 'show']();
			return false;
		});
// HOME PAGE : image handler...
//  $('#home_image').cycle({fx: 'scrollRight', timeout:9000, speed:2000});
  $('#home_image').cycle({fx: 'fade', timeout:9000, speed:2000});
	//...transparent 'about' text...
	$('#about').each(function(){
			$(this).appendTo($('#content')).show();
			var inner = $('#aboutWrap')
				, outer = $('#about')
				, anim = $('#aboutContentWrap')
				, trans = $('#aboutContentTransparent').css({opacity:0.40})
				, right = inner.width() - outer.width()
				, top = inner.height() - outer.height();
			$('#aboutClick').data({about:false}).click(function(ev, sp){
					var exp = $(this).data();
					exp.about = !exp.about;
					$('#home_image').cycle(exp.about ? 'pause' : 'resume');
					if(exp.about){
						$('#home_image').cycle(1);
					}
					inner.toggleClass('aboutIsOpen', exp.about);
					anim.stop().animate(
							{	top:exp.about ? top : 0
							, right:exp.about ? right : 0
							}
						, sp || 1000
						);
					trans.stop().animate(
							{ opacity:exp.about ? 0.75 : 0.4
							}
						, sp || 1000
						);
					return false;
				});
		});
	$('#homefooter').each(function(){
			var h = $('#content').height();
			$('#content').data('vidh',
				{ op: parseInt($('.homevideo iframe', this).attr('height'), 10) + 21,
					cl: h
				}).height(h);
			$('.homefootvideo', this).click(function(){
					var vidEl = $('#homevideo'),
							frameEl = $('iframe', vidEl),
							vidId = this.id.replace(/foot/, 'video'),
							contentEl = $('#content'),
							heights = contentEl.data('vidh');
					if(vidId !== this.id){
						//could be (1) playing THIS video, or (2) playing a different video, or (3) not playing any video
						if(frameEl.length){
							//(1) or (2), ie. playing something...
							if(frameEl.attr('id') === vidId){
								//(1), ie. playing THIS : remove and reset...
								vidEl.remove();
								contentEl.stop().animate({height:heights.cl}, function(){
										if(!$('#aboutClick').data().about){
											$('#home_image').cycle('resume');
										}
									});
							}else{
								//(2), ie. playing different : just swap the source and id...
								frameEl.attr({src:this.href, id:vidId});
							}
						}else{
							//(3), ie. not playing : set images, clone video, and append...
							vidEl.remove();// just to make sure!
							$('.aboutIsOpen #aboutClick').trigger('click', [400]);
							$('#home_image').css({height:'100%'}).cycle('pause').find('img').css({height:'100%'});
							vidEl = $('#homefooter .homevideo').clone().attr({id:'homevideo'});
							$('iframe', vidEl).attr({src:this.href, id:vidId});
							contentEl.append(vidEl).stop().animate({height:heights.op});
						}
					}
					return false;
				});
			$('.homefootlabel', this).click(function(){
					var vid = this.id.replace(/label/, '');
					if(vid !== this.id){
						$('#' + vid).click();
					}
					return false;
				});
		});

// DGTV...
	$('#dgtv').each(function(){
			var control,
					items = $('#dgtvList li').filter(function(){
						//ensure 2nd image is a 'hover' image, and remove any surplus...
						var i = $('img', this),
								rtn = !!i.length;
						if(rtn){
							i.slice(1).addClass('dgtvImageHover').slice(1).remove();
						}else{
							$(this).remove();
						}
						return rtn;
					}),
					itemWidth = items.first().width() || 0;
			//make list width wide enough for an extra item, just to be on safe side...
			$('#dgtvList').width( (items.length + 1) * itemWidth )
				.data('minleft', -itemWidth * (items.length - 4))
				.find('a').click(function(){
					var li = $(this).closest('li').not('.dgtvPlaying'),
							player = $('#dgtvPlayer');
					if(li.length){
						if(!player.length){
							player = $('<iframe id="dgtvPlayer" src="" frameborder="0" allowfullscreen></iframe>')
								.appendTo($('#dgtvPlaying'));
						}
						player.attr({src:$(this).attr('href')})
						li.siblings('.dgtvPlaying').andSelf().toggleClass('dgtvPlaying');
					}
					return false;
				}).first().click();
			if(items.length > 4){
				control = $('<div/>').attr({id:'dgtvPrev'}).addClass('dgtvPrevNext')
					.append('<a href="#"><img src="data/upload/images/iconSlideLeft.gif" alt="" /></a>')
					.append('<img src="data/upload/images/dgtv/dgtvLeftbg.png" alt="" />');
				$('#dgtvVideos').append(control)
					.append(
						control.clone().attr({id:'dgtvNext'})
							.find('img').each(function(){
								$(this).attr({src:this.src.replace(/Left/, 'Right')});
							}).end()
					).find('.dgtvPrevNext a').click(function(){
						var slideBy = 4,
								self = $(this),
								list = $('#dgtvList'),
								listLeft = parseInt(list.css('left'), 10),
								minLeft = list.data('minleft'),
								setLeft = self.parent().is('#dgtvPrev')
									? Math.min(0, listLeft + (slideBy * itemWidth))
									: Math.max(minLeft, listLeft - (slideBy * itemWidth));
						list.animate({left:setLeft});
						$('#dgtvPrev')[setLeft < 0 ? 'show' : 'hide']();
						$('#dgtvNext')[setLeft > minLeft ? 'show' : 'hide']();
						return false;
					});
				$('#dgtvNext').show();
			}
		});

// ACCORDION...
  var accordionNext = function(sib, el){
        if(!sib){ sib = el.parent().children('.accordion'); }
        var k = sib.index(el), j = (k+1)%sib.length;
        while(j != k && !sib.eq(j).is('.accordionBody')){ j = (j+1)%sib.length; }
        return sib.eq(j);
      }
    , accordionParent = function(sib, el){
        var j = sib.index(el);
        while((j--) && !sib.eq(j).is('.accordionHead')){ ; }
        return j < 0 ? sib.eq(0) : sib.eq(j);
      };
  //slide each fieldset by clicking preceding header (only one expanded at any one time)...
  var ach = $('div.accordionHead').bind('click', function(){
      var me = $(this), sib = me.parent().children('.accordion'), tog;
      if(me.hasClass('accordionCollapse')){ //clicked is expanded - add next or first collapsed fieldset to this expanded fieldset
        tog = accordionNext(sib, this);
        tog = tog.add(accordionNext(sib, tog[0]));
      }else{ //clicked is collapsed - find expanded fieldset, then add this collapsed fieldset
        tog = accordionNext(sib, sib.filter('.accordionCollapse')).add(accordionNext(sib, this));
      }
      tog.slideToggle(function(){
          accordionParent(sib, this).toggleClass('accordionCollapse');
        });
    }).filter('.accordionCollapse');
  if(ach.length){
    accordionNext(false, ach).slideToggle();
  }

// BOOKING FORM...
  //booking form requires javascript to be enabled...
  $('#bookingJavascript, #bookingInstruction').toggle();
  $('#bookingSubmit').each(function(){ this.disabled = false; });
  //apply datepick to date fields...
  $('.jqDatePick').datepick({ dateFormat:$.datepick.RFC_1123 //format : [short day], [day of month] [short month] [4 digit year]
                            , minDate:'+0' //allow from today onwards
                            , maxDate:'+1y' //allow up to 1 year hence
                            , firstDay:1 //start at Monday
                            , monthsToShow:2 //show 2 months at a time
                            , monthsToStep:2 //prev/next by 2 months instead of just 1
                            , constrainInput:false //don't constrain input to datepicker format
                            , showOnFocus:false //show on click of trigger icon (not on field focus)
                            , showTrigger:'<img src="data/upload/images/iconCalendar.gif" alt="Select a date..." title="Select a date..." />'
														, onDate:function(d){ return {selectable:!!d.getDay(), dateClass:''}; } //disable Sundays
														, onShow:function(datepicker){
																$('tbody:first tr', datepicker).find('td:last').css('borderRightColor','#000000');
															}
                            });
  //apply classname of selected option to the select itself...
  var bfselect = function(){
      this.className = $('option:selected', this)[0].className;
    };
  $('#bookingForm select').bind('change', bfselect).each(bfselect);
  //cache the accordion fieldsets...
  var bookfldset = $('#bookingForm fieldset.accordion');
  //Reset button handler...
  $('#bookingReset').bind('click',function(){
      $('#bookingForm').resetForm().find('.reqd_field_empty').removeClass('reqd_field_empty');
      $('#bookingError').empty('');
      $('#bookingSuccess').hide();
      $('#bookingSubmit').show().get(0).disabled = false;
      if(bookfldset.eq(0).is(':hidden')){ bookfldset.eq(0).prev().trigger('click'); }
      $('#bookingForm select').each(bfselect);
    });
  //Submit button handler...
  $('#bookingForm').ajaxForm({
      //pre-submission validation for required fields...
      beforeSubmit:function(data, fm, opt){
          var valid = true;
          //for each customer-accessible field, if the class indicates that it's required then check that it has a value...
          fm.find(':input[name^=cust_]', this).each(function(){
              var el = $(this);
              if(el.hasClass('reqd_field')){ //IS required...
                if(!el.val()){ //does NOT have a value...
                  el.addClass('reqd_field_empty'); //give it a class to hilite the field...
                  if(valid){ //if this is the first error...
                    bookfldset.each(function(){ //make sure the containing fieldset is fully visible...
                        var fs = $(this);
                        if(el.parents().index(fs) >= 0 && fs.is(':hidden')){
                          fs.prev().trigger('click');
                          return false;
                        }
                      });
                    el.get(0).focus(); //focus the offending field
                  }
                  valid = false;
                }else{ //HAS a value, so clear any previous 'missing' class...
                  el.removeClass('reqd_field_empty');
                }
              }
            });
          if(valid){ //all required fields entered :clear any previous error and disable Submit...
            $('#bookingError').empty();
            $('#bookingSubmit').get(0).disabled = true;
          }else{ //missing 1 or more required fields : show an error...
            $('#bookingError').html('One, or more, required fields are missing...');
          }
          return valid;
        }
      //on-success handler...
    , success:function(resp){
        if(resp){ //problem! show returned error and re-enable Submit...
          $('#bookingError').html(resp);
          $('#bookingSubmit').get(0).disabled = false;
        }else{ //OK! clear any previous error, hide Submit, show success message...
          $('#bookingError').empty();
          $('#bookingSubmit').hide();
          $('#bookingSuccess').show();
        }
      }
    });

//MEET THE...
  var meetScroller = $('#meetList div.scroller'), meetScrollerHtml = [], meetCarouselCt = 5;
  $('#meetCarousel')
			.each(function(){
					$(this).before( $('<div></div>').attr('id', 'meetCarousel_shield') );
					var staff = $('<ul></ul>'),
							aCount = 0,
							anchors = $('a', this).filter(function(){
									var self = $(this),
											photo = $('img', self),
											li, title;
									if(photo.length){
										li = $('<li></li>').appendTo(staff).append(photo);
										self.empty().appendTo(li).append(photo);
										$('<strong><span>' + (self.attr('title') || photo.attr('title') || '') + '</span></strong>')
											.addClass('meetLabel').css({opacity:0.6}).prependTo(self);
										photo.add(self).removeAttr('title');
										//this makes FF show the space for a missing photo (IE does it automatically - the red cross)...
										self.css({width:photo.attr('width')+'px',height:photo.attr('height')+'px'});
										//build the scroller list...
										meetScrollerHtml.push(
											"<li><a class='meet_scrollLink' href='#",
											Math.floor(aCount / meetCarouselCt), '_', aCount, "'><span>",
											$('span', self).text(), '</span></a></li>'
											);
										++aCount;
									}
									return !!photo.length;
								});
					if(aCount){
						$(this).empty().append(staff);
						anchors.hover( function(ev){
								var mout = ev.type === 'mouseout' || ev.type === 'mouseleave';
								$('img',this).css({opacity: mout ? 1 : 0.6}).prev('.meetLabel')[mout ? 'hide' : 'show']();
							});
					}
				})
			.css({visibility:'visible'})
      .bind('click',function(e){
          var anch = $(e.target).closest('a'),
							url = anch.attr('href'),
							tgt = anch.attr('target');
					this.blur();
          if(url){
						if(tgt && tgt !== '_self'){
							//true link, like to biography james.php?
							window.location.href = anch.attr('href');
						}else{
   	          $.get(url,{cb:(new Date()).getTime()}, function(data,state,jqXHR){
     	            if(data && data.indexOf('<!') !== 0){
										$('#meetInfo').html(data);
									}else{
										$('#meetInfo').html("<div id='meetNoInfo'>No information available...</div>");
									}
         	      });
        	  }
          }
					return false;
        })
      //intialise the carousel...
      .carousel({ dispItems:meetCarouselCt
                , pagination:true
                , paginationPosition:'outside'
                , nextBtn:'<div><img src="data/upload/images/iconSlideRight.gif" alt="" /></div>'
                , prevBtn:'<div><img src="data/upload/images/iconSlideLeft.gif" alt="" /></div>'
                });
  //set up the scroller list...
  meetScroller.html('<ul>'+meetScrollerHtml.join('')+'</ul>')
              .jScrollPane({ verticalGutter:0
                           , verticalDragMinHeight:20
                           , verticalDragMaxHeight:50
                           })
              .bind('click', function(e){
                  var anch = $(e.target).closest('a.meet_scrollLink');
                  if(anch.length){
                    var h = (anch.attr('href').split('#')[1]||'').split('_');
                    if(h.length > 0){
											$('#meetThumbnails div.carousel-pagination a:eq('+h[0]+')').not('.active').triggerHandler('click');
										}
                    if(h.length > 1){
											$('#meetCarousel div.carousel-wrap a:eq('+h[1]+')').trigger('click');
										}
                    anch[0].blur();
                    return false;
                  }
                });
  $('#meetCarousel_shield').remove();

//VERTICAL GALLERY...
	$('.vertical_gallery').each(function(){
			var self = $(this),
					para = $('p', self),
					anchor = $('a', self),
					gname = $.trim((para.text() || '').replace(/&nbsp;/g, ' ')),
					href = anchor.attr('href') || '';
			self.empty();
			if(gname && href){
				self.load(href, {vertgal:gname}, function(){
						var picSets = $('.vertgal_picset', this)
							, pCt = picSets.length;
						if(pCt > 1){
							$('.vertgal_pics', this).cycle({fx:'scrollVert2', timeout:0, nowrap:1});
							$('a.vertgal_nav', this).click(function(){ 
										var Parent = $(this).parent()
											, isTop = Parent.hasClass('vertgal_top_nav');
										this.blur();
										Parent[isTop ? 'next' : 'prev']().cycle(isTop ? 'prev' : 'next'); 
										return false; 
									})
								.removeClass('vertgal_hide');
						}else if(pCt){ //only 1 picset: remove top nav link... 
							$('.vertgal_top_nav', this).hide();
						}
						if(pCt){
							Shadowbox.setup($('a', picSets).get(), {handleOversize:'resize', counterType:'skip'});
						}
						$('img', this).hover(
								function(){	$(this).css({opacity:0.8}); return false; } 
							, function(){	$(this).css({opacity:1}); return false; }
							);
						$('.vertgal_container', this).removeClass('vertgal_hide');
					});
			}
		});

//SUBSCRIPTIONS...
	$('#subscribe_form').submit(function(){
			var n = $('#subscribeName')
				, e = $('#subscribeEmail')
				, u = $('#subscribeUnsubscribe:checked')
				, m = ''
				, txt = 
					{ sub:'To register for our newsletter, please provide both Email and Name'
					, unsub:'To unsubscribe, please provide your registered Email address'
					}
				;
			if(!e.val()){
				e.addClass('reqdField').get(0).focus();
				m = txt[u.length ? 'unsub' : 'sub'];
			}else{
				e.removeClass('reqdField');
				if(!n.val() && !u.length){
					n.addClass('reqdField').get(0).focus();
					m = txt.sub;
				}else{
					n.removeClass('reqdField');
				}
			}
			if(m){
				$('#subscribeError .errorMsg').text(m).parent().slideDown();
			}else{
				$('#subscribeError').hide();
			}
			return !m;
		});
	$('#subscribeError .errorMsg').click(function(){
			return !$(this).parent().slideUp();
		}).hover(function(ev){
			$(this).toggleClass('errorMsgHover', ev.type === 'mouseenter' || ev.type === 'mouseover');
		});

//PRESS RELEASES...
	$('#pressReleases').each(function(){
			var prhover = function(el, ac){
						$(el).closest('.pressReleasePod')[ac]('pressReleaseShow');
//							.find('div.pressReleaseBox')[ac]('pressReleaseShow');
					},
					prhoveron = function(){
						prhover(this, 'addClass');
					},
					prhoveroff = function(){
						prhover(this, 'removeClass');
					},
					prfetched = function(resp, status, xhr){
						var tgt = $('#pressReleases'),
								problem = function(colour){
									return $('<div/>').css({padding:'50px 0',textAlign:'center', color:colour||'#808080'});
								},
								prevnext = function(pn){
									return $('<a/>').attr({href:'#', title:pn + ' Page...'})
										.html('&nbsp;').addClass('pressReleasePage pressReleasePage' + (pn.substr(0, 4)));
								},
								i = 0,
								r, c, cls, podCls, pg;
						tgt.empty();
						if(resp){
							if(resp.count){
								for( ; i < resp.count && i < 20; i++){
									//0-based row & column co-ords
									r = Math.floor(i / 5);
									c = i % 5;
									cls = ['pressReleaseBox'];
									cls.push(cls[0] + (r > 1 ? '_above' : '_below'));
									cls.push(cls[0] + (c > 2 ? '_left' : '_right'));
									podCls = ['pressReleasePod'];
									if(c === 4){
										podCls.push(podCls[0] + '_right');
									}
									$('<div/>').addClass(podCls.join(' ')).hide().appendTo(tgt)
										.append( $(resp.pr[i]) )
										.each(function(){
											//if the press_release template was used, clear out
											//any siblings and unwrap from the template container...
											var tmpl = $(this).find('>.mceTmpl:first');
											if(tmpl.length){
												tmpl.siblings().remove();
												tmpl.children().appendTo( tmpl.parent() );
												tmpl.remove();
											}
										})
										//remove anything that doesn't contain an element with a class of 'pressrelease'...
										.contents().filter(function(){
												return this.nodeType !== 1 || !$(this).has('.pressrelease').length;
											}).wrap('<div/>').parent().remove().end().end().end() //...end the parent(), the filter() and the contents()
										.find('div.pressreleaseWrap').wrap('<div class="' + cls.join(' ') + '"></div>').end()
										.show();
								}
								//if there's only 1 row of releases on this page, we only need an additional 2 rows of dummies;
								//otherwise, we need all 4 rows
								r = r + (r ? 1 : 2);
								for( ; r < 4; r++){
									tgt.append( $('<div/>').addClass('pressReleasePod_dummy') );
								}
								$('img.pressrelease', tgt).hoverIntent(prhoveron, prhoveroff);
								if(resp.total > 20){
									pg = $('<div/>').addClass('pressReleasePaging').appendTo(tgt);
									pg.append( prevnext('Previous') );
									for(i = 0, c = 1; i < resp.total; i += 20){
										$('<a/>').attr({href:'#', title:c === resp.page ? '' : 'Page ' + c + '...'})
											.addClass('pressReleasePage' + (c === resp.page ? ' pressReleasePageCurrent' : ''))
											.text(c++)
											.appendTo(pg)
									}
									pg.append( prevnext('Next') );
								}
							}else{
								tgt.append( problem().text('None found!') );
							}
						}else{
							tgt.append( problem('#cc0000').text('Error retrieving items...') );
						}
					},
					prfetch = function(pge){
						$.post('index.php', {ajaxpost:'AjaxPressReleases', p:pge||0}, prfetched, 'json');
					},
					prpage = function(){
						var pn = this.className.match(/(next|prev)/i);
						if(pn){
							$(this).siblings('.pressReleasePageCurrent')[ pn[1].toLowerCase() ]().not(this).click();
						}else if(!$(this).hasClass('pressReleasePageCurrent')){
							prfetch( parseInt($(this).text(), 10) );
						}
						return false;
					};
			prfetch();
			$('a.pressReleasePage').live('click', prpage);
		});

//SITE MAP...
	var bottomOfContent = $('#content').height() + $('#content').offset()['top'];
	$('#content.sitemap .colspan_3 .column').each(function(){
		  var col = $(this)
		    , ncol = $(this).next('.column')
		  	, ul = ncol.length ? $(this).children('ul') : []
		  	, ulen = !!ul.length
		    ;
		  if(ulen){
				ul.each(function(i){
						if(($(this).height() + $(this).offset()['top']) > bottomOfContent){
							ul.slice(i).appendTo(ncol);
							return false;
						}
						return true;
					});
			}
			return ulen;
		});
	$('#content.sitemap ul.rootLevel').removeClass('rootLevel');
});


