/*----------------------------------------*/
/* International RiverFoundation (Public) */
/*----------------------------------------*/

jQuery(document).ready(function($) {
  
  /*********************/
  /* Image Pre-Loading */
  /*********************/
  
  $('body').data('preload')('pics/itm__social_networking_icons_in_header__youtube_hover.png');
  $('body').data('preload')('pics/itm__social_networking_icons_in_header__vimeo_hover.png');
  $('body').data('preload')('pics/itm__social_networking_icons_in_header__twitter_hover.png');
  $('body').data('preload')('pics/itm__social_networking_icons_in_header__facebook_hover.png');
  $('body').data('preload')('pics/btn__ecards_hover.png');
  
  /******************/
  /* Drop-Down Menu */
  /******************/
  
  var d = $('div#irf-header-middle');
  if (d.size())
  {
    // the complex animated drop-down is
    // powered through a series of hover
    // events so begin by defining what 
    // happens when a main topic is hovered
    d.find('table.menu td.topic').hover(
      function() {
        var t = $(this);
        var samt = t.find('div.sub-and-micro-topics').removeClass('irf-hidden');
        var st = samt.find('table.sub-topics');
        
        // add the class which
        // give hover style to
        // the main topic text
        t.addClass('hover');
        
        // stop all animations
        // which are closing the
        // drop-down and blink on
        // the sub-topics if there
        samt.stop();
        samt.css('height', 36);
        samt.css('opacity', 1.0).show();
        
        // customize the width of the sub and micro container after the tables
        // have had a chance to assume their full size based on their contents
        samt.css('width', st.width() < 900 ? 900 : st.width()); /* st.width()); */
      },
      function() {
        var t = $(this);        
        var samt = t.find('div.sub-and-micro-topics');
        var st = samt.find('table.sub-topics');
        
        // ensure the topic text
        // returns to normal style
        // and all sub-topics too
        t.removeClass('hover');
        st.find('td.sub-topic').removeClass('hover');
        
        // now simply close both sub and micro topics drop-downs
        // using a rapid animation and completing hiding when done
        samt.animate({ opacity: 0.0 }, 200, 'swing', function() { 
          $(this).css('height', 36).hide(); 
        });
      }
    );
    
    // the other animation effects are triggered
    // when a sub-topic of the first leve drop-down
    // is hovered by the user so define behavior
    d.find('table.menu td.sub-topic').hover(
      function(e) {
        e.stopPropagation();
        var st = $(this);
        var samt = st.parents('div.sub-and-micro-topics');
        var mt = samt.find('table.micro-topics');
        
        // ensure all over sub-topics are not hover-styled then style
        // the one that just became hovered which the proper over class
        samt.find('table.sub-topics td.sub-topic').removeClass('hover');
        st.addClass('hover');
        
        // establish our animation
        // speed one time here
        var mt_animate = 200; // ms
        
        // when the sub-topic has micro topics beneath 
        // it we can slide the panel or even if it doesnt
        if (true) /* st.hasClass('has-micro-topics') */ 
        {
          // halt previous
          // animation
          samt.stop();
          mt.stop();
          
          // open the panel by extending its container to the proper height to show
          samt.animate({ height: 36+mt.height(), opacity: 1.0 }, mt_animate, 'swing');
          mt.animate({ opacity: 1.0 }, mt_animate / 2.0, 'swing');
        }
        else 
        {
          // otherwise when hovering over a topic with no micro
          // topics we can close the lower panel with same effects
          samt.animate({ height: 36 }, mt_animate / 2.0, 'swing');
          mt.animate({ opacity: 0.0 }, mt_animate, 'swing');
        }
      },
      function() {
      }
    );
  }
  
  /***************************************/
  /* Header Feature -- Twitter Animation */
  /***************************************/
  
  var d = $('div#irf-header-overlays div.twitter-animation');
  if (d.size())
  {
    // for maximum flexibility
    // embed a function with div
    // to start the animation
    d.data('open', function() {
      var ta = $('div#irf-header-overlays div.twitter-animation');
      var bird = ta.find('div.bird');
      var speech = ta.find('div.speech');
      
      // extract the embedded timing parameters for the animation ensuring valid
      var slide_down_duration = parseFloat(ta.find('.slide-down-duration').text());
      if (slide_down_duration < 0.01) slide_down_duration = 0.5;
      var speech_fadein_duration = parseFloat(ta.find('.speech-fadein-duration').text());
      if (speech_fadein_duration < 0.01) speech_fadein_duration = 0.5;
      
      // set flag during open and do
      // not open while we are opening
      if (ta.data('opening')) return;
      ta.data('opening', true);
      
      // use the animation function to bring the bird down then when that is
      // complete fade in the speech bubble and add a class to signify its open
      bird.animate({ top: 0 }, slide_down_duration*1000, 'swing', function() {
        var ta = $(this).parents('.twitter-animation');
        ta.find('div.speech').fadeIn(speech_fadein_duration*1000);
        ta.find('div.bird').addClass('expanded');
        ta.data('opening', false);
        
        // when we have been instructed to close right away
        if (ta.data('close-immediately')) ta.data('close')();
      });
    });
    d.data('close', function() {
      var ta = $('div#irf-header-overlays div.twitter-animation');
      var bird = ta.find('div.bird');
      var speech = ta.find('div.speech');
      
      // extract the embedded timing parameters for the animation ensuring valid
      var slide_down_duration = parseFloat(ta.find('.slide-down-duration').text());
      if (slide_down_duration < 0.01) slide_down_duration = 0.5;
      var speech_fadein_duration = parseFloat(ta.find('.speech-fadein-duration').text());
      if (speech_fadein_duration < 0.01) speech_fadein_duration = 0.5;
      
      // when a request to close is received when the bird is opening schedule
      if (ta.data('opening')) { ta.data('close-immediately', true); return; }
      else ta.data('close-immediately', false);
        
      // set flag during close and do
      // not open while we are closing
      if (ta.data('closing')) return;
      ta.data('closing', true);
      
      // immediately fade out the speech before bird is gone
      ta.find('div.speech').fadeOut(speech_fadein_duration*1000);
      
      // use the animation function to send the bird up to original
      bird.animate({ top: -60 }, slide_down_duration*1000, 'swing', function() {
        var ta = $(this).parents('.twitter-animation');
        ta.data('closing', false);
      });
    });
    
    // enable the bird when hovered to open
    // of visit url if opened and clicked
    d.find('div.bird').click(function(e) {
      e.preventDefault();
      var ta = $(this).parents('.twitter-animation');
      var url = ta.find('.url').text();
      if ($(this).hasClass('expanded')) window.open(url);
    });
    d.find('div.bird').hover(
      function(e) {
        e.preventDefault();
        
        // locate the embedded function which animates the bird down
        var fn = $(this).parents('.twitter-animation').data('open');
        if (fn) fn();
      },
      function(e) {
      }
    );
    d.hover(function(e) {}, function(e) {
      e.preventDefault();
      
      // locate the embedded function
      var fn = $(this).data('close');
      if (fn) fn();
    });
    
    // enable the speech bubble to go to url
    d.find('div.speech').click(function(e) {
      e.preventDefault();
      var ta = $(this).parents('.twitter-animation');
      window.open(ta.find('.url').text());
    });
  }
  
  /***********************************************/
  /* Behaviors Used/Usable Across Multiple Pages */
  /***********************************************/
  
  /*************************/
  /* Lightbox'd (Reusable) */
  /*************************/
  
  // encapsulate the method for showing indicator
  $('body').data('plb__show_activity', function() {
    var el = $('<img src="pics/ajax__lightbox_loading.gif" alt="Loading" style="display: block; width: 54px; height: 55px;"/>');
    plb__lightbox.open(el, true);
  });
  
  // encapsulate a method for displaying an error
  $('body').data('plb__show_error', function(msg) {
    var el = $('<div class="irf-error-lightbox">'+
               '  <div class="irf-message error">'+msg+'</div>'+
               '  <a href="javascript:void(0)" class="plb__closer x"><img src="pics/itm__lightbox_closing_x_on_gray.png" alt="X"/></a>'+
               '</div>');
    plb__lightbox.open(el);
  });
  
  /****************************/
  /* Lightbox'd News Articles */
  /****************************/
  
  // allow the specially styled article openers to
  // open associated articles in a lightbox as needed
  var els = $('.irf-embedded-news-article-opener');
  els.each(function(i, el) {
    var el = $(el);
    el.click(function(e) {
      e.preventDefault();
      var container = $(this).parents('.irf-contains-embedded-news-article');
      var lb = container.find('.irf-embedded-article .irf-news-article-lightbox').clone();
      
      // use all available height for the article
      lb.css('max-height', $(window).height() - 100);
      plb__lightbox.open(lb);
    });
  });
  
  // allow the specially styled tell a friend lightbox
  // openers to open a lightbox email form to use as desired
  var els = $('.irf-tell-a-friend-about-this-lightbox-opener');
  els.each(function(i, el) {
    var el = $(el);
    el.click(function(e) {
      e.preventDefault();
      
      // use the embedded popup and clone it then add necessary actions to the popup elements and show it on page
      var lb = $('#irf-embedded-tell-a-friend-about-this-lightbox .irf-tell-a-friend-about-this-lightbox').clone(true);      
      
      // extract the item type and identifier as these
      // will be used in the form and for event tracking
      var item_type = $(this).find('.item_type').text();
      var item_id = parseInt($(this).find('.item_id').text());
      if (!item_id) item_id = null;
      
      // initialize google 
      // event tracking parts
      var ga_category = null;
      var ga_action = 'tell_a_friend_opened';
      var ga_label = null;
      var ga_value = null;
      
      // based on the type
      // of item we are sharing
      // track the click event
      switch (item_type)
      {
        case 'news_article':
          ga_category = 'irf_article';
          ga_label = 'news';
          ga_value = item_id;
          break;
          
        case 'home_feature_article':
          ga_category = 'irf_article';
          ga_label = 'home_feature';
          ga_value = item_id;
          break;
          
        case 'fundraising_event':
          ga_category = 'irf_article';
          ga_label = 'fundraising_event';
          ga_value = item_id;
          break;
      }
      
      // after preparing the proper data for the event use the analytics interface to register the event occurance
      if (typeof(_gaq) !== 'undefined') _gaq.push(['_trackEvent', ga_category, ga_action, ga_label, ga_value]);
      
      // attach a function to the onsuccess component of our form so that the 
      // successful submission of the tell a friend form can also be recorded
      lb.find('form.irf-basic-ajax-powered-form').data('onsuccess', function() {
        if (typeof(_gaq) !== 'undefined') _gaq.push(['_trackEvent', ga_category, 'tell_a_friend_submitted', ga_label, ga_value]);
      });

      // the link has all the content and settings necessary to 
      // present the tell a friend form and process it so populate
      lb.find('h1').html($(this).find('.popup_heading').text());
      lb.find('div.instructions').html($(this).find('.popup_instructions').text());
      lb.find('span.email_subject').text($(this).find('.email_subject').text());
      lb.find('input[name=email_subject]').val($(this).find('.email_subject').text());
      lb.find('input[name=item_type]').val($(this).find('.item_type').text());
      lb.find('input[name=item_id]').val($(this).find('.item_id').text());
      
      // show the lightbox
      plb__lightbox.open(lb);
    });
  });
  
  // allow the specially styled tell a friend lightbox
  // openers to open lightbox email form to use as desired
  var els = $('.irf-enews-subscription-form-lightbox-opener');
  els.each(function(i, el) {
    var el = $(el);
    el.click(function(e) {
      e.preventDefault();
      
      // use the embedded popup and clone it then add necessary actions to the popup elements and show it on page
      var lb = $('#irf-embedded-enews-subscription-form .irf-enews-subscription-form-lightbox').clone(true);
      
      // attach a function to the onsuccess component of our form so that the 
      // successful submission of the tell a friend form can also be recorded
      lb.find('form.irf-basic-ajax-powered-form').data('onsuccess', function() {
        if (typeof(_gaq) !== 'undefined') _gaq.push(['_trackEvent', 'irf_mailing_list', 'enews_subscription_form_submitted']);
      });
      
      // when the form opener is part of a form itself locate the email address and prepopulate
      var email = $('body').data('irf__real_val')($(this).parents('form').find('input[name=email]'));
      if (email) lb.find('input[name=email]').val(email).addClass('irf-focused');
      
      // show the lightbox
      plb__lightbox.open(lb);
    });
  });
  
  /*****************************/
  /* Lightbox'd Gallery Images */
  /*****************************/
  
  // allow the specially styled image openers to open associated images
  // in a lightbox as needed configurin the context of the image album
  $('body').data('irf__enable_gallery_image_links', function(root) {
    var els = root ? root.find('.irf-embedded-gallery-image-opener') : $('body').find('.irf-embedded-gallery-image-opener');
    els.each(function(i, el) {
      var el = $(el);
      if (el.data('irf-enabled')) return;
      el.click(function(e) {
        e.preventDefault();
        
        // extract the image identifier from the opener link contents
        var image_id = parseInt($(this).find('.irf-image-id').text());
        
        // show the indicator within a lightbox
        $('body').data('plb__show_activity')();                
        
        // define a function which will handle
        // both success and failure of our post
        var complete = function(data, status) { 
          if (!(data instanceof Object)) data = new Object();                    
                    
          // for any type of error use lightbox error
          // function which has been embedded in the body
          if ((!data.success) || (status != 'success'))
          {
            var error = data.error || 'System/Network error; Please try again.';
            $('body').data('plb__show_error')(error);
          }
          
          // otherwise proceed
          // to open lightbox
          else
          {
            // prepare to open the image retrieve by obtaining the html contents of the lightbox
            var lb = $('#irf-embedded-gallery-image-lightbox .irf-gallery-image-lightbox').clone();
            
            // set the components of the lightbox here
            lb.find('.image img').attr('src', data.src);
            lb.find('.image').css('width', parseInt(data.width));
            lb.find('.image').css('height', parseInt(data.height));
            lb.find('.insets').css('width', parseInt(data.width));
            lb.find('h1').html(data.album_title);
            lb.find('.title').html(data.title);
            lb.find('.caption').html(data.caption);
            lb.find('img.loading').css('top', ((parseInt(data.height) - 55) / 2.0));
            lb.find('img.loading').css('left', ((parseInt(data.width) - 54) / 2.0));
            
            // set the next and previous navigation buttons showing relevant
            lb.find('.previous .irf-image-id').text(data.previous_image_id);
            lb.find('.next .irf-image-id').text(data.next_image_id);
            if (!parseInt(data.previous_image_id)) lb.find('.previous').hide();
            if (!parseInt(data.next_image_id)) lb.find('.next').hide();
            lb.find('.previous').css('top', ((parseInt(data.height) - 72) / 2.0));
            lb.find('.next').css('top', ((parseInt(data.height) - 72) / 2.0));
            
            // after adding proper behaviors
            // display the lightbox content
            plb__lightbox.open(lb);
            
            // enable contact opener links in caption by calling enabler
            $('body').data('irf__enable_contact_form_lightbox_openers')();
            
            // enable the next and previuos image gallery links
            $('body').data('irf__enable_gallery_image_links')();
          }
        };
        
        // execute request
        $.ajax({ url: '?',
                 type: 'POST',
                 cache: false,               
                 data: { 'irf__action': 'fetch_image_gallery_image',
                         'image_id': image_id                         
                       },
                 dataType: 'json',
                 success: complete,
                 error: complete });
      });
        
      // after enabling link set flag
      // to prevent enabling again
      el.data('irf-enabled', true);
    });
  });
  
  // enable all image gallery links initially
  $('body').data('irf__enable_gallery_image_links')();
  
  /*******************************************/
  /* Behaviors Used/Usable On Specific Pages */
  /*******************************************/
  
  /*************/
  /* News Page */
  /*************/

  var d = $('div#irf-content.news');
  if (d.size())
  {
    // enable the accordion feature of the archived news
    d.find('div.archived-news .accordion').accordion({
      active: 0,
      collapsible: true
    });
  }
  
  /**********************/
  /* Blog Page (User's) */
  /**********************/
  
  var d = $('div#irf-content.blog');
  if (d.size())
  {
    // enable the accordion feature of the archived news
    d.find('div.archived-news .accordion').accordion({
      active: 0,
      collapsible: true
    });
    
    // enable the find out more links to open the embedded details
    d.find('div.upcoming-events a.details-opener').click(function(e) {
      e.preventDefault();
      var s = $(this).parents('div.irf-section');
      var lb = s.find('.irf-embedded-details .irf-blog-event-details-lightbox').clone();
      plb__lightbox.open(lb);
    });
  }
  
  /**************/
  /* About Page */
  /**************/
  
  var d = $('div#irf-content.about');
  if (d.size())
  {
    // preload images that we will use in our pinnable map lightbox
    $('body').data('preload')('pics/itm__pinable_world_map_large.png');
    $('body').data('preload')('pics/itm__orange_map_pin_normal.png');
    $('body').data('preload')('pics/itm__orange_map_pin_hover.png');
    $('body').data('preload')('pics/bg__pinable_map_popup_top.png');
    $('body').data('preload')('pics/bg__pinable_map_popup_middle.png');
    $('body').data('preload')('pics/bg__pinable_map_popup_bottom.png');        
    
    // enable the read bio links to open the embedded biography lightboxes
    d.find('div.governors div.governor div.bio-link a').click(function(e) {
      e.preventDefault();
      var g = $(this).parents('div.governor');
      var lb = g.find('.irf-embedded-biography .irf-biography-lightbox').clone();
      plb__lightbox.open(lb);
    });
    
    // enable the more links to open the embedded biography lightboxes for each
    d.find('div.our-staff div.profiles div.profile div.bio-link a').click(function(e) {
      e.preventDefault();
      var g = $(this).parents('div.profile');
      var lb = g.find('.irf-embedded-biography .irf-biography-lightbox').clone();
      plb__lightbox.open(lb);
    });
  }
  
  /***************************/
  /* Riverprize - About Page */
  /***************************/
  
  var d = $('div#irf-content.riverprize-about');
  if (d.size())
  {
    // enable the read bio links to open the embedded biography lightboxes
    d.find('div.judges div.judge div.bio-link a').click(function(e) {
      e.preventDefault();
      var g = $(this).parents('div.judge');
      var lb = g.find('.irf-embedded-biography .irf-biography-lightbox').clone();
      plb__lightbox.open(lb);
    });
  }
  
  /******************************/
  /* Riverprize - Entering Page */
  /******************************/
  
  var d = $('div#irf-content.riverprize-entering');
  if (d.size())
  {
    // enable the proper links to open the embedded application enquiry form lightbox
    d.find('.irf-riverprize-application-enquiry-form-lightbox-opener').click(function(e) {
      e.preventDefault();
      var el = $('#irf-embedded-riverprize-application-enquiry-form');
      if (el.data('already_open')) plb__lightbox.open(el.data('already_open')); 
      else 
      {
        // no lightbox has been created since they arrived at this page so start a new one
        var lb = el.find('.irf-riverprize-application-enquiry-form-lightbox').clone(true);
        lb.data('plb__preserve', true);
        el.data('already_open', lb);
        plb__lightbox.open(lb);
      }
    });
    
    // attach special processing to the application enquiry form so that it can reveal the proper application form icons after success
    d.find('#irf-embedded-riverprize-application-enquiry-form form.irf-basic-ajax-powered-form').data('onsuccess', function(f, data) {
      var tbl = f.find('table.download-links').show();
      if (data.national) tbl.find('td.national').show();
      if (data.international) tbl.find('td.international').show();
      f.find('div.submit').addClass('button-is-hidden');
      plb__lightbox.reposition();
      
      // enable the link within the success message to reset form
      f.find('div.submit div.ajax-success a').click(function(e) {
        e.preventDefault();
        var f = $(this).parents('form');
        var tbl = f.find('table.download-links').hide();
        tbl.find('td.download-link').hide();
        f.find('div.submit').removeClass('button-is-hidden');
        var ajr = f.find('.irf-basic-ajax-results');
        ajr.find('.ajax-failure').hide();
        ajr.find('.ajax-success').hide();
        
        // perform the standard processing to reset form fields
        var fields = f.find('input[type=text], textarea, select');
        fields.each(function(j, el) {
          $(el).val('').blur();
        });
        
        // clear the custom checkboxes differently
        var boxes = f.find('.irf-input-checkbox');
        boxes.each(function(j, el) {
          $(el).data('checked')($(el), 0);
        });
      });
    });
  }
  
  /************************************************/
  /* Riverprize - Case Studies Page (And Similar) */
  /************************************************/
  
  if ($('div#irf-content .irf-case-studies').size())
  {
    // locate the main container
    var d = $('div#irf-content');
    
    // attach a function to the ajax powered form so that the results may be enabled to locate
    d.find('.search-case-studies .irf-basic-ajax-powered-form').data('onsuccess', function(f, data) {
      var r = f.find('.irf-basic-ajax-results');
      
      // add behavior to each result such that
      // the appropriate study is opened up
      r.find('div.result a').click(function(e) {
        e.preventDefault();
        var s = $('div#irf-content .irf-case-studies');
        var id = parseInt($(this).find('.result_id').text());
        
        // the first step is to close all panels so that only the target is open
        s.find('.irf-slide-down-panel-with-arrow-trigger').each(function(i, el) {
          var el = $(el);
          var fn = el.data('close_panel');
          if (fn) fn(el, false);
        });
        
        // next locate the slide which should be active within the target group
        var pane = s.find('span.irf-case-study-id-'+id).parents('div.slide');
        
        // locate the slide down panel which contains the target slide and open
        var panel = pane.parents('.irf-slide-down-panel-with-arrow-trigger');
        var fn = panel.data('open_panel');
        if (fn) fn(panel, false);
        
        // locate the target pane show and set the active pane
        var show = pane.parents('div.irf-numbered-pane-slideshow');
        var fn = show.data('goto');
        if (fn) fn(show, parseInt(pane.find('.irf-slideshow-slide-index').text()));
        
        // locate the anchor which sits at the top of the panel which holds our target pane
        var a = panel.parents('.irf-case-study-group').find('a.irf-top-of-case-study-group');
        if (a.size()) window.location.href = '#'+a.attr('name');
      });
    });
  }
  
  /***************/
  /* Events Page */
  /***************/
  
  var d = $('div#irf-content.events');
  if (d.size())
  {
    // enable the more info links to open embedded event description lightbox
    d.find('div.events-directory table.list a.more-info').click(function(e) {
      e.preventDefault();
      var lb = $(this).parent().find('.irf-embedded-event-descriptoin .irf-event-description-lightbox').clone(true);
      plb__lightbox.open(lb);
    });
  }
  
  /*******************************/
  /* Contribute - Volunteer Page */
  /*******************************/
  
  var d = $('div#irf-content.contribute-volunteer');
  if (d.size())
  {
    // enable the apply links within the volunteer positions table or lightbox to pre-populate the volunteer form
    d.find('table.volunteer-positions-available a.apply, .irf-job-description-lightbox a.apply').click(function(e) {
      e.preventDefault();
      var d = $('div#irf-content.contribute-volunteer');
      var f = d.find('div.volunteer-database-form form');
      plb__lightbox.close();
      f.find('textarea[name=message]').val($(this).find('span.pre-populated-message').text()).addClass('irf-focused');
      window.location.href = '#volunteer_database_form';
      
      // after adjusting the page to make the form visible animate the form title to draw eye
      d.find('div.volunteer-database-form h1').effect('shake', { times:6, distance:1 }, 50);
    });
    
    // enable the more info links to open embedded job description lightbox
    d.find('table.volunteer-positions-available a.more-info').click(function(e) {
      e.preventDefault();
      var lb = $(this).parent().find('.irf-embedded-job-descriptoin .irf-job-description-lightbox').clone(true);
      plb__lightbox.open(lb);
    });
  }
  
  /*****************************/
  /* Contribute - Careers Page */
  /*****************************/
  
  var d = $('div#irf-content.contribute-careers');
  if (d.size())
  {
    // enable the apply links within the career positions table tor lightbox to pre-populate the applicant form
    d.find('table.career-positions-available a.apply, .irf-job-description-lightbox a.apply').click(function(e) {
      e.preventDefault();
      var d = $('div#irf-content.contribute-careers');
      var f = d.find('div.job-applicant-database-form form');
      plb__lightbox.close();
      f.find('textarea[name=message]').val($(this).find('span.pre-populated-message').text()).addClass('irf-focused');
      window.location.href = '#job_applicant_database_form';
      
      // after adjusting the page to make the form visible animate the form title to draw eye
      d.find('div.job-applicant-database-form h1').effect('shake', { times:6, distance:1 }, 50);
    });
    
    // enable the more info links to open embedded job description lightbox
    d.find('table.career-positions-available a.more-info').click(function(e) {
      e.preventDefault();
      var lb = $(this).parent().find('.irf-embedded-job-descriptoin .irf-job-description-lightbox').clone(true);
      plb__lightbox.open(lb);
    });
  }
  
  /******************************************/
  /* Resources - Image & Video Gallery Page */
  /******************************************/
  
  var d = $('div#irf-content.image-and-video-gallery');
  if (d.size())
  {
    // when the ajax search results are generated enable the opener links
    d.find('.search-galleries form').data('onsuccess', function(f, data) {
      $('body').data('irf__enable_gallery_image_links')();
      $('body').data('irf__enable_video_lightbox_openers')();
    });
  }
  
  /****************************************/
  /* Resources - Image Gallery Album Page */
  /****************************************/

  var d = $('div#irf-content.image-gallery-album');
  if (d.size())
  {
    // enable the accordion feature of the archived news
    d.find('.images .image .thumbnail').hover(function() {
      var thmb = $(this);
      var hvr = thmb.parent().find('.hover-preview');
      var w = hvr.find('.image-width').text();
      var h = hvr.find('.image-width').text();
      hvr.css('top', thmb.position().top - (h/4));
      hvr.fadeIn(100);
    },
    function() {
      var thmb = $(this);
      var hvr = thmb.parent().find('.hover-preview');
      hvr.fadeOut(100);
    });
  }
  
  /***********************************/
  /* E-Cards - Delivery Request Form */
  /***********************************/

  var d = $('div#irf-content.ecards-delivery-request');
  if (d.size())
  {
    // enable the continue button on the first step to alter the preview
    // form in such a way that it submit and continue to the next step
    d.find('div.steps div.step.one div.continue a').click(function(e) {
      e.preventDefault();
      var f = $(this).parents('form');
      if (!f.size()) return;
      f.find('input[name=irf__action]').val('ecards__step1_submit');
      f.get(0).submit();
    });
  }
  
  /*****************************/
  /* E-Cards - Style Selectors */
  /*****************************/
  
  $('body').data('irf__enable_ecard_style_selectors', function() {
    var els = $('.irf-ecard-style-selectors');
    els.each(function(i, el) {
      var el = $(el);
      if (el.data('irf-enabled')) return;
      el.data('irf-enabled', true);
      
      // enable the style selector to open on click
      // and enable the closing element on each too
      el.find('.style-selector').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        var p = $(this).find('.style-selector-popup');
        
        // as well as enable the closer to reverse
        if (!p.find('.closer').data('irf-enabled'))
          p.find('.closer').click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            var p = $(this).parents('.style-selector-popup');
            p.hide();
          }).data('irf-enabled', true);
        
        // ensure that all other selector popups are closed before we open the target one       
        $(this).parents('.irf-ecard-style-selectors').find('.style-selector-popup').hide();

        // after enabling
        // closer open
        p.show();
        
        // the ideal location for the top of the popup
        var ideal_y = p.css('top').replace('px', '');
          
        // locate the normal bottom edge of image and maximum
        var bottom_edge_y = p.offset().top + p.height();
        var max_y = $(window).scrollTop() + $(window).height();
        
        // compute and apply any adjustment
        var adjust_y = bottom_edge_y - max_y;
        if (adjust_y < 0) var adjust_y = 0;
        if (p.offset().top < $(window).scrollTop())
          adjust_y = -($(window).scrollTop() - p.offset().top);
        p.css('top', (ideal_y - adjust_y)+'px');
      });
      
      // this function accepted the main style selectors
      // element and will use the enclosing form values
      // to update the font and color selection previews
      el.data('irf__refresh_selected_styles', function(el) {
        var f = el.parents('form');
        var fnt = f.find('input[name=font]').val();
        var ts = f.find('input[name=text_size]').val();
        var clr = f.find('input[name=color]').val();
        var url = 'ecards_delivery_request_font_sampler.php';

        // update the selected font image preview
        var img = el.find('img.selected-font');
        img.attr('src', url+'?font='+fnt+'&mode=face_name&text_size=medium');
        
        // update the text size preview element
        var img = el.find('img.selected-text-size');
        img.attr('src', url+'?font='+fnt+'&mode=text_sizing&text_size='+ts);
        
        // and lastly updated the swatch to its current selected value
        el.find('.selected-color').css('background-color', '#'+clr);
      });
      
      // when a font choice is made we can update the enclosing form and refresh previews
      el.find('.style-selector.font .style-selector-popup .font-choice').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        var f = $(this).parents('form');
        var p = $(this).parents('.style-selector-popup');
        var fnt = $(this).find('.font-name').text();
        f.find('input[name=font]').val(fnt);
        
        // use the encapsulated function to refresh selections
        var el = $(this).parents('.irf-ecard-style-selectors')
        el.data('irf__refresh_selected_styles')(el);
        
        // close after 
        // selection
        p.hide();
      });
      
      // when a size choice is made we can update the enclosing form and refresh previews
      el.find('.style-selector.text-size .style-selector-popup .text-size-choice').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        var f = $(this).parents('form');
        var p = $(this).parents('.style-selector-popup');
        var ts = $(this).find('.text-size').text();
        f.find('input[name=text_size]').val(ts);
        
        // use the encapsulated function to refresh selections
        var el = $(this).parents('.irf-ecard-style-selectors')
        el.data('irf__refresh_selected_styles')(el);
        
        // close after 
        // selection
        p.hide();
      });
      
      // when a color choice is made we can update the enclosing form and refresh previews
      el.find('.style-selector.color .style-selector-popup .color-choice').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        var f = $(this).parents('form');
        var p = $(this).parents('.style-selector-popup');
        var clr = $(this).find('.color').text();
        f.find('input[name=color]').val(clr);
        
        // use the encapsulated function to refresh selections
        var el = $(this).parents('.irf-ecard-style-selectors')
        el.data('irf__refresh_selected_styles')(el);
        
        // close after 
        // selection
        p.hide();
      });
    });
  });
  $('body').data('irf__enable_ecard_style_selectors')();
});
