(function($) {
  if(!($.iv)){
    $.extend({ iv: {} });
  }

  // ===========================================================
  // START PHOTOGALLERY
  // ===========================================================
  $.fn.iv_photogallery = function(options) {
    return this.each(function() {
      new $.iv.photogallery(this, options);
    });
  }

  $.iv.photogallery = function(el, options) {

    options = $.extend({ 
      // gallery id
      photogallery_id             : null,
  
      // Data Vars
      display_options             : null,
      image_list                  : null,
      gallery_dropdowns           : null,

      // Button Names
      left_button_name            : null,
      right_button_name           : null,
      pause_button_name           : null, 

      // Container names
      order_num_container_name    : null,
      images_container_name       : null,
      ul_name                     : null,
      description_container_name  : null,
      p_name                      : null,
      loading_container_name      : null,

      current_page_num_name       : null,
      max_page_num_name           : null,
      show_description            : null,

      txtImage                    : null,
      txtOf                       : null

    }, options);

    // This will append it to the overall div.
    $.data(el, 'photogallery_' + options.photogallery_id, this);

    // Start vars
    var $$                      = $(el);

    // rot_ctr1_bod_ctr3_bod_wrp1_blk3_blk2    
    var $parent_div             = $$.parent().parent();

    // Containers
    var $images_container       = $('div.' + options.images_container_name, $$);
    var $ul_container           = $('ul.' + options.ul_name, $$);
    var $description_container  = $('div.' + options.description_container_name, $$);
    var $p_container            = $('p.' + options.p_name, $$);
    var $loading_container      = $('div.' + options.loading_container_name, $$);
    var $order_num_container    = $('#' + options.order_num_container_name, $$);

    // Need to know current_page_number and total_pages
    var $pagination_container           = $('div.pagination_container', $$);
    var $pagination_current_container   = $('span.pagination_current', $$);
    var $pagination_total_container     = $('span.pagination_total', $$);

    var $current_page_num_container     = $('#' + options.current_page_num_name, $$);
    var $max_page_num_container         = $('#' + options.max_page_num_name, $$);

    var $pagination_controls_container  = $('div.pagination_controls', $$);
    var $images_showing_start_container = $('span.images_showing_start', $$);
    var $images_showing_end_container   = $('span.images_showing_end', $$);
    var $main_image_container           = $('div.images_container', $$);

    // Buttons
    var $left_button           = $('span.' + options.left_button_name, $$);
    var $right_button          = $('span.' + options.right_button_name, $$);
    var $pause_button          = $('span.' + options.pause_button_name, $$);

    // Data 
    var photogallery_id       = options.photogallery_id;
    var display_options       = JSON.parse(options.display_options);
    var image_list            = JSON.parse(options.image_list);
    var gallery_dropdowns     = JSON.parse(options.gallery_dropdowns);

    // 1 == Yes, 2 == No
    var show_description      = options.show_description;


/*
    // Debug area, used to see if the list can handle 1 item.
    var temp_image_list = new Array(); 
    $.each(image_list, function(cnt, image_hash) { 
      //if(cnt != 0){
      if(cnt < 7){
        temp_image_list[cnt] = image_list[cnt];
      }
    });
    image_list = temp_image_list;
*/

    // Other Vars
    var max_order_num         = image_list.length || 0; 
    var current_order_num     = $order_num_container.val();
    var current_page_num      = $current_page_num_container.val();
    var max_page_num          = $max_page_num_container.val();
    var locked                = 0;
    var $preview_window       = null;
    var paused                = 1; // We start off paused
    var images_showing_start  = parseInt($images_showing_start_container.html());
    var images_showing_end    = parseInt($images_showing_end_container.html());

    // Find the gallery name
    var gallery_type_selected     = display_options['gallery_type_selected'];
    var gallery_type_display_name = gallery_dropdowns['gallery_types'][gallery_type_selected].toLowerCase();
    var regex                     = new RegExp(/\s+/g);
    var gallery_name              = gallery_type_display_name.replace(regex, "_");

    // -----------------------------------------------------------------------------
    // LIGHTBOX SECTION
    // Please note that this plugin has been modified slightly from the original
    // plugin that is available at: http://leandrovieira.com/projects/jquery/lightbox/
    // I took out all the english text. so Next/Back are arrows, Close is an X .. ect..
    // -----------------------------------------------------------------------------
    var raw_gallery_name      = gallery_dropdowns['gallery_types'][gallery_type_selected];
    var large_image_style     = display_options[raw_gallery_name]['large_image_style'];

    // Init the photogallery
    switch(gallery_name){

      case ('single_image') :
        init_single_image();
      break;
      
      case ('grid') :
        init_grid();
      break;

      case ('filmstrip_1') :
        init_filmstrip(gallery_name);
      break;

      case ('filmstrip_2') :
        init_filmstrip(gallery_name);
      break;

      case ('slideshow') :
        init_slideshow();
      break;
    }

    // ========================================================================= 
    // SINGLE IMAGE
    // ========================================================================= 
    function init_single_image(){
      _reset_position();

      // We hide the gallery with the loading screen.
      $loading_container.show();

      // We'll see if there is an image list
      if(image_list.length > 0){

        // Set button triggers
        // ---------------------------------------------------------------------------
        $left_button.unbind('click').click( function() {
          _move('left', 'single_image');
          return false;
        });

        $right_button.unbind('click').click( function() {
           _move('right', 'single_image');
          return false;
        });

        // Decide if we show the buttons right away
        // ---------------------------------------------------------------------------
        if(current_order_num > 0 && max_order_num > 1){
          $right_button.show()
        }

        if( (current_order_num < (max_order_num - 1)) && (!(current_order_num == 0)) ){
          $left_button.show()
        }
      }

      $loading_container.hide();
    };

    // ========================================================================= 
    // GRID
    // ========================================================================= 
    function init_grid() {
      _reset_position();

      // We hide the gallery with the loading screen.
      //$loading_container.show();

      if(large_image_style == 1){
        // Set the pop-up type
        $("img", $images_container).each(function(cnt) {
          var image_hash = image_list[cnt];
          $(this).click(function() { 
            _preview(image_hash); 
            return false;
          });
        });
      }
      else{
        // This will use animated lightbox.
        $(function() {
        // $('#photogallery_container_<% $photogallery_id %> img[rel*="lightbox"]').lightBox(lightbox_hash); 
          var lightbox_hash = {
            txtImage        : options.txtImage,
            txtOf           : options.txtOf,
            showDescription : show_description,
            parent_div_id   : 'photogallery_' + options.photogallery_id
          };
          $('img[rel*="lightbox"]', $$).lightBox(lightbox_hash);
        });
      }

      // Now we need to know which controls to activate
      var $current_page = $('li.page_selected', $ul_container);

      if($current_page.next().length){
        $right_button.unbind('click').css("color" , "blue").click( function() {
          _move_grid('right');
          return false;
        });
      }
      else{
        $right_button.css("color" , "black");
        $right_button.unbind('click');
      }

      if($current_page.prev().length){
        $left_button.unbind('click').css("color" , "blue").click( function() {
          _move_grid('left');
          return false;
        });
      }
      else{
        $left_button.css("color", "black");
        $left_button.unbind('click');
      }

      $loading_container.hide();
    }

    // ========================================================================= 
    // SLIDESHOW
    // ========================================================================= 
    function init_slideshow(){
      _reset_position();

      // We hide the gallery with the loading screen.
      $loading_container.show();

      // We'll see if there is an image list
      if(image_list.length > 0){

        // Set button triggers
        // ---------------------------------------------------------------------------
        $pause_button.unbind('click').click( function() {
          _pause();
          return false;
        });

        $right_button.unbind('click').click( function() {
           _start();
          return false;
        });

/*
        // If we're not on the first image, we'll scroll to it. 
        // ---------------------------------------------------------------------------
        if(current_order_num != 0){
          var find_list_item  = "li:eq(" + current_order_num + ")";
          var $selected_image = $(find_list_item, $ul_container);

          // This is to make sure the images are hidden till 
          // we've scrolled to the selected image.
          var loading_function = function(){
            $loading_container.hide();
          }
          $images_container.scrollTo( $selected_image, 800, loading_function); 
        }
*/
      }

      $loading_container.hide();

    };

    // ========================================================================= 
    // FILMSTRIP 1 & 2
    // ========================================================================= 
    function init_filmstrip(gallery_name) {
      _reset_position();
      $loading_container.show();

      if(image_list.length > 0){
        // Set the pagination
        // $pagination_total_container.html(max_order_num);
        // $('div.pagination', $$).show();

/*
        if(($.browser.msie) && (gallery_name == 'filmstrip_2')){
          $ul_container.css('padding-top', '3px');
        }
        if(gallery_name == 'filmstrip_2'){ border_size = 0; }
*/

        if(gallery_name == 'filmstrip_1'){

          // Set the pop-up type
          $("img", $images_container).each(function(cnt) {
            var image_hash = image_list[cnt];

            $(this).click(function() { 
              // This will show the large picture on the top frame 
              _filmstrip_1_preview(image_hash); 

              // Move the selected image class to the new image 
              $('li.img_selected', $$).removeClass('img_selected');

              // Set the new img selected  
              $(this).parent().parent().addClass('img_selected');
              $order_num_container.val(cnt);

              return false;
            });
          });
        }
        else if (gallery_name == 'filmstrip_2'){

          // Set the pop-up type
          // Testing purposes, large image style #2 doesn't work yet
          // large_image_style = 1;

          if(large_image_style == 1){

            $("img", $images_container).each(function(cnt) {
              var image_hash = image_list[cnt];
              $(this).click(function() { 

                _filmstrip_2_preview(image_hash); 

                // Move the selected image class to the new image 
                $('li.img_selected', $$).removeClass('img_selected');

                // Set the new img selected  
                $(this).parent().parent().addClass('img_selected');
                $order_num_container.val(cnt);

                return false;
              });
            });

          }
          else{
            // This will use animated lightbox.
            $(function() {
              // $('#photogallery_container_<% $photogallery_id %> img[rel*="lightbox"]').lightBox(lightbox_hash); 
              var lightbox_hash = {
                txtImage        : options.txtImage,
                txtOf           : options.txtOf,
                showDescription : show_description,
                parent_div_id   : 'photogallery_' + options.photogallery_id
              };
  
              $('img[rel*="lightbox"]', $$).lightBox(lightbox_hash); 
            });
          }
        }


        // Now we need to know which controls to activate
        var $current_page = $('li.page_selected', $ul_container);

        // Right Button
        if($current_page.next().length){
          $right_button.unbind('click').click( function() {
            _move_grid('right');
            return false;
          });
        }
        else{
          $right_button.unbind('click');
        }

        // Left Button
        if($current_page.prev().length){
          $left_button.unbind('click').click( function() {
            _move_grid('left');
            return false;
          });
        }
        else{
          $left_button.unbind('click');
        }

        // $pagination_controls_container.show();
      }

      $loading_container.hide();
    }

    // ======================================================================== 
    // FUNCTIONS
    // ========================================================================= 
    function _reset_position(){
      current_page_num = 1;
      $current_page_num_container.val(current_page_num);
      current_order_num = 0;
      $order_num_container.val(current_order_num);
    }

    function _start(){
      // Unbind the start button, to stop start spamming.
      $right_button.unbind('click');

      // Set our flag
      paused = 0;

      // Switch the button icons
      $right_button.hide();
      $pause_button.show();

      // When a user hits the play button, we want to move to the next pic right away.
      // We just have to see if we're at the last image, or not.
      if($order_num_container.val() < max_order_num - 1){
        _move('right', 'slideshow');
      }
      else{
        _move_to_first();  
      }

      // This sets the timer for the rotation.
      setInterval( function() {
        if(paused == 0){
          // We want to make sure they don't click anything while we're in the process of moving
          $pause_button.unbind('click');

          // Decide where to move to 
          if($order_num_container.val() == max_order_num - 1){
            _move_to_first();
          }
          else{
            _move('right', 'slideshow');
          }

          // Now that we're out the movement, set the click event again.   
          $pause_button.click( function() {
            _pause();
            return false;
          });        

        };

      }, 5000);
    }

    // --------------------------------------------------------------------------
    function _move_to_first(){
      // clear the selected class  
      var current_image = $('li.img_selected', $ul_container);
      current_image.removeClass('img_selected');

      // set the order num back to zero
      $order_num_container.val(0);

      // find the first li container
      var $selected_image = $("li:eq(0)", $ul_container);

      // reassign the selected class to new image 
      $selected_image.addClass('img_selected');

      // Set the image description if there is any.
      var image_hash = image_list[0];

      // Set the description 
      if(image_hash.description){
        $p_container.fadeOut('slow', function() {
          $p_container.html(image_hash.description)
        }).fadeIn('slow');
      }
      else{
        $p_container.fadeOut('slow', function(){
          $p_container.empty();
        });
      }

      var loading_function = function(){
        $loading_container.hide();
      }

      // now we scroll to the first item.
      $loading_container.show();
      $images_container.scrollTo( $selected_image, 800, loading_function);
    }

    // --------------------------------------------------------------------------
    function _pause(){
      // unbind the pause button, to keep from spamming it.
      $pause_button.unbind('click');

      $right_button.unbind('click').click( function() {
         _unpause();
        return false;
      });

      // Set our flag
      paused = 1;
    
      // Switch the button icons 
      $pause_button.hide();
      $right_button.show(); 
    }

    // --------------------------------------------------------------------------
    function _unpause(){
      // unbind the pause button, to keep from spamming it.
      $right_button.unbind('click');

      $pause_button.unbind('click').click( function() {
         _pause();
        return false;
      });

      // Set our flag
      paused = 0;

      // Switch the button icons 
      $pause_button.show();
      $right_button.hide();
    }


    // --------------------------------------------------------------------------
    function _move_grid(dir){
      // alert("locked: " + locked);
      // alert("dir: " + dir);
      // alert("current_page_num / max_page_num: " + current_page_num + "/" + max_page_num);

      // While we're trying to load pictures, we'll need to lock people out of moving around. 
      if( 
          (locked) ||
          ( current_page_num == 1 && dir == 'left') || 
          ( (max_page_num == current_page_num) && dir == 'right') 
        ){
        return(1);
      }

      // Set the lock.
      locked = 1;

      // see what page number we're current on.
      var $next_page   = null;
      var new_page_num = current_page_num;

      // Get the current selected item (with selected class), if none was found, get the first item  
      // var current_page = $('li.page_selected', $ul_container).length ? $('li.selected', $ul_container) : $('li:first', $ul_container);  
      var $current_page = $('li.page_selected', $ul_container);  

      var new_images_showing_start  = 0;
      var new_images_showing_end    = 0;
 
      // use prev and next to determine increment or decrement  
      // because the controls disappear, i don't do checking to see if there is a next or prev.
      if (dir == 'left') {  
        $next_page = $current_page.prev();
        new_page_num--;

        // Find out how many images are showing.
        var img_array = $('img', $next_page);
        new_images_showing_start  = parseInt(images_showing_start) - img_array.length; 
        new_images_showing_end    = parseInt(images_showing_start) - 1;
      } 
      else {  
        $next_page = $current_page.next();  
        new_page_num++;

        var img_array = $('img', $next_page);
        new_images_showing_start  = parseInt(images_showing_end) + 1;
        new_images_showing_end    = parseInt(images_showing_end) + img_array.length;
      }  
 
      // Set the number of images 
      $images_showing_start_container.html(new_images_showing_start);
      images_showing_start = new_images_showing_start;

      $images_showing_end_container.html(new_images_showing_end);
      images_showing_end = new_images_showing_end;
 
      // Set our new array number
      $current_page_num_container.val(new_page_num);
      current_page_num = new_page_num

      //clear the selected class  
      $current_page.removeClass('page_selected'); 

      //reassign the selected class to new image 
      $next_page.addClass('page_selected');  

      // We scroll to the next image, and We use the function to 
      // make sure that the lock isn't set to zero before it's finished scrolling.
      var lock_function = function(){ locked = 0; };
      $images_container.scrollTo($next_page, 800, lock_function);

      // Set the buttons again
      if($next_page.next().length){
        $right_button.unbind('click').css("color" , "blue").click( function() {
          _move_grid('right');
          return false;
        });
      }
      else{
        $right_button.css("color" , "black");
        $right_button.unbind('click');
      }

      if($next_page.prev().length){
        $left_button.unbind('click').css("color" , "blue").click( function() {
          _move_grid('left');
          return false;
        });
      }
      else{
        $left_button.unbind('click').css("color", "black");
      }
    }

    // --------------------------------------------------------------------------
    function _filmstrip_1_preview(image_hash) {

      var src             = image_hash.thumbnail_thumb_path + gallery_name + '_thumbnail_' + image_hash.filecabinet_file_id + '_' + image_hash.unique_id + image_hash.thumbnail_extension;
      var description     = image_hash.description;
      var image_url_link  = image_hash.image_url_link;

      var image_attributes ={
        id      : "photogallery_image_" + image_hash.filecabinet_file_id,
        // alt     : image_hash.original_image_name,
        src     : src
      };

      // Create the image!
      var $img                  = $('<img style="padding:0px; margin:0px;"></img>').attr(image_attributes);

      var $top_main_image_container = $('div.main_image_container', $$);

      // JH - 12/04/2009 - Had to do a quick switcharoo to populate the inner container instead of the main one..
      var $main_image_container  = $('div.sub_image_container', $top_main_image_container);
      //var $align_div            = $('<div style="text-align: center;"></div>');

      // target Links
      if(image_url_link){
        var url_link        = image_url_link;
        var regex           = new RegExp(/http:\/\//g);
        var clean_url_link  = url_link.replace(regex, "");
        var target          = '_self';

        if(image_hash.click_option == 2){
          target            = '_blank'; 
        }

        var $anchor       = $('<a style="text-decoration:none;" href="http://' + clean_url_link + '" target="' + target + '"></a>'); 

        // do a switcharoo
        $anchor.html($img);
        $img = $anchor;
        // $img.appendTo($anchor);
        //$anchor.appendTo($align_div);
      }
      else{
        //$img.appendTo($align_div);
      }

      $main_image_container.empty();
      //$main_image_container.html($align_div);

      $main_image_container.html($img);

      // always clear out the description.
      // $description_container.empty();

      // Set the description if there is one.
      if(description && (show_description == 1)){
        $description_container.empty();
        $description_container.html('<p style="padding:0px; height:30px; overflow-x: hidden; overflow-y: auto; margin:0px;">' + description + '</p>');
      }
      else{
        if(show_description == 1){
          $description_container.html('<p style="padding:0px; margin:0px; height:30px; overflow-x: hidden; overflow-y: auto;"></p>');
        }
        else{
          $description_container.html('<p style="padding:0px; margin:0px; height:30px; overflow-x: hidden; overflow-y: auto; display:none;"></p>');
        }
      }
    }

    // --------------------------------------------------------------------------
    function _filmstrip_2_preview(image_hash) {
      // Fix eventually.
      _preview(image_hash);
    }


    // --------------------------------------------------------------------------
    function _preview(image_hash) {
      // This function creates the pop-up window that shows the full image
      var img_loader    = new Image();
      img_loader.onload = function() { _center_preview(image_hash, img_loader); };

      if(image_hash.original_image_path){
        img_loader.src    = image_hash.original_image_path + "/" + image_hash.original_image_name;
      }
      else{
        img_loader.src    = image_hash.original_image_name;
      }

      $('<div></div>').addClass('photogallery_overlay').addClass('photogallery_thumbnail_overlay').css('z-index', 4000).appendTo('body').unbind('click').click(_close_preview);
    }

    // --------------------------------------------------------------------------
    function _center_preview(image_hash, img_loader) {
      img_loader.onload = null;

      var image_path    = image_hash.original_image_name;

      if(image_hash.original_image_path){
        image_path    = image_hash.original_image_path + "/" + image_hash.original_image_name;
      }

      var description   = image_hash.description;

      // Hack to force preview window to be recreated
      if($preview_window){ $preview_window == null; }

      // If the preview div doesn't exist, lets create it
      if(!$preview_window) {

        $preview_window             = $('<div class="photogallery_preview_window" style="font-size:0px"><img></img></div>').appendTo('body');
        var $preview_close          = $('<div class="photogallery_preview_close"></div>');
        var $description_container  = $('<div class="photogallery_preview_description"></div>');

        // Pull all the global css 
        var d_font          = $parent_div.css('font-family');
        var d_font_color    = $parent_div.css('color');
        var d_font_size     = $parent_div.css('font-size');
        var d_font_weight   = $parent_div.css('font-weight');
        var d_font_style    = $parent_div.css('font-style');
        var d_font_variant  = $parent_div.css('font-variant');
        var d_text_align    = $parent_div.css('text-align');
        var d_text_decor    = $parent_div.css('text-decoration');
        var d_text_trans    = $parent_div.css('text-transform');
        var d_white_space   = $parent_div.css('white-space');
         
        if(d_font)        { $description_container.css('font-family', d_font); }
        if(d_font_color)  { $description_container.css('color', d_font_color);}
        if(d_font_size)   { $description_container.css('font-size', d_font_size);}
        if(d_font_weight) { $description_container.css('font-weight', d_font_weight);}
        if(d_font_style)  { $description_container.css('font-style', d_font_style);}
        if(d_font_variant){ $description_container.css('font-variant', d_font_variant);}
        if(d_text_align)  { $description_container.css('text-align', d_text_align);}
        if(d_text_decor)  { $description_container.css('text-decoration', d_text_decor);}
        if(d_text_trans)  { $description_container.css('text-transform', d_text_trans);}
        if(d_white_space) { $description_container.css('white-space', d_white_space);}

        // assemble the divs
        $preview_close.appendTo($preview_window);
        $description_container.appendTo($preview_window);

        // Assign the close button
        $('div.photogallery_preview_close', $preview_window).unbind('click').click(_close_preview);
      }

      var div_width = img_loader.width - 20;

      // Set the description
      if(description && show_description == 1){
        $('div.photogallery_preview_description', $preview_window).html('<p style="padding:0px; width:' + div_width + 'px; height:auto; margin:0px;">' + description + '</p>');
      }
      else{
        if(show_description == 1){
          $('div.photogallery_preview_description', $preview_window).html('<p style="padding:0px; width:' + div_width + 'px; height:auto; margin:0px;"></p>');
        }
        else{
          $('div.photogallery_preview_description', $preview_window).html('<p style="padding:0px; width:' + div_width + 'px; height:auto; margin:0px; display:none;"></p>');
        }
      }

      var img_x = img_loader.width;
      var img_y = img_loader.height;
      var x     = $(window).width();
      var y     = $(window).height();

      if(img_y > y) {
        img_y = y - 40;
      } 

      $('img', $preview_window).attr('src', image_path).unbind('click').click(_close_preview).attr('height', img_y);
      // $('img', $preview_window).attr('src', image_path).unbind('click').click(_close_preview);

      var left = 0 - (parseInt($preview_window.width()) / 2);
      var top  = 0 - (parseInt($preview_window.height()) / 2);

      if($.browser.msie && ($.browser.version < 7)) {
        top += $(window).scrollTop();
        $('select').hide();
      }

      $preview_window.css({ 'margin-top': top + 'px', 'margin-left': left + 'px' }).show();
    }

    // --------------------------------------------------------------------------
    function _close_preview() {
      $preview_window.hide();
      $('div.photogallery_thumbnail_overlay').remove();
    }

    // function to produce full size images
    // --------------------------------------------------------------------------
    function generate_image(image_hash) {

      // Fix the path
      var src = image_hash.original_image_path + "/" + image_hash.original_image_name;

      var image_hash ={
        id      : "photogallery_image_" + image_hash.filecabinet_file_id,
        // alt     : image_hash.original_image_name,
        src     : src
      };

      // Create the image!
      var $img  = $('<img style="padding:5px;"></img>').attr(image_hash);  

      return($img);
    }

    // function to produce the thumbnails 
    // --------------------------------------------------------------------------
    function generate_thumbnail(image_hash) {

      // Fix the path
      var src         = image_hash.thumbnail_thumb_path;
      var image_name  = image_hash.original_image_name;
      var image_desc  = image_hash.description;
      var image_path  = image_hash.original_image_path + "/" + image_hash.original_image_name;
      var image_id    = "photogallery_image_" + image_hash.filecabinet_file_id;

      var image_attributes ={
        id      : image_id,
        // alt     : image_hash.original_image_name,
        src     : src
        // href    : image_hash.original_image_path + "/" + image_hash.original_image_name,
        // rel     : "lightbox[gallery]"
      };

      if(image_desc){
        image_attributes['title'] = image_desc;  
      }
      else{
        image_attributes['title'] = image_name;  
      } 
 
      // Create the image!
      // NOTE: had to hardcode "rel" and "href" because jquery.min.js is choking IE when trying to set these fake attributes
      var $img  = $('<img rel="lightbox[gallery]" href="' + image_path + '"></img>').attr(image_attributes);

      return($img);
    }

    // --------------------------------------------------------------------------
    function _move(dir, gallery_type) {
        //window.console.log("-----------------------------------");
        //window.console.log(dir);
        //window.console.log(locked);
        //window.console.log(gallery_type);
        //window.console.log(current_order_num);
        //window.console.log(max_order_num);
        //window.console.log("-----------------------------------");

      // While we're trying to load pictures, we'll need to lock people out of moving around. 
      if( 
          (locked) ||
          ( current_order_num == 0 && dir == 'left') || 
          ( (max_order_num == current_order_num) && dir == 'right') 
        ){
        //window.console.log("got caught!");
        return(1);
      }

      // Set the lock.
      locked = 1;

      // see what image number we're current on.
      current_order_num = $order_num_container.val();
      var next_image    = null;
      var new_order_num = current_order_num;

      // Get the current selected item (with selected class), if none was found, get the first item  
      // var current_image = $('li.selected', $ul_container).length ? $('li.selected', $ul_container) : $('li:first', $ul_container);  
      var current_image = $('li.img_selected', $ul_container);  
 
      // use prev and next to determine increment or decrement  
      // because the controls disappear, i don't do checking to see if there is a next or prev.
      if (dir == 'left') {  
        next_image = current_image.prev();
        new_order_num--;
        current_order_num--;
      } 
      else {  
        next_image = current_image.next();  
        new_order_num++;
        current_order_num++;
      }  
  
      // Set our new array number
      $order_num_container.val(new_order_num);

      //clear the selected class  
      current_image.removeClass('img_selected'); 

      //reassign the selected class to new image 
      next_image.addClass('img_selected');  

      // We scroll to the next image, and We use the function to 
      // make sure that the lock isn't set to zero before it's finished scrolling.
      var lock_function = function(){ locked = 0; };
      $images_container.scrollTo(next_image, 800, lock_function);

      // Set the image description if there is any.
      var image_hash = image_list[new_order_num];

      // Set the description 
      if(gallery_type != 'grid'){
        if(image_hash.description){
          if(show_description == 1){
            $p_container.fadeOut('slow', function() {
              $p_container.html(image_hash.description)
            }).fadeIn('slow');
          }
        }
        else{
          $p_container.fadeOut('slow', function(){ 
            $p_container.empty(); 
          });
        }
      }

      // Set the buttons again
      if( (gallery_type != 'slideshow') && (gallery_type != 'grid') ){
        if(next_image.next().length){
          $right_button.show(); 
        }
        else{
          $right_button.hide();
        }

        if(next_image.prev().length){
          $left_button.show();
        }
        else{
          $left_button.hide();
        }
      }
    }  
  }
  // ==========================================================
  // END PHOTOGALLERY
  // ==========================================================

})(jQuery);

