/**************************************************/
/* Opals Fine Jewellery -- Javascript (All Pages) */
/**************************************************/

// global reference to slide show 
// variables for animation access
var ofj__home_rotate_slides = null;
var ofj__home_current_slide = null;
var ofj__home_next_slide = null;
var ofj__about_rotate_slides = null

/*********************/
/* Image Pre-Loading */
/*********************/

// create a global array and add to it
var ofj__preload = new Array();
var ofj__img = new Image();
ofj__img.src = 'pics/txt__info_at_opalsfinejewellery_hover.png';
ofj__preload[ofj__preload.length] = ofj__img;

jQuery(document).ready(function($) {
  
  /*****************************/
  /* Drop-Down Menu (Products) */
  /*****************************/
  
  var a = $('div#ofj-header div.menu a.products');
  if (a.size()) a.hover(function(){ $('div#ofj-header div.drop-down-container div.anchor.products').show(); });
  var d = $('div#ofj-header div.menu');
  if (d.size()) d.hover(null, function(){ $('div#ofj-header div.drop-down-container div.anchor').hide(); });
  
  /**********/
  /* Footer */
  /**********/
  
  // create a shortcut reference
  var d = $('div#ofj-footer');
  if (d.size())
  {
    // allow the terms of use link to show information on hover closing on footer exit and ensure the link does not perform its default action
    d.find('p.copyright a.terms').hover(function () { 
      var f = $(this).parents('div#ofj-footer');
      var p = f.find('.ofj-popup-panel.terms-of-use');
      p.show();
      
      // ensure that the terms is never past the top of the page and adjust if it is
      if (p.offset().top < 0) p.css('top', (p.position().top + Math.abs(p.offset().top)));
      
    }, null);
    d.hover(null, function () { $(this).find('.ofj-popup-panel.terms-of-use').hide(); });
    d.find('div.copyright a.terms').click(function(e) {
      e.preventDefault();
    });
  }
  
  /*****************/
  /* Contact Panel */
  /*****************/
  
  // create a shortcut element reference
  var d = $('div.ofj-contact-panel');
  if (d.size())
  {
    // when the contact
    // panel is present
    var img = new Image();
    img.src = 'pics/itm__tickbox_not_ticked.gif';
    ofj__preload[ofj__preload.length] = img;
    img = new Image();
    img.src = 'pics/itm__tickbox_ticked.gif';
    ofj__preload[ofj__preload.length] = img;
    
    // when the checkbox is clicked toggle the class and the checkmark image
    d.find('div.controls div.mailing-list div.checkbox').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $(this).toggleClass('checked');
    });
    
    // allow the what is this link to show instruction on hover
    // and ensure the link does not perform its default action
    d.find('div.controls div.mailing-list a.whats-this').hover(
      function () { $(this).parents('div.controls').find('.mailing-list-instructions').show(); },
      function () { $(this).parents('div.controls').find('.mailing-list-instructions').hide(); }
    );    
    d.find('div.controls div.mailing-list a.whats-this').click(function(e) {
      e.preventDefault();
    });
    
    // initially focus when prepopulated
    var n = d.find('input[name=name]');
    var m = d.find('textarea[name=message]');    
    if (m.val()) n.focus();
    
    // when the send message link is clicked start ajax process
    d.find('div.controls div.send a').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;
        ajs.find('.results .text').empty();
        
        // 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').addClass('error');
        }
        else
        {
          msg = ajs.find('.results .success').text();
          ajs.find('.results').removeClass('error');
        }
        
        // after the proper status message is constructed show
        ajs.find('.results .text').html('<span>'+msg+'</span>');
        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(),
                       join: (f.find('div.controls div.mailing-list div.checkbox').hasClass('checked') ? 'YES' : 'NO')
                     },
               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) {
      var ajs = $(this).parents('div.ajax-status');
      ajs.hide();
      if (ajs.find('.results').hasClass('error')) return;
      var f = ajs.parents('form');
      f.find('input[name=name]').val('');
      f.find('input[name=email]').val('');
      f.find('textarea[name=message]').val('');
    });
  }
    
  /**************************/
  /* Slide Show (Home Page) */
  /**************************/
  
  // create a shortcut page reference
  var pg = $('div.ofj-content.home');  
  if (pg.size())
  {
    // time to wait between slides
    var ofj__delay = 7; // seconds
    
    // retrieve all the slides from the featured image division
    var ofj__slides = pg.find('div.slideshow div.slide').get();
    var ofj__current = 0;
    
    // determine of current slide by locating the first visible slide within the array and saving the offset
    for (var i=0; i<ofj__slides.length; i++) if (!($(ofj__slides[i]).hasClass('ofj-hidden'))) ofj__current = i;
    
    // define a global rotation function
    // which can be schedule with timeout
    ofj__home_rotate_slides = function() {
      
      // determine the next index using a modulus operator
      ofj__next = ((ofj__current + 1) % ofj__slides.length);
      ofj__home_current_slide = $(ofj__slides[ofj__current]);
      ofj__home_next_slide = $(ofj__slides[ofj__next]);
      
      // begin the animation of current and
      // the next slide after current is out
      ofj__home_current_slide.fadeOut(2000);
      setTimeout('ofj__home_next_slide.fadeIn(2000)', 2000);
      
      // update our current offset
      ofj__current = ofj__next;
      
      // ensure that the next slide
      // is visible when it fades in
      n.removeClass('ofj-hidden');
      
      // schedule the next rotation of the slide show images
      setTimeout('ofj__home_rotate_slides()', ofj__delay * 1000);
    };
        
    // schedule the first rotation of the slide show images
    setTimeout('ofj__home_rotate_slides()', ofj__delay * 1000);
  }
  
  /***************************/
  /* Slide Show (About Page) */
  /***************************/
  
  // create a shortcut page reference
  var pg = $('div.ofj-content.about');  
  if (pg.size())
  {
    // time to wait between slides
    var ofj__delay = 5; // seconds
    
    // retrieve all the slides from the featured image division
    var ofj__slides = pg.find('div.slideshow div.slide').get();
    var ofj__current = 0;
    
    // determine of current slide by locating the first visible slide within the array and saving the offset
    for (var i=0; i<ofj__slides.length; i++) if (!($(ofj__slides[i]).hasClass('ofj-hidden'))) ofj__current = i;
    
    // define a global rotation function
    // which can be schedule with timeout
    ofj__about_rotate_slides = function() {
      
      // determine the next index using a modulus operator
      ofj__next = ((ofj__current + 1) % ofj__slides.length);
      var c = $(ofj__slides[ofj__current]);
      var n = $(ofj__slides[ofj__next]);
      
      // begin the animation
      // of current and next
      c.fadeOut(3000);
      n.fadeIn(3000);
      
      // update our current offset
      ofj__current = ofj__next;
      
      // ensure that the next slide
      // is visible when it fades in
      n.removeClass('ofj-hidden');
      
      // schedule the next rotation of the slide show images
      setTimeout('ofj__about_rotate_slides()', ofj__delay * 1000);
    };
        
    // schedule the first rotation of the slide show images
    setTimeout('ofj__about_rotate_slides()', ofj__delay * 1000);
  }
  
  /**************************/
  /* Products Category Page */
  /**************************/
  
  // create a shortcut reference before continuing
  var pg = $('div.ofj-content.products-category');  
  if (pg.size())
  {
    // allow properly classed duplicate links to trigger the configured thickbox
    pg.find('div.products div.product a.thickbox-duplicate').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var tb = $(this).parents('div.product').find('a.thickbox');
      if (!tb.size()) return;
      tb.click();
    });
  }
  
  /**********************/
  /* Lightbox (General) */
  /**********************/
  
  // encapsulate the method for showing indicator
  $('body').data('plb__show_activity', function() {
    var el = $('<img src="pics/itm__ajax_lightbox.gif" alt="Loading" style="display: block; width: 220px; height: 19px;"/>');
    plb__lightbox.open(el, true);
  });
  
  // encapsulate a method for displaying an error
  $('body').data('plb__show_error', function(msg) {
    var el = $('<div class="ofj-lightbox-error">'+
               '  <div class="ofj-message error">'+msg+'</div>'+
               '  <div class="closer"><span class="ofj-arrowed-link plb__closer"><a href="javascript:void(0)"><img src="pics/itm__arrow_blue_right.png" alt=""/></a><a class="ofj-shopping-blue" href="javascript:void(0)">CLOSE</a></span></div>'+
               '</div>');
    plb__lightbox.open(el);
  });
  
  /*******************************************************/
  /* Shopping Cart Features (Used Across Multiple Pages) */
  /*******************************************************/
  
  // allow the terms of use link to show information on click 
  // closing on footer exit and ensure the link does default
  $('a.ofj-terms-of-use-opener').click(function(e) {
    e.preventDefault();
    var p = $('div#ofj-footer').find('.ofj-popup-panel.terms-of-use');
    p.show();
    
    // ensure that the terms is never past the top of the page and adjust if it is
    if (p.offset().top < 0) p.css('top', (p.position().top + Math.abs(p.offset().top)));
  });
  
  // ignore clicks on any 
  // disabled anchor links
  $('a').click(function(e) {
    if (!ofj__is_disabled($(this))) return;
    e.preventDefault();
    e.stopPropagation();
  });
  
  // shortcut function for checking
  // our proprietary disabled state
  function ofj__is_disabled(el) {
    if (el.parents('.ofj-disabled').size() ||
        el.hasClass('ofj-disabled')) return true;
    return false;
  }
  
  // the following function can be used to prevent enter
  // from submitting a form for all elements within container
  function ofj__disable_enter_submission(container) {
    var inputs = container.find('input:not(.ofj-enter-submission-disabled)');
    inputs.keypress(function(e) {
      if (e.which != 13) return;
      e.preventDefault();
      e.stopPropagation();
    });
    inputs.addClass('ofj-enter-submission-disabled');
  }
  
  // this function sets and unsets an invisible
  // div in front of all the contents of element
  function ofj__disabling_screen(el, state) {
    var s = el.find('.ofj-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();
    }
  }
  
  // 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 = $('.ofj-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: { 'ofj_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(root) {
    var links = root ? root.find('.ofj-ajax-buy') : $('body').find('.ofj-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('.ofj-product-id').text());
        var quantity = parseInt($(this).find('.ofj-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')();
        
        // when the thickbox is being used close it just
        // after we open our activity to prevent flicker
        if (typeof(tb_remove) != 'undefined') tb_remove(true);
        
        // 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: { 'ofj_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: { 'ofj_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 */
  /***********************************/
  
  // when the checkbox is clicked toggle the class and the checkmark image
  $('div#ofj-order-details div.mailing-list div.checkbox').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).toggleClass('checked');
  });
    
  // allow the what is this link to show instruction on hover
  // and ensure the link does not perform its default action
  $('div#ofj-order-details div.mailing-list a.whats-this').hover(
    function () { $(this).parents('div#ofj-order-details').find('.mailing-list-instructions').show(); },
    function () { $(this).parents('div#ofj-order-details').find('.mailing-list-instructions').hide(); }
  );    
  $('div#ofj-order-details div.mailing-list a.whats-this').click(function(e) {
    e.preventDefault();
  });
  
  // add special behaviors when page detected
  var d = $('div#ofj-shopping-cart-review');
  if (d.size())
  {
    // when second step is hidden bring
    // it to visible but faded and disabled
    var od = $('div#ofj-order-details');
    if (od.hasClass('ofj-hidden')) {
      od.addClass('ofj-disabled');
      od.css('opacity', 0.35);
      ofj__disabling_screen(od, true);
      od.show(); 
    }
    
    // disable enter submitting on form
    ofj__disable_enter_submission(od);
    
    // prepare the proper state for link
    // which continues based on the cart
    var sc = $('div#ofj-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#ofj-shopping-cart');
      var tbl = $(this).parents('table.ofj-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('.ofj-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: { 'ofj_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#ofj-shopping-cart');
      var tbl = $(this).parents('table.ofj-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('.ofj-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: { 'ofj_store': 'ajax_cart_delete',
                       'cart_item_id': cart_item_id
                     },
               dataType: 'json',
               success: complete,
               error: complete });
    };
    
    // encapsulate the process of replacing
    // a new cart table into page with handlers
    var reinstall_table = function(html) {
      var d = $('div#ofj-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);
      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.ofj-shopping-cart');
    tbl.find('td.qty a').click(update_handler);
    tbl.find('td.delete a').click(delete_handler);
    
    /////////// ORDER DETAILS ///////////
    
    // install the functionality to continue from the cart to the first checkout process
    d.find('div#ofj-shopping-cart div.navigation-links a.continue').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if (ofj__is_disabled($(this))) return;
      var od = $('div#ofj-order-details');
      var sc = $('div#ofj-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('.ofj-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('ofj-disabled');
          ofj__disabling_screen(sc, true);
          od.css('opacity', 1.00);
          od.removeClass('ofj-disabled');
          ofj__disabling_screen(od, false);
          
          // store the order linkid within the order details
          od.find('input[name=ofj_order]').val(data.linkid);
          
          // ensure new form elements cannot
          // submit when enter is clicked too
          ofj__disable_enter_submission(od);
        }
      };
      
      // compose and execute ajax request
      $.ajax({ url: 'shopping_cart.php',
               type: 'POST',
               cache: false,               
               data: { 'ofj_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#ofj-order-details div.navigation-links a.back-to-cart').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var od = $('div#ofj-order-details');
      var sc = $('div#ofj-shopping-cart');
      od.css('opacity', 0.35);
      od.addClass('ofj-disabled');
      ofj__disabling_screen(od, true);
      sc.css('opacity', 1.00);
      sc.removeClass('ofj-disabled');
      ofj__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#ofj-order-details div.join-and-continue a.continue').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if (ofj__is_disabled($(this))) return;
      var od = $('div#ofj-order-details');
      var sc = $('div#ofj-shopping-cart');
      var co = $('div#ofj-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('.ofj-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#ofj-order-review-center .ofj-message').text('');
          co.show();
          
          // the order number and linkid are provided separately for insertion so put them in their proper place
          co.find('div#ofj-order-review-center div.top div.order-number span.number').text(data.order_number);
          co.find('div#ofj-order-review-center div.top span.linkid').text(data.linkid);
          co.find('div#ofj-order-review-center div.top div.print-link a.print-this').attr('href', 'print_your_order.php?ofj_order='+data.linkid);
          
          // now replace the compose html which was sent from our server
          co.find('div#ofj-order-review-left').html(data.order_details);
          co.find('div#ofj-order-review-table').html(data.order_table);
        }
      };
      
      // begin preparing our
      // post data for order
      var post = new Object();
      post.ofj_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')] = $(el).val();
      });
      
      // translate the graphical checkbox into a form field that is suitable for sumbission to page
      post.billing_join = od.find('div.mailing-list div.checkbox').hasClass('checked') ? 'yes' : '';
      
      // 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#ofj-checkout div.navigation-links a.back-to-order').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var od = $('div#ofj-order-details');
      var sc = $('div#ofj-shopping-cart');
      var co = $('div#ofj-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#ofj-checkout div.navigation-links a.checkout').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      if (ofj__is_disabled($(this))) return;
      var co = $('div#ofj-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('.ofj-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#ofj-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: { 'ofj_store': 'ajax_checkout',
                       'ofj_order': co.find('div#ofj-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#ofj-checkout div.paypal-overview a.paypal-accepts').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $('div#ofj-checkout div.navigation-links a.checkout.text-link').trigger('click');
    });
  }
  
});

