jQuery(function($){
  var Ph = $('div.photos img').hide()
    , jqld = $.browser.opera || $.browser.safari
    , web = $('#weblinks')
    ;

  //note: header images stuff relies on all images having the same dimensions...
  var hp = $('img.hdr_pics')
    , hpct = 0
    ;
  //run through all header images with a loader; on the last to be loaded, run headerImages()...
  hp.each(function(h){
      if(jqld){ //jQuery method...
        $('<img />').bind('load', function(){ if(++hpct >= hp.length) setTimeout(headerImages, 0); }).attr({src:this.src});
      }else{ //native 'new Image()' method...
        var pre = new Image();
        pre.onload = function(){ if(++hpct >= hp.length) setTimeout(headerImages, 0); pre.onload = function(){}; };
        pre.src = this.src;
      }
    });
  //sorts out the spacing, the layers, the click events, the activity menu option hovers, etc...
  function headerImages(){
    var hpc = $('#hdr_pics')
      , hpi = hp.eq(0).width()+10 //add borders and padding
      , i = hp.length //number of images
      , hpd = location.href.match(/([\w_]+)\.php$/) //current page name
      , hpj = hpd ? $('#hdr_'+hpd[1]) : [] //find image related to current page?
      , hpo = hpd = hpj.length ? hp.index(hpj[0]) : Math.round(Math.random()*(hp.length - 1)) //use random if no related image
      , hpl = $('#hdr_picsLabel').css({zIndex:i, width:hpi-10}) //set some label styling
      , hptx = function(idx){ //from an image's ID, return capitalised text...
                 var tx = hp.eq(idx)[0].id.split('_');
                 return $.map(tx, function(v, n){ return n > 0 ? v.substr(0,1).toUpperCase()+v.substr(1) : null; }).join(' ');
               }
      , hpfn = function(idx){ //takes index of an image to bring to front; swaps current front image with new front image
                 var j = hp.length;
                 hp.eq(hpo).removeClass('hdr_picsOn'); //remove class from current
                 hpl.hide().css({left:((hp.length - 1 - idx)*hpi)+5}).text(hptx(idx)); //hide current label, reposition to new image and update text for new image
                 hpo = idx; //set current to new
                 while((j--)){ hp[j].style.zIndex = j < hpo ? j : hp.length + hpo - 1 - j; } //layer other images
                 hp.eq(hpo).addClass('hdr_picsOn'); //add class to new current
                 hpl.show(); //show label
               }
      , ma = $('ul.menu a')
      ;
    while((i--)){ //layer images
      hp.eq(i).css({zIndex:i < hpo ? i : hp.length + hpo - 1 - i});
    } //ends loop with i = -1
    hpi = Math.floor(Math.min((hpc.parent().width() - hpc.width() - 450) / (hp.length - 1), hpi * 0.3)); //work out spacing
    //for each image, set its position according to calculated spacing, and animate to that position...
    while((++i) < hp.length-1){ 
      hp.eq(i).css({right:(i*hpi)});
      hpc.animate({width:'+='+hpi}, 50, 'linear', i < (hp.length - 2) ? null : function(){ hpfn(hpo); });
    }
    //set mouseout on pics' container : if not moving TO an image or label, set to page's original front...
    hpc.bind( 'mouseout'
            , function(e){ if(e.relatedTarget && hp.index(e.relatedTarget) < 0 && hpl.index(e.relatedTarget) < 0){ hpfn(hpd); } } );
    //...set mouseenter on each image : set image to front...
    hp.bind( 'mouseenter'
           , function(e){ var i = hp.index(this); if(i != hpo){ hpfn(i); }  return false; } )
      //...and set click on each image to navigate to related page for the image...
      .bind( 'click'
           , function(){ location.href = this.id.substr(4)+'.php'; })
      .css({cursor:'pointer'});
    //link the menu options to the header pics...
    //Note : header pic ids and activity page filenames must be in sync!
    //       eg. #hdr_[filename] relates to page [filename].php
    ma.each(function(){ //this runs through ALL menu options, even though only the activity options will probably be relevant
        var x = $('#hdr_'+this.href.match(/([\w_]+)\.php$/)[1])
          , y = x.length ? hp.index(x[0]) : -1;
        if(y >= 0){ //if match between option's href and a header image is found, set a hover on the menu option to bring the related image to the front...
          $(this).hover( function(e){ if(y != hpo) hpfn(y); }
                       , function(e){ if(e.relatedTarget && ma.index(e.relatedTarget) < 0 && y != hpd){ hpfn(hpd); } }
                       );
        }
      });
  }//end headerImages()

  //attach a photo-helper to the page...
  var Phh = $("<div id='photoHelper'"+(web.length?" class='weblinksHelper'":'')+"><div id='photoHelperLabel'></div><img id='photoHelperImg' src='#' /></div>").appendTo('body')
    , Phi = $('#photoHelperImg')
    , Phl = $('#photoHelperLabel')
    , Phe = { hb : (parseInt(Phh.css('borderTopWidth'), 10) * 2)
            , ip : (parseInt(Phi.css('paddingTop'), 10) * 2)
            , ib : (parseInt(Phi.css('borderTopWidth'), 10) * 2)
            , lb : (parseInt(Phl.css('borderLeftWidth'), 10) * 2)
            , t : 0 }
    ;
  Phe.t = Phe.hb + Phe.ip + Phe.ib;
  //image loader function...
  function iLoader(fn, sr){
    sr = sr || this.src;
    if(jqld){ //jQuery method...
      $('<img />').bind('load', fn).attr({src:sr});
    }else{ //native 'new Image()' method...
      var pre = new Image();
      pre.onload = function(){ fn.call(this); pre.onload = function(){}; };
      pre.src = sr;
    }
  } //end iLoader()
  //if a page has photos, set up the photo-helper to appear on hover...
  Ph.each(function(){
      var me = this;
      //run a loader on each photo on the page...
      iLoader.call(this, function(){ //context is image
          var X = this.width + Phe.t - 20 //right hand edge 20px to right of cursor position
            , Y = this.height + Phe.t + 20 //bottom edge 20px above cursor position
            ;
          //set the height of all photos to be 120, with proportional width; set hover to show full size image in helper...
          $(me).css({width:Math.round(120 * this.width / this.height), height:120}).show()
            .bind('mousemove', function(e){ Phh.css({top:e.pageY-Y, left:e.pageX-X}); })
            .hover( function(e){ Phi.attr({src:me.src}); Phh.css({top:e.pageY-Y, left:e.pageX-X}).show(); }
                  , function(e){ Phh.hide(); }
                  );
            ;
        });
    });

  //if on contact us page, set up some validation...
  $('#enquiryForm').bind('submit', function(e){
      var rtn = true
        , focussed = 0
        ;
      $('#formMailerError, #formThanks').hide();
      $('input.fldRequired', this).removeClass('fldError').each(function(){
          var v = $.trim(this.value);
          if(!v || (this.id == 'femail' && !/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/.test(v))){
            rtn = false;
            $(this).addClass('fldError');
            if(!(focussed++)) this.focus();
          }
        });
      $('#formError')[rtn ? 'hide' : 'show']();
      return rtn;
    }).bind('reset', function(){
        $('#formError, #formMailerError, #formThanks').hide();
        $('input.fldError', this).removeClass('fldError');
      });
  //allow for a new captcha to be requested...
  $('#changeCaptcha').bind('click', function(e){
      $('img.fldCaptcha').get(0).src = 'inc/captcha.php?cb='+(new Date()).getTime();
      $('#fcaptcha').each(function(){ this.focus(); });
      return false;
    }).show();
  //put focus in the captcha input field...
  $('#fcaptcha').each(function(){ this.focus(); });

  //striping on weblinks...
  web.find('div.weblink').each(function(i){
      if(i%2){ $(this).addClass('linkOddBg'); }
    }).find('img.screenShot').each(function(){
      var me = this
        , alt = $(this).attr('alt')
        , ss = alt ? this.src.replace(/\/[^\/]+$/i, '/'+alt) : 0
        , t = this.title
        , h = 20; //for height of label
      if(ss){
        Phl.show();
        //run a loader on each screenshot...
        iLoader.call(this, function(){ //context is image (screenshots are typically 400px wide)
            var X = this.width + Phe.t - 200 //horizontally centred on cursor position
              , Y = this.height + Phe.t + h + 20 //bottom edge 20px above cursor position
              , W = this.width + Phe.ib + Phe.ip - Phe.lb;
            //set hover to show screenshot image in helper...
            $(me).bind('mousemove', function(e){ Phh.css({top:e.pageY-Y, left:e.pageX-X}); })
              .hover( function(e){ Phi.attr({src:ss}); Phl.text(t).width(W); Phh.css({top:e.pageY-Y, left:e.pageX-X}).show(); }
                    , function(e){ Phh.hide(); }
                    );
              ;
          }, ss);
      }
    });
  //10% 'springtime' offer...
/*
  var tenA = $('div.background')
    , tenB = [ $('div.pageContent').offset(), parseInt(tenA.css('marginRight'), 10), parseInt(tenA.css('paddingRight'), 10) ]
    , tenC = $('#tenPercent').css({top:tenB[0].top-25, right:tenB[1]+tenB[2], visibility:'visible'})
    , tenD = function(){
        var cb = function(){ tenE = window.setTimeout(tenD, 3000); };
        tenC[tenC.is(':visible')?'fadeOut':'fadeIn'](1500, cb);
      }
    , tenE = window.setTimeout(tenD, 1000);
*/
});
