/*--------------------------------*/
/* Rudekat Records Store (Public) */
/*--------------------------------*/

jQuery(document).ready(function($) {
  
  /*********************/
  /* Image Pre-Loading */
  /*********************/
  
  // establish reusable
  // preloading method
  (function($){
    $('body').data('preloader', new Array());
    $('body').data('preload', function(src) {
      var arr = $('body').data('preloader');
      var img = new Image();
      img.src = src;
      arr[arr.length] = img;
    });
  })(jQuery);
  
  // use following to preload images start with other backgrounds
  $('body').data('preload')('pics/itm__ajax_lightbox_activity.gif');
  $('body').data('preload')('pics/itm__logo_myspace_colour.png');
  $('body').data('preload')('pics/itm__logo_facebook_colour.png');
  $('body').data('preload')('pics/itm__logo_youtube_colour.png');
  
  /***********/
  /* General */
  /***********/
  
  // temporarily disable some of the footer links properly classed
  $('#rkat-footer div.navigation a.disabled').css('opacity', 0.2);
  
  // ignore clicks on any 
  // disabled anchor links
  $('a').click(function(e) {
    if (!rkat__is_disabled($(this))) return;
    e.preventDefault();
    e.stopPropagation();
  });
  
  // shortcut function for checking
  // our proprietary disabled state
  function rkat__is_disabled(el) {
    if (el.parents('.rkat-disabled').size() ||
        el.hasClass('rkat-disabled')) return true;
    return false;
  }
  
  // the following function can be used to prevent enter
  // from submitting a form for all elements within container
  function rkat__disable_enter_submission(container) {
    var inputs = container.find('input:not(.rkat-enter-submission-disabled)');
    inputs.keypress(function(e) {
      if (e.which != 13) return;
      e.preventDefault();
      e.stopPropagation();
    });
    inputs.addClass('rkat-enter-submission-disabled');
  }
  
  // this function sets and unsets an invisible
  // div in front of all the contents of element
  function rkat__disabling_screen(el, state) {
    var s = el.find('.rkat-disabling-screen');
    if (!s.size()) return;
    if (!state) s.hide();
    else
    {
      // set the screen to the
      // proper size then show
      s.width(el.outerWidth());
      s.height(el.outerHeight());
      s.show();
    }
  }
  
  /**********************/
  /* Lightbox (General) */
  /**********************/
  
  // encapsulate the method for showing indicator
  $('body').data('plb__show_activity', function() {
    var el = $('<img src="pics/itm__ajax_lightbox_activity.gif" alt="Loading" style="display: block; width: 66px; height: 66px;"/>');
    plb__lightbox.open(el, true);
  });
  
  // encapsulate a method for displaying an error
  $('body').data('plb__show_error', function(msg) {
    var el = $('<div class="rkat-lightbox-error">'+
               '  <div class="rkat-message error">'+msg+'</div>'+
               '  <div class="closer"><span class="rkat-arrowed-link plb__closer"><a href="javascript:void(0)"><img src="pics/itm__arrow_blue.png" alt=""/></a><a class="rkat-blue" href="javascript:void(0)">CLOSE</a></span></div>'+
               '</div>');
    plb__lightbox.open(el);
  });
  
  /*********************************/
  /* Text Field/Area Auto-Labeling */
  /*********************************/
  
  function rkat__install_tfa_labeler() 
  {
    // this function may be called when 
    // additional form elements are added
    var tf = $('input.rkat.tf-first-name');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'First Name') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('First Name'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-last-name');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Surname') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Surname'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-email');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Email') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Email'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-phone');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Phone') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Phone'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-address1');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Address Line 1') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Address Line 1'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-address2');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Address Line 2') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Address Line 2'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-city');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'City') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('City'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-state');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'State/County') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('State/County'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-postcode');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Postcode') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Postcode'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('textarea.rkat.tf-message');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'Message') $(this).addClass('rkat-focused').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Message'); });      
      $(el).addClass('rkat-auto-labeler');
    });
    var tf = $('input.rkat.tf-artist-ep-or-album');
    tf.each(function(i, el) { 
      if ($(el).hasClass('rkat-auto-labeler')) return;
      $(el).focus(function(e) { if ($(this).val() == 'ARTIST, EP or ALBUM NAME') $(this).addClass('rkat-focused').removeClass('rkat-blurred').val(''); });
      $(el).blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').addClass('rkat-blurred').val('ARTIST, EP or ALBUM NAME'); });      
      $(el).addClass('rkat-auto-labeler');
    });
  }
  
  // run the installer once
  // for any existing elements
  rkat__install_tfa_labeler();
  
  // ensures that the auto
  // label values are ignored
  function rkat__real_val(el)
  {
    if (el.hasClass('tf-first-name') && (el.val() == 'First Name')) return '';
    if (el.hasClass('tf-last-name') && (el.val() == 'Surname')) return '';
    if (el.hasClass('tf-email') && (el.val() == 'Email')) return '';
    if (el.hasClass('tf-phone') && (el.val() == 'Phone')) return '';
    if (el.hasClass('tf-address1') && (el.val() == 'Address Line 1')) return '';
    if (el.hasClass('tf-address2') && (el.val() == 'Address Line 2')) return '';
    if (el.hasClass('tf-city') && (el.val() == 'City')) return '';
    if (el.hasClass('tf-state') && (el.val() == 'State/County')) return '';
    if (el.hasClass('tf-postcode') && (el.val() == 'Postcode')) return '';
    if (el.hasClass('tf-message') && (el.val() == 'Message')) return '';
    if (el.hasClass('tf-artist-ep-or-album') && (el.val() == 'ARTIST, EP or ALBUM NAME')) return '';
    return el.val();
  }
  
  /********/
  /* Home */
  /********/
  
  var d = $('div.rkat-content.home');
  if (d.size())
  {
    // when present prepare the proper animations for the slide show
    var el = d.find('div.rkat-standard-right-column div.slideshow');
    if (el.size())
    {
      // time to wait between transitions and duration of animation
      el.data('delay', parseFloat(el.find('span.delay').text())); // seconds
      el.data('transition', parseFloat(el.find('span.transition').text())); // seconds
      
      // esetablish the array of slides in the show element
      el.data('slides', el.find('div.slides').children().get());
      el.data('current', 0);
      el.data('preloader', new Array());
      
      // determine the current slide by locating the first visible slide within the array and saving the offset
      for (var j=0; j<el.data('slides').length; j++) if (!($(el.data('slides')[j]).hasClass('rkat-hidden'))) el.data('current', j);
      for (var j=0; j<el.data('slides').length; j++) { el.data('preloader')[j] = new Image(); var sl = $(el.data('slides')[j]); el.data('preloader')[j].src = sl.is('img') ? sl.attr('src') : sl.find('img').attr('src'); }
      
      // associate a rotation function with the
      // feature requiring itself as parameter
      el.data('rotate_slides', function(el) {
        
        // when no slides present abort rotations
        if (el.data('slides').length < 1) return;
        
        // determine the next index using a modulus operator
        el.data('next', ((el.data('current') + 1) % el.data('slides').length));
        var c = $(el.data('slides')[el.data('current')]);
        var n = $(el.data('slides')[el.data('next')]);
        
        // stop animation if there is only one slide in show
        if (el.data('next') == el.data('current')) return;
        
        // begin animation of current and next
        c.fadeOut(el.data('transition')*1000);
        n.fadeIn(el.data('transition')*1000);
        
        // update our current offset
        el.data('current', el.data('next'));
        
        // ensure that the next slide
        // is visible when it fades in
        n.removeClass('rkat-hidden');
        
        // schedule the next rotation of the slide show images used absolute references to the slide show element
        setTimeout("jQuery('div.rkat-content.home div.rkat-standard-right-column div.slideshow').data('rotate_slides')("+
                   "jQuery('div.rkat-content.home div.rkat-standard-right-column div.slideshow'))", el.data('delay') * 1000);
      });
      
      // schedule the first rotation of the slide show images used absolute references to the slide show element
      setTimeout("jQuery('div.rkat-content.home div.rkat-standard-right-column div.slideshow').data('rotate_slides')("+
                 "jQuery('div.rkat-content.home div.rkat-standard-right-column div.slideshow'))", el.data('delay') * 1000);
    }
    
    // in order to allow the history panel to slide into place and
    // the container to adjust its height appropriately use the following
    // routines to detect the height necessary and animate the change
    d.find('div.welcome-and-history a.history').click(function(e) {
      var wh = $(this).parents('div.welcome-and-history');
      var ph = wh.find('div.pane.history');
      var pw = wh.find('div.pane.welcome');
      ph.animate({ left: '0px' }, 'slow', 'swing');
      pw.animate({ left: '315px' }, 'slow', 'swing');
      wh.animate({ height: ph.height() }, 'slow', 'swing');
    });
    d.find('div.welcome-and-history a.welcome').click(function(e) {
      var wh = $(this).parents('div.welcome-and-history');
      var ph = wh.find('div.pane.history');
      var pw = wh.find('div.pane.welcome');
      ph.animate({ left: '-315px' }, 'slow', 'swing');
      pw.animate({ left: '0px' }, 'slow', 'swing');
      wh.animate({ height: pw.height() }, 'slow', 'swing');
    });
    
    // enable the older months link to expand and collapse the archive links
    d.find('div.news-archive div.older-months-link a').click(function(e) {
      e.preventDefault();
      var na = $(this).parents('div.news-archive');
      var om = na.find('div.older-months');
      if ($(this).parents('.rkat-arrowed-link').hasClass('down')) 
      {
        // we are opening the list of months
        om.slideDown('normal', function() { 
          var na = $(this).parents('div.news-archive');
          var oml = na.find('div.older-months-link');
          oml.removeClass('down').addClass('up');
        });
      }
      else 
      {
        // we are closing the list of months
        om.slideUp('normal', function() { 
          var na = $(this).parents('div.news-archive');
          var oml = na.find('div.older-months-link');
          oml.removeClass('up').addClass('down');
        });
      }
    });
  }
  
  /*********/
  /* Music */
  /*********/
  
  var d = $('div.rkat-content.music');
  if (d.size())
  {
    // enable the search form submission arrow to operate
    d.find('form.search td.arrow img').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var f = $(this).parents('form');
      f.find('input[name=search_pattern]').val(rkat__real_val(f.find('input[name=search_pattern]')));
      f.find('td.ajax img').show();
      f.get(0).submit();
    });
    
    // add faded effects using opacity to the arrow navigation links which are not relevant
    d.find('div.search-results div.navigation div.links .rkat-disabled img').css('opacity', 0.35);  
    d.find('div.browsing-results div.navigation div.links .rkat-disabled img').css('opacity', 0.35);  
    
    // allow the navigation links to set the proper page number then submit form
    d.find('div.search-results div.navigation div.links a').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if ($(this).hasClass('rkat-disabled')) return;
      var p = parseInt($(this).find('span.page').text());
      var f = $('div.rkat-content.music form.search');
      f.find('input[name=current_page]').val(p);
      f.get(0).submit();
    });
    d.find('div.browsing-results div.navigation div.links a').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if ($(this).hasClass('rkat-disabled')) return;
      var p = parseInt($(this).find('span.page').text());
      var f = $('div.rkat-content.music form.browse');
      f.find('input[name=current_page]').val(p);
      f.get(0).submit();
    });
  }
  
  /*****************/
  /* Music Juekbox */
  /*****************/
  
  // first establish a function which can be called to open a lightbox after loading
  // this function can be associated with click handlers or explicitly called as needed
  $('body').data('open_jukebox_lightbox', function(product_id, autoplay_track_id) {
    
    // 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
      {
        // create a jquery 
        // object from the
        // raw html data
        var lb = $(data.html);
        
        // establish a shortcut to setting the volume and embed with the player
        lb.find('#rkat-music-player').data('set_volume', function(player, vol) {
          var sl = player.find('div.volume-slider');
          if (vol === undefined) vol = 0.75;
          var x = vol * 62.0;
          sl.css('left', x);
          var full = sl.parent();
          full.css('width', x);
          $('body').data('last_jukebox_vol', vol);
          player.data('refresh_volume')();
        });
        
        // this function is designed to be called repeated to provide fade
        lb.find('#rkat-music-player').data('refresh_volume', function() {
          var vol = $('body').data('last_jukebox_vol');
          var s = soundManager.getSoundById('s');
          if (!s) return;
          
          // auto fade out during the last portion of song
          var remaining = 1.0 - (s.position / s.duration);
          var fade = remaining / 0.10;
          if (fade > 1) fade = 1;
          s.setVolume(vol*100*fade);
        });
        
        // restore the last volume used for the jukebox since that last page reload although not perfect memory
        lb.find('#rkat-music-player').data('set_volume')(lb.find('#rkat-music-player'), $('body').data('last_jukebox_vol'));
        
        // enable the volume slider to move and show its current volume level 
        lb.find('#rkat-music-player div.volume-slider').drag(function(e, dd){
            var sl = $(this);
          
            // keep the slider 
            // position within
            // some boundaries
            var x = dd.offsetX;
            if (x < 0) x = 0;
            if (x > 62) x = 62;
            var vol = x / 62.0;
            
            // locate the music player and adjust volume
            var player = $(this).parents('#rkat-music-player');
            player.data('set_volume')(player, vol);
          
            // remember the last volume used here
            $('body').data('last_jukebox_vol', vol);
          },
          { relative: true }
        );
        
        // also enable the volume to be changed by directly clicking controls
        lb.find('#rkat-music-player div.volume-meter.empty').click(function(e) {
          e.preventDefault();
          var x = e.pageX - $(this).offset().left;
          var y = e.pageY - $(this).offset().top;
          if (x < 0) x = 0;
          if (x > 62) x = 62;
          var vol = x / 62.0;
          
          // locate the music player and adjust volume
          var player = $(this).parents('#rkat-music-player');
          player.data('set_volume')(player, vol);
        });
        
        // enable the play button to start playback from a paused or stopped position
        lb.find('#rkat-music-player div.playback-controls .play').click(function(e) {
          e.preventDefault();
          var s = soundManager.getSoundById('s');
          if (!s) return;
          if (!s.playState) s.play();
          if (s.paused) s.resume();
          $('#rkat-music-player').data('refresh_current_time')();
        });
        
        // enable the pause button to pause playback at the current audio position
        lb.find('#rkat-music-player div.playback-controls .pause').click(function(e) {
          e.preventDefault();
          var s = soundManager.getSoundById('s');
          if (!s) return;
          s.pause();
          $('#rkat-music-player').data('refresh_current_time')();
        });
        
        // enable the stop function to be called from outside
        lb.find('#rkat-music-player').data('stop', function() {
          var s = soundManager.getSoundById('s');
          if (!s) return;
          if (s.playState) s.stop();
          $('#rkat-music-player').data('refresh_current_time')(0);
        });
        
        // enable the pause button to pause playback at the current audio position
        lb.find('#rkat-music-player div.playback-controls .stop').click(function(e) {
          e.preventDefault();
          $('#rkat-music-player').data('stop')();
        });
        
        // enable the fast forward button to advance the position by a set step size
        lb.find('#rkat-music-player div.playback-controls .rewind').click(function(e) {
          e.preventDefault();
          var s = soundManager.getSoundById('s');
          if (!s) return;
          if (!s.playState) return;
          var jump = 7*1000;
          var p = s.position;
          if (p-jump < 0) s.setPosition(0);
          else s.setPosition(p-jump);
          $('#rkat-music-player').data('refresh_current_time')();
        });
        
        // enable the fast forward button to advance the position by a set step size on click
        lb.find('#rkat-music-player div.playback-controls .fast-forward').click(function(e) {
          e.preventDefault();
          var s = soundManager.getSoundById('s');
          if (!s) return;
          if (!s.playState) return;
          var jump = 7*1000;
          var p = s.position;
          if (p+jump > p.duration) s.setPosition(s.duration - (1*1000));
          else s.setPosition(p+jump);
          $('#rkat-music-player').data('refresh_current_time')();
        });
        
        // embed a function to simplify the process of updating total time
        lb.find('#rkat-music-player').data('refresh_total_time', function() {
          var s = soundManager.getSoundById('s');
          if (!s) return;
          var seconds = s.duration / 1000.0;
          var minutes = seconds / 60.0;
          var seconds = Math.round(60 * (minutes - Math.floor(minutes)));
          minutes = Math.floor(minutes);
          seconds = seconds.toString().length < 2 ? '0'+seconds : seconds;
          $('#rkat-music-player').find('.total-time').text(minutes+':'+seconds);
        });
        
        // embed a function to simplify the process of updating current time
        lb.find('#rkat-music-player').data('refresh_current_time', function(t) {
          var s = soundManager.getSoundById('s');
          if (!s) return;
          var seconds = (t === undefined ? s.position : t) / 1000.0;
          var minutes = seconds / 60.0;
          var seconds = Math.round(60 * (minutes - Math.floor(minutes)));
          minutes = Math.floor(minutes);
          seconds = seconds.toString().length < 2 ? '0'+seconds : seconds;
          $('#rkat-music-player').find('.current-time').text(minutes+':'+seconds);
        });
        
        // embed a simple function which handles all proper actions to play track
        lb.find('#rkat-music-player').data('load_and_play', function(fn, title) {
          var s = soundManager.getSoundById('s');
          if (s) s.destruct();
          
          // begin the process by creating a
          // sound object using our global id
          // and configuring the proper functions
          var s = soundManager.createSound({
            id: 's', 
            url: '/gtcms/catalog/'+fn,
            whileloading: function() {
              
              // update the total time to show loading progress
              $('#rkat-music-player').data('refresh_total_time')();
            },
            onload: function() {
                
              // after loading set the proper volume refresh the
              // total time and hide the indication of loading
              this.setVolume($('body').data('last_jukebox_vol')*100);
              $('#rkat-music-player').data('refresh_total_time')();
              $('#rkat-music-player').find('.buffering').hide();
            },
            whileplaying: function() {
              
              // simply update the current time indicator during play                
              $('#rkat-music-player').data('refresh_current_time')();
              $('#rkat-music-player').data('refresh_volume')();
            },
            onstop: function() {
              
              // ensure proper items
              // are updated on end
              this.setPosition(0);
              $('#rkat-music-player').data('refresh_current_time')(0);
              $('#rkat-music-player').data('refresh_volume')();
            },
            onfinish: function() {
              
              // ensure proper items
              // are updated on end
              this.setPosition(0);
              $('#rkat-music-player').data('refresh_current_time')(0);
              $('#rkat-music-player').data('refresh_volume')();
            }
          });
          
          // always begin by showing the loading indicators
          $('#rkat-music-player').find('.buffering').show();
          $('#rkat-music-player-currently-playing').text(title ? title : fn);
          
          // then load
          // and start
          s.play();
        });
        
        // enable the track names in the table to play their samples
        lb.find('table.tracks tr.track a.play').click(function(e) {
          e.preventDefault();
          var td = $(this).parents('table.tracks td');
          var fn = td.find('span.filename').text();
          var titl = td.find('span.title').text();
          if (fn) $('#rkat-music-player').data('load_and_play')(fn, titl);
        });
        
        // enable clicking on the checkboxes to work
        lb.find('img.checkbox').click(function(e) {
          e.preventDefault();
          $(this).toggleClass('checked');
        });
        
        // enable the add to cart and checkout links to function by first
        // adding the selection items to the cart then showing added lightbox
        // or proceeding directly to the shopping cart page to begin checkout
        lb.find('div.shopping-controls div.links .add').click(function(e) {
          e.preventDefault();
          var link = $(this);
          
          // 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();
            
            // no matter what our response update the page totals
            $('body').data('refresh_total_quantity_of_items')();
                      
            // 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);
            }
            
            // we may just redirect to the cart
            else if (link.hasClass('checkout'))
            {
              // peform a redirect to the shopping cart
              window.location.href = 'shopping_cart.php';
            }
            
            // otherwise proceed
            // to open lightbox
            else
            {
              // create a jquery 
              // object from the
              // raw html data
              var lb = $(data.html);
              
              // before opening the lightbox add functionality
              // to the cancel link which makes proper request
              lb.find('.cancel-link').click(function(e) {
                e.preventDefault();
                var td = $(this).parents('td.cancel');
                var just_added_ids = td.find('span.just-added-cart-item-ids').text();
                var just_added_quantities = td.find('span.just-added-cart-item-quantities').text();
                var aja = td.find('div.ajax-activity');
                
                // show the 
                // indicator
                aja.show();
                
                // 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 a cancel action we provide no feedback other
                  // than updating the total items in cart on the page
                  $('body').data('refresh_total_quantity_of_items')();
                  
                  // when the special back to jukebox link is present return
                  // there when the add to cart action is canceled or close
                  var atc = td.parents('.rkat-lightbox-added-to-cart');
                  var album_id = parseInt(atc.find('.back-to-jukebox .album-id').text());
                  if (album_id) $('body').data('open_jukebox_lightbox')(album_id, 'disable');
                  else plb__lightbox.close();
                };
                
                // compose and execute ajax request
                $.ajax({ url: 'shopping_cart.php',
                         type: 'POST',
                         cache: false,               
                         data: { 'rkat_store': 'ajax_undo_cart_addition',
                                 'just_added_cart_item_ids': just_added_ids,
                                 'just_added_cart_item_quantities': just_added_quantities
                               },
                         dataType: 'json',
                         success: complete,
                         error: complete });
              });
              
              // when the back to link is properly classed enable it
              lb.find('.back-to-jukebox-link').click(function(e) {
                e.preventDefault();
                var atc = $(this).parents('.rkat-lightbox-added-to-cart');
                var album_id = parseInt(atc.find('.back-to-jukebox .album-id').text());
                if (album_id) $('body').data('open_jukebox_lightbox')(album_id, 'disable');
                else plb__lightbox.close();
              });
            
              // after adding proper behaviors
              // display the lightbox content
              plb__lightbox.open(lb);
            }
          };
          
          // extract the selected products
          // on the album jukebox lightbox
          var product_ids = new Array();
          var quantities = new Array();
          var jb = $(this).parents('.rkat-lightbox-album-jukebox');
          jb.find('img.checkbox.checked').each(function(i, el) {
            var el = $(el);
            product_ids[product_ids.length] = el.parent().find('.rkat-product-id').text();
            quantities[quantities.length] = 1;
          });
          
          // we will extract the album id featured in the jukebox too
          var album_id = parseInt(jb.find('.jukebox-album-id').text());
          
          // do not do anything without
          // at least one product to add
          // go to cart page on checkout
          if (!product_ids.length) 
            if (link.hasClass('checkout')) { window.location.href = 'shopping_cart.php'; return; }
            else return;
          
          // show the indicator within a lightbox
          $('body').data('plb__show_activity')();
          
          // compose and execute ajax request
          $.ajax({ url: 'shopping_cart.php',
                   type: 'POST',
                   cache: false,               
                   data: { 'rkat_store': 'ajax_add_product',
                           'mode': 'multiple',
                           'product_ids': product_ids.join('|'),
                           'quantities': quantities.join('|'),
                           'back_to_jukebox': album_id
                         },
                   dataType: 'json',
                   success: complete,
                   error: complete });
        });
        
        // after adding proper behaviors display the lightbox content enabling a close event to stop music playing
        plb__lightbox.open(lb, false, function() { var fn = $('#rkat-music-player').data('stop'); if (fn) fn(); });
        
        // when auto play has been configured begin playing the selected track
        var fn = $('#rkat-music-player-autoplay').find('span.filename').text();
        var titl = $('#rkat-music-player-autoplay').find('span.title').text();
        if (fn) $('#rkat-music-player').data('load_and_play')(fn, titl);
      }
    };
    
    // show the indicator within a lightbox
    $('body').data('plb__show_activity')();
    
    // compose and execute ajax request
    $.ajax({ url: 'shopping_cart.php',
             type: 'POST',
             cache: false,               
             data: { 'rkat_store': 'ajax_open_jukebox',
                     'product_id': product_id,
                     'autoplay_track_id': autoplay_track_id
                   },
             dataType: 'json',
             success: complete,
             error: complete });
  });
  
  // this function which we will embed with the body can be
  // called whenever links exists on the page that we be
  // used to open the jukebox lightbox for a given album
  $('body').data('enable_jukebox_lightbox_openers', function() {
    var openers = $('body').find('.rkat-jukebox-opener');
    openers.each(function(i, el) {
      el = $(el);
      if (el.data('jukebox-opening-enabled')) return;
      el.click(function(e) {
        e.preventDefault();
        
        // extract the product from a hidden tag within jukebox opener
        var product_id = parseInt($(this).find('.rkat-product-id').text());
        var autoplay_track_id = $(this).find('.rkat-autoplay-track-id').text();
        
        // use the encapsulated function perform the opening of the jukebox
        $('body').data('open_jukebox_lightbox')(product_id, autoplay_track_id);
      });
      
      // after enabling the opener set flag
      // to prevent us from enabling again
      el.data('jukebox-opening-enabled', true);
    });
  });
  
  // enable all relevant links to be enabled initially
  $('body').data('enable_jukebox_lightbox_openers')();
  
  /****************************/
  /* Tickets Page Slide Shows */
  /****************************/
  
  var d = $('div.rkat-content.tickets');
  if (d.size())
  {
    // prepare each featured slide show
    var ft = d.find('div.featured-ticket');
    ft.each(function(i, el) {
      el = $(el);
      
      // time to wait between transitions
      // and duration of each animation
      el.data('delay', 6); // seconds
      el.data('transition', 1.5); // seconds
      
      // remember this slide show
      // index among all tickets
      el.data('index', i); 
      
      // esetablish the array of slides in the element
      el.data('slides', el.find('div.slides img').get());
      el.data('current', 0);
      el.data('preloader', new Array());
      
      // determine the current slide by locating the first visible slide within the array and saving the offset
      for (var j=0; j<el.data('slides').length; j++) if (!($(el.data('slides')[j]).hasClass('rkat-hidden'))) el.data('current', j);
      for (var j=0; j<el.data('slides').length; j++) { el.data('preloader')[j] = new Image(); el.data('preloader')[j].src = $(el.data('slides')[j]).attr('src'); }
      
      // associate a rotation function with the
      // feature requiring itself as parameter
      el.data('rotate_slides', function(el) {
        
        // when no slides present abort rotations
        if (el.data('slides').length < 1) return;
        
        // determine the next index using a modulus operator
        el.data('next', ((el.data('current') + 1) % el.data('slides').length));
        var c = $(el.data('slides')[el.data('current')]);
        var n = $(el.data('slides')[el.data('next')]);
        
        // stop animation if there is only one slide in show
        if (el.data('next') == el.data('current')) return;
        
        // begin animation of current and next
        c.fadeOut(el.data('transition')*1000);
        n.fadeIn(el.data('transition')*1000);
        
        // update our current offset
        el.data('current', el.data('next'));
        
        // ensure that the next slide
        // is visible when it fades in
        n.removeClass('rkat-hidden');
        
        // schedule the next rotation of the slide show images used absolute references to the slide show element
        setTimeout("jQuery(jQuery('div.rkat-content.tickets div.featured-ticket').get("+el.data('index')+")).data('rotate_slides')("+
                   "jQuery(jQuery('div.rkat-content.tickets div.featured-ticket').get("+el.data('index')+")))", el.data('delay') * 1000);
        
      });
      
      // schedule the first rotation of the slide show images used absolute references to the slide show element
      setTimeout("jQuery(jQuery('div.rkat-content.tickets div.featured-ticket').get("+el.data('index')+")).data('rotate_slides')("+
                 "jQuery(jQuery('div.rkat-content.tickets div.featured-ticket').get("+el.data('index')+")))", el.data('delay') * 1000);
      
    });
  }
  
  /**************************/
  /* Event Page Slide Shows */
  /**************************/

  var d = $('div.rkat-content.event');
  if (d.size())
  {
    // prepare each featured slide show
    var ft = d.find('div.featured-ticket');
    ft.each(function(i, el) {
      el = $(el);
      
      // time to wait between transitions
      // and duration of each animation
      el.data('delay', 6); // seconds
      el.data('transition', 1.5); // seconds
      
      // remember this slide show
      // index among all tickets
      el.data('index', i); 
      
      // esetablish the array of slides in the element
      el.data('slides', el.find('div.slides img').get());
      el.data('current', 0);
      el.data('preloader', new Array());
      
      // determine the current slide by locating the first visible slide within the array and saving the offset
      for (var j=0; j<el.data('slides').length; j++) if (!($(el.data('slides')[j]).hasClass('rkat-hidden'))) el.data('current', j);
      for (var j=0; j<el.data('slides').length; j++) { el.data('preloader')[j] = new Image(); el.data('preloader')[j].src = $(el.data('slides')[j]).attr('src'); }
      
      // associate a rotation function with the
      // feature requiring itself as parameter
      el.data('rotate_slides', function(el) {
        
        // when no slides present abort rotations
        if (el.data('slides').length < 1) return;
        
        // determine the next index using a modulus operator
        el.data('next', ((el.data('current') + 1) % el.data('slides').length));
        var c = $(el.data('slides')[el.data('current')]);
        var n = $(el.data('slides')[el.data('next')]);
        
        // stop animation if there is only one slide in show
        if (el.data('next') == el.data('current')) return;
        
        // begin animation of current and next
        c.fadeOut(el.data('transition')*1000);
        n.fadeIn(el.data('transition')*1000);
        
        // update our current offset
        el.data('current', el.data('next'));
        
        // ensure that the next slide
        // is visible when it fades in
        n.removeClass('rkat-hidden');
        
        // schedule the next rotation of the slide show images used absolute references to the slide show element
        setTimeout("jQuery(jQuery('div.rkat-content.event div.featured-ticket').get("+el.data('index')+")).data('rotate_slides')("+
                   "jQuery(jQuery('div.rkat-content.event div.featured-ticket').get("+el.data('index')+")))", el.data('delay') * 1000);
        
      });
      
      // schedule the first rotation of the slide show images used absolute references to the slide show element
      setTimeout("jQuery(jQuery('div.rkat-content.event div.featured-ticket').get("+el.data('index')+")).data('rotate_slides')("+
                 "jQuery(jQuery('div.rkat-content.event div.featured-ticket').get("+el.data('index')+")))", el.data('delay') * 1000);
      
    });
  }
  
  /***************/
  /* Merchandise */
  /***************/
  
  var d = $('div.rkat-content.merchandise');
  if (d.size())
  {
    // add faded effects using opacity to the arrow navigation links which are not relevant here
    d.find('div.browsing-results div.navigation div.links .rkat-disabled img').css('opacity', 0.35);
    
    // allow the navigation links to set the proper page number then submit form
    d.find('div.browsing-results div.navigation div.links a').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if ($(this).hasClass('rkat-disabled')) return;
      var p = parseInt($(this).find('span.page').text());
      var f = $('div.rkat-content.merchandise form.browse');
      f.find('input[name=current_page]').val(p);
      f.get(0).submit();
    });
    
    // first establish a function which can be called to open a lightbox
    // this function can be associated with click handlers or called
    $('body').data('open_merchandise_lightbox', function(product) {
      var p = product;
      
      // retrieve the embedded lightbox html and clone it then proceed to populate elements    
      var lb = $('#rkat-embedded-merchandise-viewer .rkat-merchandise-lightbox').clone();
      lb.find('.rkat-product-id').html(p.id);
      lb.find('.name').html(p.name);
      lb.find('.price').html(p.price);
      lb.find('.description').html(p.long_description);
      if (!p.is_purchaseable) lb.find('.add-to-cart').addClass('sold-out'); 
      else lb.find('.add-to-cart').removeClass('sold-out');
      lb.find('img.full-image').attr('src', p.full_image);
      if (p.full_image_w > p.full_image_h) lb.addClass('landscape').removeClass('portrait'); 
      else
      {
        // dynamically adjust the width of the lightbox
        lb.removeClass('landscape').addClass('portrait');
        lb.find('.insets').css('width', p.full_image_w + 8 + 364);
      } 
      
      // we do not want to open
      // the lightbox until the
      // image is fully loaded
      var img = new Image();
      img.src = p.full_image;
      img._lightbox = lb;
      img.onload = function() { 
        plb__lightbox.open(this._lightbox); 
        $('body').data('enable_ajax_buy_links')();
      };
      
      // show the indicator within a lightbox
      $('body').data('plb__show_activity')();
    });
    
    // this function which we will embed with the body can be
    // called whenever links exists on the page that we be
    // used to open the merchandise lightbox for a given product
    $('body').data('enable_merchandise_lightbox_openers', function() {
      var openers = $('body').find('.rkat-merchbox-opener');
      openers.each(function(i, el) {
        el = $(el);
        if (el.data('merchbox-opening-enabled')) return;
        el.click(function(e) {
          e.preventDefault();
          
          // all the data necessary to open the box is embedded
          // so extract and prepare into a object as parameter
          var m = $(this).parents('.rkat-merchandise-product');
          var p = new Object();
          p.id = parseInt($(this).find('.rkat-product-id').text());
          p.name = m.find('.name').text();
          p.price = m.find('.price').text();
          p.long_description = m.find('.long-description').text();
          p.full_image = m.find('.full-image').text();
          p.full_image_w = parseInt(m.find('.full-image-width').text());
          p.full_image_h = parseInt(m.find('.full-image-height').text());
          p.is_purchaseable = (m.find('.is-purchaseable').text() == 'YES' ? true : false);
          
          // use the encapsulated function to open lightbox
          $('body').data('open_merchandise_lightbox')(p);
        });
        
        // after enabling the opener set flag
        // to prevent us from enabling again
        el.data('merchbox-opening-enabled', true);
      });
    });
    
    // enable all relevant links to be enabled initially
    $('body').data('enable_merchandise_lightbox_openers')();
  }
  
  /*******************************************************/
  /* Shopping Cart Features (Used Across Multiple Pages) */
  /*******************************************************/
  
  // embed a simple function to contact the system and retrieve
  // the total quantity of items in the cart useful after additions
  $('body').data('refresh_total_quantity_of_items', function() {
    
    // 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 just dont update page content
      if ((!data.success) || (status != 'success')) return;
      
      // determine from the response if we use items
      var plural = data.total == '1' ? false : true;
      
      // simply update the plural status and
      // the count with the count string given
      var el = $('.rkat-whats-in-your-cart');
      if (plural) el.find('span.plural').show(); else el.find('span.plural').hide();
      el.find('span.count').text(data.total);
    };
    
    // compose and execute ajax request
    $.ajax({ url: 'shopping_cart.php',
             type: 'POST',
             cache: false,               
             data: { 'rkat_store': 'ajax_total_quantity_of_items_in_cart' },
             dataType: 'json',
             success: complete,
             error: complete });
  });
  
  // this function which we will embed with the body can be
  // called whenever ajax purchasing links need to be powered
  // which might be useful when links are added via ajax
  $('body').data('enable_ajax_buy_links', function() {
    var links = $('body').find('.rkat-ajax-buy');
    links.each(function(i, el) {
      el = $(el);
      if (el.data('ajax-buy-enabled')) return;
      el.click(function(e) {
        e.preventDefault();
        
        // extract the product and quantity from a hidden tag within buy link
        var product_id = parseInt($(this).find('.rkat-product-id').text());
        var quantity = parseInt($(this).find('.rkat-product-qty').text());
        if (!quantity || quantity < 1) quantity = 1;
        
        // when special ticket products are detected use special popup
        if ($('body').data('island_vibe_tickets') instanceof Array)
          for (var j=0; j<$('body').data('island_vibe_tickets').length; j++)
            if ($('body').data('island_vibe_tickets')[j] == product_id) 
            { $('body').data('open_island_vibe_popup')(); return; }
        
        // 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();
          
          // no matter what our response update the page totals
          $('body').data('refresh_total_quantity_of_items')();
                    
          // 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
          {
            // create a jquery 
            // object from the
            // raw html data
            var lb = $(data.html);
            
            // before opening the lightbox add functionality
            // to the cancel link which makes proper request
            lb.find('.cancel-link').click(function(e) {
              e.preventDefault();
              var td = $(this).parents('td.cancel');
              var just_added_ids = td.find('span.just-added-cart-item-ids').text();
              var just_added_quantities = td.find('span.just-added-cart-item-quantities').text();
              var aja = td.find('div.ajax-activity');
              
              // show the 
              // indicator
              aja.show();
              
              // 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 a cancel action we provide no feedback other
                // than updating the total items in cart on the page
                $('body').data('refresh_total_quantity_of_items')();
                plb__lightbox.close();
              };
              
              // compose and execute ajax request
              $.ajax({ url: 'shopping_cart.php',
                       type: 'POST',
                       cache: false,               
                       data: { 'rkat_store': 'ajax_undo_cart_addition',
                               'just_added_cart_item_ids': just_added_ids,
                               'just_added_cart_item_quantities': just_added_quantities
                             },
                       dataType: 'json',
                       success: complete,
                       error: complete });
            });
          
            // after adding proper behaviors
            // display the lightbox content
            plb__lightbox.open(lb);
          }
        };
        
        // compose and execute ajax request
        $.ajax({ url: 'shopping_cart.php',
                 type: 'POST',
                 cache: false,               
                 data: { 'rkat_store': 'ajax_add_product',
                         'mode': 'single',
                         'product_id': product_id,
                         'quantity': quantity
                       },
                 dataType: 'json',
                 success: complete,
                 error: complete });
      });
      
      // after enabling the link set flag
      // to prevent us from enabling again
      el.data('ajax-buy-enabled', true);
    });
  });
  
  // enable all purchasing links initially
  $('body').data('enable_ajax_buy_links')();
  
  /***********************************/
  /* Shopping Cart Review & Checkout */
  /***********************************/
  
  var d = $('div#rkat-shopping-cart-review');
  if (d.size())
  {
    // when second step is hidden bring
    // it to visible but faded and disabled
    var od = $('div#rkat-order-details');
    if (od.hasClass('rkat-hidden')) {
      od.addClass('rkat-disabled');
      od.css('opacity', 0.35);
      rkat__disabling_screen(od, true);
      od.show(); 
    }
    
    // disable enter submitting on form
    rkat__disable_enter_submission(od);
    
    // prepare the proper state for link
    // which continues based on the cart
    var sc = $('div#rkat-shopping-cart');
    if (sc.find('p.no-products').size())
      sc.find('div.navigation-links div.right').hide();
    else sc.find('div.navigation-links div.right').show();
    
    /////////// SHOPPING CART ///////////
    
    // declare a resinstallation
    // function at the top here
    var reinstall_table = null;
    
    // establish an update link handler
    // which can be added to table element
    var update_handler = function(e) {
      e.preventDefault();
      e.stopPropagation();
      var sc = $('div#rkat-shopping-cart');
      var tbl = $(this).parents('table.rkat-shopping-cart');
      var td = $(this).parents('td.qty');
      var tr = $(this).parents('tr.item');
      var cart_item_id = parseInt(tr.find('td.number span.cart-item-id').text());
      var qty = parseInt(td.find('input[name=qty]').val());
      var ajs = td.find('img.ajax');
      ajs.show();
      
      // 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();
        var msg = sc.find('.rkat-message');
        
        // for any type of error find the message box
        // on the page and insert the proper text there
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'System/Network error; Please try again.';
          msg.addClass('error').removeClass('notice');
          msg.text(error);
        }
        
        // successful removes
        // all message text
        else msg.text('');
          
        // call the function to place
        // the updated table on page
        reinstall_table(data.html);
      };
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: { 'rkat_store': 'ajax_cart_update',
                       'cart_item_id': cart_item_id,
                       'quantity': qty
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    };
    
    // establish an update link handler
    // which can be added to table element
    var delete_handler = function(e) {
      e.preventDefault();
      e.stopPropagation();
      var sc = $('div#rkat-shopping-cart');
      var tbl = $(this).parents('table.rkat-shopping-cart');
      var td = $(this).parents('td.delete');
      var tr = $(this).parents('tr.item');
      var cart_item_id = parseInt(tr.find('td.number span.cart-item-id').text());
      var ajs = td.find('img.ajax');
      ajs.show();
      
      // 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();
        var msg = sc.find('.rkat-message');
        
        // for any type of error find the message box
        // on the page and insert the proper text there
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'System/Network error; Please try again.';
          msg.addClass('error').removeClass('notice');
          msg.text(error);
        }
        
        // successful removes
        // all message text
        else msg.text('');
        
        // call the function to place
        // the updated table on page
        reinstall_table(data.html);
      };
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: { 'rkat_store': 'ajax_cart_delete',
                       'cart_item_id': cart_item_id
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    };
    
	// WPE
    // establish an update link handler
    // which can be added to table element
    var remove_handler = function(e) {
      e.preventDefault();
      e.stopPropagation();
      var sc = $('div#rkat-shopping-cart');
      var tbl = $(this).parents('table.rkat-shopping-cart');
      var td = $(this).parents('td.remove');
      var tr = $(this).parents('tr.item');
      var cart_item_id = parseInt(tr.find('td.number span.cart-item-id').text());
      var ajs = td.find('img.ajax');	  
      ajs.show();
      
      // 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();
        var msg = sc.find('.rkat-message');
        
        // for any type of error find the message box
        // on the page and insert the proper text there
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'System/Network error; Please try again.';
          msg.addClass('error').removeClass('notice');
          msg.text(error);
        }
        
        // successful removes
        // all message text
        else msg.text('');
        
        // call the function to place
        // the updated table on page
        reinstall_table(data.html);
      };
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: { 'rkat_store': 'ajax_cart_remove',
                       'cart_item_id': cart_item_id
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    };	
	// WPE
	
	
    // encapsulate the process of replacing
    // a new cart table into page with handlers
    var reinstall_table = function(html) {
      var d = $('div#rkat-shopping-cart-review');
      var container = d.find('.cart-table-container');
      container.html(html);
      container.find('td.qty a').click(update_handler);
      container.find('td.delete a').click(delete_handler);
	  container.find('td.remove a').click(remove_handler); /*WPE*/
      if (container.find('p.no-products').size())
        d.find('div.navigation-links div.right').hide();
      else d.find('div.navigation-links div.right').show();
    };
    
    // establish the click handlers first time
    var tbl = d.find('table.rkat-shopping-cart');
    tbl.find('td.qty a').click(update_handler);
    tbl.find('td.delete a').click(delete_handler);
    tbl.find('td.remove a').click(remove_handler); /*WPE*/ 
	 
    /////////// ORDER DETAILS ///////////
    
    // install the functionality to continue from the cart to the first checkout process
    d.find('div#rkat-shopping-cart div.navigation-links a.continue').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if (rkat__is_disabled($(this))) return;
      var od = $('div#rkat-order-details');
      var sc = $('div#rkat-shopping-cart');
      var ajs = $(this).parent().find('img.ajax');
      ajs.show();
      
      // 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();
        var msg = sc.find('.rkat-message');
        ajs.hide();
        
        // for any type of error find the message box
        // on the page and insert the proper text there
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'System/network error; Please try again.';
          msg.addClass('error').removeClass('notice');
          msg.text(error);
        }
        else
        {
          // remove any other
          // message here
          msg.text('');
          
          // disable shopping cart
          // and enable order details
          sc.css('opacity', 0.35);
          sc.addClass('rkat-disabled');
          rkat__disabling_screen(sc, true);
          od.css('opacity', 1.00);
          od.removeClass('rkat-disabled');
          rkat__disabling_screen(od, false);
          
          // then replace the supplemental form 
          // html into the proper container on right
          var sd = $('#rkat-supplemental-details');
          sd.html(data.supplemental_forms);
          
          // store the order linkid within the order details
          od.find('input[name=rkat_order]').val(data.linkid);
          
          // enable disappearing labels
          // on any forms that were added
          rkat__install_tfa_labeler();
          
          // ensure new form elements cannot
          // submit when enter is clicked too
          rkat__disable_enter_submission(od);
        }
      };
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: { 'rkat_store': 'ajax_checkout_begin' },
               dataType: 'json',
               success: complete,
               error: complete });
    });
    
    // install the functionality to go back from the order details to the shopping cart
    d.find('div#rkat-order-details div.navigation-links a.back-to-cart').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var od = $('div#rkat-order-details');
      var sc = $('div#rkat-shopping-cart');
      od.css('opacity', 0.35);
      od.addClass('rkat-disabled');
      rkat__disabling_screen(od, true);
      sc.css('opacity', 1.00);
      sc.removeClass('rkat-disabled');
      rkat__disabling_screen(sc, false);
      
      // possibly scroll the window to the top of cart
      /* $('html').animate({ scrollTop: 0 }, 2000); */
    });
    
    // install the functionality to continue from the order details and finish checkout
    d.find('div#rkat-order-details div.navigation-links a.continue').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if (rkat__is_disabled($(this))) return;
      var od = $('div#rkat-order-details');
      var sc = $('div#rkat-shopping-cart');
      var co = $('div#rkat-checkout');
      var ajs = $(this).parent().find('img.ajax');
      ajs.show();
      
      // 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();
        var msg = od.find('.rkat-message');
        ajs.hide();
        
        // for any type of error find the message box
        // on the page and insert the proper text there
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'System/network error; Please try again.';
          msg.addClass('error').removeClass('notice');
          msg.text(error);
        }
        else
        {
          // remove any other
          // message here
          msg.text('');
         
          // hide the shopping
          // cart and order details
          // and show final page
          sc.hide();
          od.hide();
          co.find('div#rkat-order-review-center .rkat-message').text('');
          co.show();
          
          // the order number and linkid are provided separately for insertion so put them in their proper place
          co.find('div#rkat-order-review-center div.top div.order-number span.number').text(data.order_number);
          co.find('div#rkat-order-review-center div.top span.linkid').text(data.linkid);
          co.find('div#rkat-order-review-center div.top div.print-link a.print-this').attr('href', 'print_your_order.php?rkat_order='+data.linkid);
          
          // now replace the compose html which was sent from our server
          co.find('div#rkat-order-review-left').html(data.order_details);
          co.find('div#rkat-order-review-table').html(data.order_table);
        }
      };
      
      // begin preparing our
      // post data for order
      var post = new Object();
      post.rkat_store = 'ajax_checkout_details'; 
      
      // simply traverse all form fields and post them
      var fields = od.find('input, textarea, select');
      fields.each(function(i, el) { 
        post[$(el).attr('name')] = rkat__real_val($(el));
      });
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: post,
               dataType: 'json',
               success: complete,
               error: complete });
    });
    
    // install the functionality to go back from the checkout page to order details
    $('div#rkat-checkout div.navigation-links a.back-to-order').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var od = $('div#rkat-order-details');
      var sc = $('div#rkat-shopping-cart');
      var co = $('div#rkat-checkout');
      co.hide();
      sc.show();
      od.show();
      
      // possibly scroll the window to the top of cart
      /* $('html').animate({ scrollTop: 0 }, 2000); */
    });
    
    // install the functionality to dynamically compose and sumbit to paypal
    $('div#rkat-checkout div.navigation-links a.checkout').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if (rkat__is_disabled($(this))) return;
      var co = $('div#rkat-checkout');
      var ajs = $(this).parent().find('img.ajax');
      ajs.show();
      
      // 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();
        var msg = co.find('.rkat-message');
        
        // for any type of error find the message box
        // on the page and insert the proper text there
        if ((!data.success) || (status != 'success'))
        {
          var error = data.error || 'System/network error; Please try again.';
          msg.addClass('error').removeClass('notice');
          msg.text(error);
          ajs.hide();
        }
        else
        {
          // remove any other
          // message here
          msg.text('');
         
          // the response includes the internals
          // of paypal form so insert and submit
          var pf = $('form#rkat-paypal-form');
          pf.html(data.paypal);
          pf.get(0).submit();
        }
      };
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: { 'rkat_store': 'ajax_checkout',
                       'rkat_order': co.find('div#rkat-order-review-center div.top span.linkid').text()
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    });
    
    // we are going to enable the paypal imagery to functio the same as checkout link
    $('div#rkat-checkout div.paypal-overview a.paypal-accepts').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $('div#rkat-checkout div.navigation-links a.checkout.text-link').trigger('click');
    });
  }
  
  /****************************/
  /* Contact Form Submissions */
  /****************************/
  
  // add necessary functionality to power the contact
  // form which appears on multiple pages on the site
  var d = $('div.rkat-content div.rkat-contact-form');  
  if (d.size())
  {
    // when the go link is clicked start ajax process
    d.find('div.send-links .send').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var f = $(this).parents('form');
      
      // the first task in our attempt to 
      // send the message is to show status
      var ajs = f.find('div.ajax-status');
      ajs.find('.loading-indicator').show();
      ajs.find('.results').hide();
      ajs.show();
      
      // 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();
        var msg = null;
        
        // determine if any error was reported by the
        // process of simply from the ajax request
        if ((!data.success) || (status != 'success'))
        {
          msg = data.error || 'Error; Please try again.';
          ajs.find('.results .error').text(msg);
          ajs.find('.results').addClass('error');
        }
        
        // show the success message by removing class
        else ajs.find('.results').removeClass('error');
        
        // after message is constructed show
        ajs.find('.loading-indicator').hide();
        ajs.find('.results').show();        
      };
      
      // compose an execute the ajax request
      $.ajax({ url: 'contact_form_processor.php',
               type: "POST",
               cache: false,               
               data: { name: f.find('input[name=name]').val(),
                       email: f.find('input[name=email]').val(),
                       message: f.find('textarea[name=message]').val()
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    });
  }
  
  /********************************/
  /* Footer Subscribe To Features */
  /********************************/
  
  // add the ability for the footer subscribe text field to label  
  var el = $('div#rkat-footer div.subscribe div.text-field input');  
  if (el.size()) 
  {
    el.focus(function(e) { if ($(this).val() == 'Email address') $(this).addClass('rkat-focused').val(''); });
    el.blur(function(e) { if ($(this).val() == '') $(this).removeClass('rkat-focused').val('Email address'); });
  }
  
  // add necessary functionality to power
  // the subscribe to features of the form
  var d = $('div#rkat-footer div.subscribe');  
  if (d.size())
  {
    // when the go link is clicked start
    // ajax process to subscribe address
    d.find('div.go a').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var s = $(this).parents('div.subscribe');
      
      // the first task in our attempt to 
      // send the message is to show status
      var ajs = s.find('div.ajax-status');
      ajs.find('.loading-indicator').show();
      ajs.find('.results').hide();
      ajs.show();
      
      // 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();
        var msg = null;
        
        // determine if any error was reported by the
        // process of simply from the ajax request
        if ((!data.success) || (status != 'success'))
        {
          msg = data.error || 'Error; Please try again.';
          ajs.find('.results .error').text(msg);
          ajs.find('.results').addClass('error');
        }
        
        // show the success message by removing class
        else ajs.find('.results').removeClass('error');
        
        // after message is constructed show
        ajs.find('.loading-indicator').hide();
        ajs.find('.results').show();        
      };
      
      // compose an execute the ajax request
      $.ajax({ url: 'mailing_list_processor.php',
               type: "POST",
               cache: false,               
               data: { email: s.find('input[name=email]').val() },
               dataType: 'json',
               success: complete,
               error: complete });
    });
    
    // enable the close link on the ajax status window to function
    d.find('div.ajax-status .results .close').click(function(e) {
      e.stopPropagation();
      e.preventDefault();
      var ajs = $(this).parents('div.ajax-status');
      ajs.hide();
      if (ajs.find('.results').hasClass('error')) return;
      var s = ajs.parents('div.subscribe');
      s.find('input[name=email]').val('Email address').removeClass('rkat-focused');
    });
  }
  
  /********************/
  /* Lightbox'd Terms */
  /********************/
  
  var d = $('div#rkat-footer');
  if (d.size())
  {
    // simply associate each of the footer links with the proper lightbox opening action using the content that is already emebedded on the page
    d.find('a.terms-of-use').click(function(e) { e.preventDefault(); plb__lightbox.open($('#rkat-embedded-terms-of-use .rkat-terms-lightbox').clone()); });
    d.find('a.privacy-policy').click(function(e) { e.preventDefault(); plb__lightbox.open($('#rkat-embedded-privacy-policy .rkat-terms-lightbox').clone()); });
  }
  
});



/**********************/
/* SoundManager Setup */
/**********************/

soundManager.url = '/swf/'; 
soundManager.useFlashBlock = false;
soundManager.debugMode = false;
soundManager.onready(function(oStatus) {
  // this framework checks
  // for success of loading
  if (oStatus.success) { } 
  else { }
});

