Shadowbox.init({adapter:'jquery',handleOversize:'drag',useSizzle:false});
jQuery(document).ready(function($){
// STYLESHEET SWITCHER,,,
  var stylesheetSwitch = function(){
      var ss = document.getElementsByTagName('link'), ov = 'override', J = ss.length
        , ABC = this.id == 'styleSwitcher' ? (document.cookie.match(/dgss=([A-Z])/)||[])[1]||'' : (this.id.match(/^styleOverride([A-Z])$/)||[])[1];
      for(;(J--);){ if(ss[J].id && ss[J].id.indexOf(ov) === 0){ ss[J].disabled = !(!!ABC && ss[J].id == ov+ABC); } }
      document.cookie = 'dgss='+(ABC||'')+'; path=/';
      $('.stylesheetButton').each(function(i){
          $(this).css({backgroundColor:((!ABC && !i) || this.id=='styleOverride'+ABC) ? '#cccccc' : '#ffffff'});
        });
    };
  $('#styleSwitcher').each(function(){ stylesheetSwitch.call(this); })
                     .hoverIntent( function(){ $(this).stop().animate({width:540}); }
                                 , function(){ $(this).stop().animate({width:$('div:first',this).css('borderLeftWidth')}); }
                                 )
                     .find('.stylesheetButton').bind('click', stylesheetSwitch);
// EVERY PAGE : main menu...
  //centre the main menu horizontally within the page...
  var sf = $('ul.sf-menu'), mn = $('#main_navigation'), sfdiff = Math.floor((mn.width() - sf.width())/2);
  mn.css({paddingLeft:sfdiff});
  //apply superfish & sub-menu dropdowns...
  sf.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});

// HOME PAGE : image handler...
//  $('#home_image').cycle({fx: 'scrollRight', timeout:9000, speed:2000});
  $('#home_image').cycle({fx: 'fade', timeout:9000, speed:2000});

// 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);
      };
  //set the height of each accordion body so that slide will work...
  $('.accordionBody').each(function(){
      var el = $(this);
      el.height(el.height());
    });
  //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
                            , numberOfMonths:2 //show 2 months at a time
                            , constrainInput:false //don't constrain input to datepicker format
                            , beforeShowDay:function(d){ return [!!d.getDay(),'']; } //disable Sundays
                            , buttonImage:'data/images/iconCalendar.gif' //url for trigger icon
                            , buttonImageOnly:true //show trigger icon only (ie not in a button)
                            , buttonText:'Select a date...' //alt/title text for trigger icon
                            , showOn:'button' //show on click of trigger icon (not on field focus)
                            });
  //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')
      .bind('click',function(e){
          var anch = $(e.target).closest('a');
          if(anch.length){
					 	if(anch.is('.meet_photoAjaxLink')){
	            var tgt = anch.attr('href');
  	          if(tgt){
    	          $.get(tgt,{cb:(new Date()).getTime()}, function(data,state){
      	            if(data && data.indexOf('<!') !== 0){ $('#meetInfo').html(data); }
        	          else{ $('#meetInfo').html("<div id='meetNoInfo'>No information available...</div>"); }
          	      });
            	}
	            anch[0].blur();
  	          return false;
    	      }else{ //true link, like to biography james.php?
      	      window.location.href = anch.attr('href');
        	    return false;
        	  }
          }
        })
      .find('a').find('b.meetLabel').css({opacity:0.6}).end()
                .hover( function(){ $('img',this).css({opacity:0.6}).prev('b').show(); }
                      , function(){ $('img',this).css({opacity:1}).prev('b').hide(); }
                      )
                .each(function(i){
                    var me = $(this), img = me.find('img');
                    //this makes FF show the space for a missing photo (IE does it automatically - the red cross)...
                    $(this).css({width:img.width(),height:img.height()});
                    //build the scroller list...
                    meetScrollerHtml.push( "<li><a class='meet_scrollLink' href='#"
                                         , Math.floor(i/meetCarouselCt), '_', i, "'><span>"
                                         , me.find('span').text(), '</span></a></li>'
                                         );
                  })
                .end()
      //intialise the carousel...
      .carousel({ dispItems:meetCarouselCt
                , pagination:true
                , paginationPosition:'outside'
                , nextBtn:'<div><img src="data/images/iconSlideRight.gif" alt="" /></div>'
                , prevBtn:'<div><img src="data/images/iconSlideLeft.gif" alt="" /></div>'
                });
  //set up the scroller list...
  meetScroller.html('<ul>'+meetScrollerHtml.join('')+'</ul>')
              .jScrollPane({ scrollbarWidth:8
                           , scrollbarMargin:0
                           , dragMinHeight:20
                           , dragMaxHeight: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]+')').trigger('click'); }
                    if(h.length > 1){ $('#meetCarousel div.carousel-wrap a:eq('+h[1]+')').trigger('click'); }
                    anch[0].blur();
                    return false;
                  }
                });
  $('#meetCarousel_shield').fadeOut(1000);

//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');
});

