// hiding flash
if (swfobject.hasFlashPlayerVersion("9.0.0")) {
  // Overwrite regular CSS used for alternative content to enable Full Browser Flash
  swfobject.createCSS(".nonflash", "visibility:hidden");
}

Cufon.replace('h1:not(body.russian h1, body.chinese h1, body.hindi h1 ), h2, #body h3, h4, h5, h6, dl.hero-panel dd strong, a.rss-logo, #wide_slot_0.open-day strong, #wide_slot_1.open-day strong, #wide_slot_2.open-day strong, .course-dropdown span', {
  hover: 'true',
  fontFamily: 'Helvetica Neue LT Std'
});

function setUpBookingForm() {
  $('#booking_referer').change(function(){
    element = $(this);
    booking_section = element.closest('form').find('#booking_referer_other_section');

    if($.inArray(element.val(),['','College Website','Prospectus','Facebook','Twitter']) > -1){
      booking_section.hide();
      booking_section.find('input#booking_referer_other').val('');
    }else{
      booking_section.show();
    }
  });
  $('#booking_referer').trigger('change');
}



function setUpImageLighboxes() {
  $('a.lightbox').fancybox({
      'padding'        : 20,
      'autoScale'      : true,
      'transitionIn'    : 'elastic',
      'transitionOut'    : 'elastic',
      'title'          : false,
      'width'        : 680,
      'height'        : 495,
      'centerOnScroll'   : true
  });
}

function setUpVideoLighboxes() {

  // Setting up Vars
  var shareurl;
  var sharetext;

  $('a.lightboxVideo').click(function(){
    shareurl = $(this).attr('longdesc');
    sharetext = $(this).attr('title');
  }); //eo: click

  // Video Lightbox

  $('a.lightboxVideo').each(function(){
    vid_link = $(this);
    vid_link.fancybox({
      'padding'        : 20,
      'autoScale'      : true,
      'transitionIn'   : 'elastic',
      'transitionOut'  : 'elastic',
      'title'          : true,
      'titleShow'      : true,
      'titlePosition' : 'outside',
      'width'          : 700,
      'height'         : 400,
      'type'           : 'swf',
      'titleFormat' : formatTitle,
      'swf': {
        'allowFullScreen'  : true,
        'flashvars'     : 'video=' + escape(vid_link.attr('href')) + '&standalone=true',
        wmode: 'transparent'
      },
      'href'      : '/flash/video.swf',
      'centerOnScroll'   : true
    });
  });


function formatTitle() {
  return '<div class="title"><h3>Share this video:</h3><ul><li class="share-twitter"><a target="_blank" href="http://twitter.com/share?url=' + shareurl + '&amp;text=' + sharetext + '">Tweet</a></li><li class="share-facebook"><a target="_blank" href="http://www.facebook.com/sharer.php?u=' + shareurl + '">Share on Facebook</a></li><li class="share-linkedin"><a target="_blank" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=' + shareurl + '&amp;title=' + sharetext + '&amp;source=Royal%20Agricultural%20College">Share on LinkedIn</a></li><li class="share-reddit"><a target="_blank" href="http://www.reddit.com/submit?url=' + shareurl + '">Share on Reddit</a></li><li class="share-stumble"><a target="_blank" href="http://www.stumbleupon.com/submit?url=' + shareurl + '" class="stumble-logo">StumbleUpon</a></li><li class="share-email"><a href="mailto:?subject=' + sharetext + '%20from%20the%20Royal%20Agricultural%20College&amp;body=' + shareurl + '">Email This</a></li></ul></div>';
  // return '<div class="title"><p>&nbsp;</p></div>';
} // eo: formatTitle

} // eo: setUpVideoLighboxes()





// Used for converting div contents into an Object
var hero_panelContents = [];
var hero_panelTransition;




$(document).ready(function () {


  // if ($.browser.msie) {
  //      $('form input[type=submit]').live('click', function() {
  //         // $('form').css("border","solid 128px red");
  //         $(this).parent().parent().load($(this).attr('action') + " div.contact-form", $(this).serializeArray(), afterAjax  );
  //          return false;
  //      })
  //   }


  // Not sure if this is helping or not.
  if (swfobject.hasFlashPlayerVersion("9")) {
    $(".nonflash").css('display', 'none');
  };


  $('body.outreach #content .component h2').css("font-size","2.4em");
  $('body.outreach #content .quote blockquote p').css("font-size","2.4em");

  Cufon.replace('body.outreach #content #related.component h2, body.outreach #content #in-this-section.component h2, body.outreach #content #also-of-interest.component h2, body.outreach #content blockquote p, body.outreach #content .component.open-day h2, body.outreach #content .component.latest-content h2, body.outreach #content .component.general-content h2, body.outreach #content .component.gallery h2, body.outreach #content .component.archive h2, body.outreach #content .component.download h2, , body.outreach #content .component.comments h2:first-child', {
    hover: 'true',
    fontFamily: 'Headline One'
  });


  $('body#the-college-virtual-tour #body').append('<div id="flash-vt"><div id="virtual-tour"><p>In order to view this content you will need the flash plugin. If you would like to do so then you can download the plugin from <a href="http://www.adobe.com/products/flashplayer/" title="Download Flash Player">Adobe</a>.</p></div></div>');

  setUpImageLighboxes();
  setUpVideoLighboxes();

  // quote lightbox
  $('div.component.quote').each(function(){
    // make a copy of the quote element
    // so that lightbox does not remove it
    // from the page
    mini_me = $(this).clone(true);
    mini_me.attr('id',$(this).attr('id') + '_clone');
    mini_me.addClass('clone');
    $(this).find('.quote-body').hide();
    mini_me.hide();
    $(this).after(mini_me);
  });
  $('div.component.quote:not(.clone)').click(function(){

    $.fancybox({
      'href'           : '#' + $(this).attr('id') + '_clone',
      'padding'        : 20,
      'autoScale'      : true,
      'transitionIn'   : 'elastic',
      'transitionOut'  : 'elastic',
      'title'          : false,
      'centerOnScroll' : true,
      'autoDimensions' : true,
      'onStart'        : function(selectedArray){  $($(selectedArray).first().attr('href')).show(); },
      'onClosed'       : function(selectedArray){  $($(selectedArray).first().attr('href')).hide(); }
    });
  });
  // Putting blockquote cufon here fixes IE isseues with Quote lightbox
  Cufon.replace('blockquote p', {
    hover: 'true',
    fontFamily: 'Helvetica Neue LT Std'
  });



  $('form.search input[type=text]').bind( 'click focus',
    function() {
      if (this.value == "Enter keyword(s) here") {
        this.value = '';
      }
    }
  );
  $('form.search input[type=text]').blur(
    function() {
      if (this.value == '') {
        this.value = "Enter keyword(s) here";
      }
    }
  );
 //prevent searching on placeholder string
  $('form.search').submit(
    function(e) {
	  	var query_field = $(this).find('input[type=text]').first();
      if (query_field.val() === "Enter keyword(s) here") {
				e.preventDefault();
				query_field.focus();
      }
    }
  );



  $('form.default-values').each(function(){
    $(this).find('input[type=text], textarea').each(function(){
      $(this).focus(function(){
        e=$(this);
        if(e.val()==this.defaultValue){
          e.val('');
          e.removeClass('default-value');
        }
      });
      $(this).blur(function(){
        e=$(this);
        if(e.val()==''){
          e.addClass('default-value');
          e.val(this.defaultValue);
        }
      });
    });
  });



  // Carousel for Small Slots (Open Days)
    $(".small.single.open-day .carousel").each(function(index, gallery) {
        gallery = $(gallery);
        if (gallery.find('li').length > 1) {
          gallery.before("<a class='carousel-back'>Backward</a>");
          gallery.after("<a class='carousel-forward'>Forward</a>");

          gallery.jCarouselLite({
            btnNext: gallery.next(".carousel-forward"),
            btnPrev: gallery.prev(".carousel-back"),
            visible: 1,
            circular: false
          });
        }
      });

      // Carousel for Small Slots (Gallery )
        $(".small.single.gallery .carousel").each(function(index, gallery) {
            gallery = $(gallery);
            if (gallery.find('li').length > 1) {
              gallery.before("<a class='carousel-back'>Backward</a>");
              gallery.after("<a class='carousel-forward'>Forward</a>");

              gallery.jCarouselLite({
                btnNext: gallery.next(".carousel-forward"),
                btnPrev: gallery.prev(".carousel-back"),
                visible: 1,
                auto: 2000,
                speed: 500
              });
            }
          });



  // Carousel for Double Slots (Open Days Only)
    $(".small.double.open-day .carousel").each(function(index, gallery) {
        gallery = $(gallery);
        if (gallery.find('li').length > 2) {
          gallery.before("<a class='carousel-back'>Backward</a>");
          gallery.after("<a class='carousel-forward'>Forward</a>");

          gallery.jCarouselLite({
            btnNext: gallery.next(".carousel-forward"),
            btnPrev: gallery.prev(".carousel-back"),
            visible: 2,
            circular: false
          });
        }
      });

  // Carousel for Double Slots (Gallery Only)
    $(".small.double.gallery.photo .carousel").each(function(index, gallery) {
      gallery = $(gallery);
      if (gallery.find('li').length > 3) {
        gallery.before("<a class='carousel-back'>Backward</a>");
        gallery.after("<a class='carousel-forward'>Forward</a>");

        gallery.jCarouselLite({
          btnNext: gallery.next(".carousel-forward"),
          btnPrev: gallery.prev(".carousel-back"),
          visible: 3
        });
      }
    });


    // Carousel for Wide Slots (Gallery Only)
    if ( $('body').hasClass('page_b') ) {

      // Carousel for Wide Slots on Page B Template (Gallery Only)
          $(".page_b .wide.gallery.widget.photo .carousel").each(function(index, gallery) {
            gallery = $(gallery);
            if (gallery.find('li').length > 5) {
              gallery.before("<a class='carousel-back page_b'>Backward</a>");
              gallery.after("<a class='carousel-forward page_b'>Forward</a>");

              gallery.jCarouselLite({
                btnNext: gallery.next(".carousel-forward.page_b"),
                btnPrev: gallery.prev(".carousel-back.page_b"),
                visible: 5
              });
            }
          });

      } else {

        // Carousel for Wide Slots (Gallery Only)
            $(".wide.gallery.widget.photo .carousel").each(function(index, gallery) {
              gallery = $(gallery);
              if (gallery.find('li').length > 3) {
                gallery.before("<a class='carousel-back page_b'>Backward</a>");
                gallery.after("<a class='carousel-forward page_b'>Forward</a>");
                $('.component.gallery.widget .carousel-wrap').css("width","332px");
                $('.component.gallery.widget .carousel-wrap').css("padding","0 64px");

                gallery.jCarouselLite({
                  btnNext: gallery.next(".carousel-forward.page_b"),
                  btnPrev: gallery.prev(".carousel-back.page_b"),
                  visible: 3
                });
              }
            });


    }; // end of if




// Carousel for Super Wide Slots (Videos Only)
      $(".gallery.video.widget.double.wide .carousel").each(function(index, gallery) {
        gallery = $(gallery);
        if (gallery.find('li').length > 4) {
          gallery.before("<a class='carousel-back page_b'>Backward</a>");
          gallery.after("<a class='carousel-forward page_b'>Forward</a>");
          $('.component.gallery.widget .carousel-wrap').css("width","332px");
          $('.component.gallery.widget .carousel-wrap').css("padding","0 64px");

          gallery.jCarouselLite({
            btnNext: gallery.next(".carousel-forward.page_b"),
            btnPrev: gallery.prev(".carousel-back.page_b"),
            visible: 4,
            scroll: 1,
            circular: true
          });
        }
      });

      // Carousel for Wide Slots (Videos Only)
            $(".wide.gallery.widget.video.single .carousel").each(function(index, gallery) {
              gallery = $(gallery);
              if (gallery.find('li').length > 2) {
                gallery.before("<a class='carousel-back page_b'>Backward</a>");
                gallery.after("<a class='carousel-forward page_b'>Forward</a>");
                $('.component.gallery.widget .carousel-wrap').css("width","332px");
                $('.component.gallery.widget .carousel-wrap').css("padding","0 64px");

                gallery.jCarouselLite({
                  btnNext: gallery.next(".carousel-forward.page_b"),
                  btnPrev: gallery.prev(".carousel-back.page_b"),
                  visible: 2
                });
              }
            });


            // Carousel for Small Double Slots (Videos Only)
                  $(".gallery.video.double.small .carousel").each(function(index, gallery) {
                    gallery = $(gallery);
                    if (gallery.find('li').length > 2) {
                      gallery.before("<a class='carousel-back page_b'>Backward</a>");
                      gallery.after("<a class='carousel-forward page_b'>Forward</a>");
                      $('.component.gallery.widget .carousel-wrap').css("width","332px");
                      $('.component.gallery.widget .carousel-wrap').css("padding","0 64px");

                      gallery.jCarouselLite({
                        btnNext: gallery.next(".carousel-forward.page_b"),
                        btnPrev: gallery.prev(".carousel-back.page_b"),
                        visible: 2,
                        scroll: 1,
                        circular: true
                      });
                    }
                  });





    //  Bits and Bobs

    $('#body a.lightbox, .gallery a.lightbox').prepend('<span class="magnify" title="Click to view Full Size"></span>');
    $('#content #body .video a.lightboxVideo').prepend('<span class="play" title="Click to play the video"></span>');
    $('.component.gallery.video a.lightboxVideo').prepend('<span class="play" title="Click to play the video"></span>');

    $("tbody tr:odd").css("background-color", "#0b0b08");
    $("blockquote p:last").addClass("last");
    $('#content #body ol li, #content #body ul li').wrapInner('<span></span>');
    $("#breadcrumbs li").css("white-space", "nowrap");



    //  $(".title.share-block ul").css("width","0");
    //
    // $('.title.share-block').hoverIntent({
    //   over: anniBig,
    //   timeout: 0,
    //   out: anniSmall
    // });
    //
    // function anniBig(){ $(this).find('ul').animate({width: '142px'}, 400); };
    // function anniSmall(){ $(this).find('ul').animate({width: '0'}, 400); };




  // Flash hero banner
  //----------------------------------
  // Create an Object that flash understands
  var definitions = $('#main_slot_0 dl dd');
  var definitionstitle = $('#main_slot_0 dl dt');

  $('#main_slot_0 dl dt').each(function(index,title){
    title = $(title);
    def = $(definitions[index]);
    defTitle = $(definitionstitle[index]);

    slide = {'thumb':title.find('img').first().attr('src'),
        'title':def.find('strong').first().text(),
        'link':defTitle.find('a').first().attr('href'),
        'target':defTitle.find('a').first().attr('target'),
        'strap':def.find('p').first().text(),
        'video_thumbnail':defTitle.find('img').first().attr('src')
        };
    hero_panelContents.push(slide);
  });

  // add transition type to last entry of array - time is against me!
  hero_panelTransition = $('#main_slot_0 dl').hasClass('fancy');

  // Banner SWFObject
  var currentBodyId = $('body').attr('id');
  var outreachBodyClass = $('body').hasClass('outreach');


  var attributes = {};
  var flashvars = {
            bodyID:currentBodyId
          };

  var params =   {
            wmode:'transparent',
            id:'flash_banner',
            allowscriptaccess: 'always',
            allowNetworking: 'all',
            allowFullScreen: 'true'
          };

	if(outreachBodyClass){
		swfobject.embedSWF(
		            "/flash/outreach_loader.swf?20110803",
		            "main_slot_0",
		            "100%",
		            "100%",
		            "9.0.0",
		            "/flash/expressInstall.swf",
		            flashvars,
		            params,
		            attributes
		            );
	}

  var currentHeroClass = $('#main_slot_0').attr('class');
  if(currentHeroClass == "component hero-panel" && !outreachBodyClass){
  swfobject.embedSWF(
            "/flash/rac_loader.swf?20111019",
            "main_slot_0",
            "100%",
            "100%",
            "9.0.0",
            "/flash/expressInstall.swf",
            flashvars,
            params,
            attributes
            );
  }


  // Virtual tour SWFObject
  var attributes = {};
  var flashvars = {};
  var params =   {wmode:'transparent'};

  swfobject.embedSWF(
            "/flash/virtual-tour/vt_loader.swf?20101027",
            "virtual-tour",
            "100%",
            "100%",
            "9.0.0",
            "/flash/expressInstall.swf",
            flashvars,
            params,
            attributes
            );



   // Video Page SWFObject
  var attributes = {};
  var flashvars = {video: $('#video-page-player a').attr('href'), standalone: true};
  var params =   {wmode:'transparent','allowFullScreen'  : true};

  swfobject.embedSWF(
            "/flash/video.swf",
            "video-page-player",
            "700",
            "400",
            "9.0.0",
            "/flash/expressInstall.swf",
            flashvars,
            params,
            attributes
            );

  setUpBookingForm();

  // Download height fix
  var downloadHeight = 0;
  $('#download-list li').each(function(index) {
      if($(this).height() > downloadHeight) {
        downloadHeight = $(this).height();
      } else {
        $(this).height(downloadHeight);
      };
  });

}); // end of document dom ready event


// Called from Flash
// OPoen fancy box
function callFancyBox(my_href){

  	var videoUrl = 'video=' + escape(my_href) + '&standalone=true';

	$.fancybox({
      'padding'        : 20,
      'autoScale'      : true,
      'transitionIn'   : 'elastic',
      'transitionOut'  : 'elastic',
      'title'          : false,
      'titleShow'      : false,
      'width'          : 700,
      'height'         : 400,
      'type'           : 'swf',

    'swf': {
         'allowFullScreen'  : true,
         'flashvars'     : videoUrl,
         wmode: 'transparent'
     },

    'href'      : '/flash/video.swf',
      'centerOnScroll'   : true
  });
}

// Retrieve objects for slides
function sendDiv () {
  return hero_panelContents;
}

function sendTransition () {
  return hero_panelTransition;
}
// eo Flash Calls


var fadeout_timeout;
var fadein_timeout;
$(document).ready(function(){

  $('#nav-node-tree-root > li, #footer-nav-node-tree-root > li').each(function(index) {
      if($(this).children().size() == 2) {

        $(this).hoverIntent({
          over: fadeIn,
          timeout: 0,
          out: fadeOut
        });

      }  // close if
    }); // close each


    // Breadcrumbs
    jQuery("#breadCrumb0").jBreadCrumb();

}); // close document.ready


    function fadeIn(){
      if(fadeout_timeout != null)
        clearTimeout(fadeout_timeout);

      fadein_timeout= setTimeout(function(){ $('div.overlay').css({'display':'block'}).fadeTo(200,0.8); }, 50);
    };

    function fadeOut(){
      if(fadein_timeout != null)
        clearTimeout(fadein_timeout);

      fadeout_timeout= setTimeout(function(){ $('div.overlay').fadeTo(200, 0, function(){
        $(this).css({'opacity':0});
        $(this).css({'display':'none'});
      }); }, 200);
    }

// Gallery pagination
$('.gallery .pagination a').live('click', function(e) {
  e.stopImmediatePropagation();
  component_div = $(this).closest('div.component');
  component_div.wrap('<div id="gallery-loading"></div>');
  component_div_id = component_div.attr('id');
  $('#gallery-loading').fadeTo(0.4);
  $('#gallery-loading').load($(this).attr('href') + ' #' + component_div_id, function() {
    setUpImageLighboxes();
    setUpVideoLighboxes();
    $('#' + component_div_id + ' a.lightbox').prepend('<span class="magnify" title="Click to view Full Size"></span>');
    $('#' + component_div_id + ' a.lightboxVideo').prepend('<span class="play" title="Click to play the video"></span>');
    $('#' + component_div_id).unwrap();
    Cufon.replace('h2',{
      hover: 'true',
      fontFamily: 'Helvetica Neue LT Std'
    });
  });
  return false;
});

// ----- Send contact-forms with AJAX -------------------
$(document).ready(function(){
  $('div.contact-form form').bind('submit', submitForm);
})

function submitForm() {

    // Is it a booking form?
    if($('body').attr('id') == "bookings-show" || $('body').attr('id') == "bookings-create")  {
      // If so, do one thing
      $(this).parent().parent().load($(this).attr('action') + " #main-content #body", $(this).serializeArray(), afterAjax );
    } else {
      // Otherwise do this
      $(this).parent().parent().load($(this).attr('action') + " div.contact-form", $(this).serializeArray(), afterAjax  );
    }

   //Setup loading animation
   $('input[type=submit]', this).addClass("processing");
   $('input[type=submit]', this).attr('disabled', 'disabled');
  return false;

}

function afterAjax() {
  $('html, body').animate({scrollTop:0}, 'slow');
  Cufon.refresh();
  setUpBookingForm();
  // Rebind submit click to account for form errors.
  $('div.contact-form form').bind('submit', submitForm);
}

$(document).ready(function () {

  // Google Analytics for file downloads
  $('a[href^="/static"]').click(function() {

    // Get the download URL
    var downloadUrl = $(this).attr('href');

    // Tell Google about it
    _gaq.push(['_trackPageview', downloadUrl])
  });
});

