// "constants" - IE doesn't support the keyword though everyone else does so we use VAR... be careful
var NUM_GAL_PER_ROW = 5; // this assumes a certain uniform width...
var NUM_VIS_GAL_ROW = 4; // assumes uniform height...
var NUM_VIS_GAL = NUM_GAL_PER_ROW * NUM_VIS_GAL_ROW;

var gallery_row = 0; // tracking index for scroll
var photo_row = 0; // tracking (for edit photos)
var photo_idx = 0; // tracking (for normal browsing)
var ias = null; // imgAreaSelect instance

function f_makeSimpleAjaxPost(p_url, p_data, success_cb, error_cb) {
  if( !error_cb ) {
    var error_cb = null;
  }
  $.ajax({ type: "POST", url: p_url, data: p_data, error: error_cb, success: success_cb, dataType: "xml" });
}

function f_makeSimpleAjaxGet(p_url, p_data, success_cb) {
  $.ajax({ type: "GET", url: p_url, data: p_data, success: success_cb, dataType: "xml", error: f_ajax_error });
}

function f_ajax_error(XMLHttpRequest, textStatus, errorThrown) {
  alert("Error: " + XMLHttpRequest.responseText + "\n" +
    textStatus + "\n" + errorThrown);
}

function f_photo_loaded() {
  $(this).data('photo_loaded',true);
}

function f_image_display_adjust(block) {
  var block_min_height = parseInt(block.css('min-height'));
  var photo = block.children('img:eq(0)');
  var title = photo.attr('title');
  var photo_caption = block.children('div:eq(0)');
  
  if( typeof(photo.data('photo_loaded')) == "undefined" ) {
    setTimeout(function(){f_image_display_adjust(block)}, 250);
  }
  else {
    var block_clone = block.clone();
    block_clone.css({
      display: 'block',
      visibility: 'hidden',
      position: 'absolute',
      left: '-658px',
      top: '0'
    });
    block_clone.attr('id','photo-block-test');
    block_clone.insertAfter(block);

  //  block.css({visibility: 'hidden', display: 'block'});
    var photo_h = block_clone.children('img:eq(0)').height();
  
    block_clone.remove();

    debug.group("First photo");
    debug.info(block, photo);
    if( photo_h < block_min_height ) {
      padding = Math.floor(block_min_height/2 - photo_h/2);
      photo.css('padding-top',padding + 'px');

      debug.warn("padding: " + padding, "photo_h: " + photo_h, "block_min_height: " + block_min_height);
    }
    debug.groupEnd();
  }
}

function f_setScrollLeftButton(left_button_id) {
  var tracker = photo_idx;
  
  // set active button if necessary
  if( tracker > 0 ) {
    $('#' + left_button_id).attr('src','images/gallery-left-active.png');
  }
  else {
    $('#' + left_button_id).attr('src','images/gallery-left-inactive.png');
  }
}

function f_setScrollRightButton(photos, right_button_id) {
  var tracker = photo_idx;
  
  if( tracker < photos.length - 1 ) {
    $('#' + right_button_id).attr('src','images/gallery-right-active.png');
  }
  else {
    $('#' + right_button_id).attr('src','images/gallery-right-inactive.png');
  }
}

function f_setScrollUpButton(up_button_id, type) {
  var tracker = gallery_row;
  if( type == "photo" ) {
    tracker = photo_row;
  }

  // set 'active' scroll button if necessary
  if( tracker > 0 ) {
    $('#' + up_button_id).attr('src','images/gallery-up-active.png');
  }
  else {
    $('#' + up_button_id).attr('src','images/gallery-up-inactive.png');
  }
}

function f_setScrollDownButton(galleries, down_button_id, type) {
  var tracker = gallery_row;
  if( type == "photo" ) {
    tracker = photo_row;
  }

  // set 'active' scroll button if necessary
  if( galleries.length > (tracker*NUM_GAL_PER_ROW)+NUM_VIS_GAL ) {
    $('#' + down_button_id).attr('src','images/gallery-down-active.png');
  }
  else {
    $('#' + down_button_id).attr('src','images/gallery-down-inactive.png');
  }
}

function f_scroll_left(photos, left_button_id, right_button_id) {
  var photo_gal_title = $('#photo-gal-title').html();
  var photo_caption_block = $('#portfolio-photo-caption');
  var photo_title = "";
  var photo_caption = "";
  var photo_block = null;
  var photo = null;
  var photo_h = 0;
  var padding = 0;
  var block_min_height = 0;
  var para_clone = photo_caption_block.clone();
  var full_height = 0;
  var limit_height = photo_caption_block.height();

  if( photo_idx > 0 ) {
    photo_block = photos.eq(photo_idx - 1);

    photo_block.show();
    photos.eq(photo_idx).hide();
    
    photo_idx--;
    
    block_min_height = parseInt(photo_block.css('min-height'));
    photo = photo_block.children('img:eq(0)');
    photo_h = photo.height();

    if( photo_h < block_min_height ) {
      padding = Math.floor(block_min_height/2 - photo_h/2);              
      photo.css('padding-top',padding + 'px');
    }

    photo_title = photo.attr('title');
    photo_caption = photo_block.children('div:eq(0)');
    
    para_clone.css({
      height: 'auto',
      'max-height': 'none',
      overflow: 'visible',
      width: '657px',
      display: 'block',
      visibility: 'hidden',
      position: 'absolute',
      left: '-658px',
      top: '0'
    });
    para_clone.attr('id','photo-caption-test');
    para_clone.insertAfter(photo_caption_block);
    
    para_clone.text(photo_caption.text());
    full_height = para_clone.height();    
    para_clone.remove();
    
    $('#portfolio-gallery-title').html('<span id="photo-gal-title">' + photo_gal_title + '</span>' + photo_title);
    $('#portfolio-photo-caption').text(photo_caption.text());

    if( full_height > limit_height ) {
      photo_caption_block.append('<div id="photo-caption-more">More...</div>');
    }
    else {
      $('#photo-caption-more').remove();
    }
    
    // check if need to change button highlights
    f_setScrollLeftButton(left_button_id);
    f_setScrollRightButton(photos, right_button_id);
  }
}

function f_scroll_right(photos, left_button_id, right_button_id) {
  var photo_gal_title = $('#photo-gal-title').html();
  var photo_caption_block = $('#portfolio-photo-caption');
  var photo_title = "";
  var photo_caption = "";
  var photo_block = null;
  var photo = null;
  var photo_h = 0;
  var padding = 0;
  var block_min_height = 0;
  var para_clone = photo_caption_block.clone();
  var full_height = 0;
  var limit_height = photo_caption_block.height();
  
  if( photos.length > photo_idx + 1 ) {
    photo_block = photos.eq(photo_idx + 1);
    
    photo_block.show();
    photos.eq(photo_idx).hide();
    
    photo_idx++;

    block_min_height = parseInt(photo_block.css('min-height'));
    photo = photo_block.children('img:eq(0)');
    photo_h = photo.height();

    if( photo_h < block_min_height ) {
      padding = Math.floor(block_min_height/2 - photo_h/2);              
      photo.css('padding-top',padding + 'px');
    }

    photo_title = photo.attr('title');
    photo_caption = photo_block.children('div:eq(0)');

    para_clone.css({
      height: 'auto',
      'max-height': 'none',
      overflow: 'visible',
      width: '657px',
      display: 'block',
      visibility: 'hidden',
      position: 'absolute',
      left: '-658px',
      top: '0'
    });
    para_clone.attr('id','photo-caption-test');
    para_clone.insertAfter(photo_caption_block);
    
    para_clone.text(photo_caption.text());
    full_height = para_clone.height();    
    para_clone.remove();
    
    $('#portfolio-gallery-title').html('<span id="photo-gal-title">' + photo_gal_title + '</span>' + photo_title);
    $('#portfolio-photo-caption').text(photo_caption.text());

    if( full_height > limit_height ) {
      photo_caption_block.append('<div id="photo-caption-more">More...</div>');
    }
    else {
      $('#photo-caption-more').remove();
    }
    
    // check if need to change button highlights
    f_setScrollLeftButton(left_button_id);
    f_setScrollRightButton(photos, right_button_id);
  }
}

function f_scroll_down(galleries, up_button_id, down_button_id, type) {
  var tracker = gallery_row;
  if( type == "photo" ) {
    tracker = photo_row;
  }

  if( galleries.length > (tracker*NUM_GAL_PER_ROW)+NUM_VIS_GAL ) {
    var start = NUM_GAL_PER_ROW*tracker;
//    galleries.children('img').removeClass('hover');
    galleries.slice(start,start+NUM_GAL_PER_ROW).hide();
    
    if( type == "photo" ) {
      photo_row++;
    } else {
      gallery_row++;
    }
    
    // check if need to change button highlights
    f_setScrollUpButton(up_button_id, type);
    f_setScrollDownButton(galleries, down_button_id, type);
  }
}

function f_scroll_up(galleries, up_button_id, down_button_id, type) {
  var tracker = gallery_row;
  if( type == "photo" ) {
    tracker = photo_row;
  }

  if( tracker > 0 ) {
    var start = NUM_GAL_PER_ROW*(tracker-1);
//    galleries.children('img').removeClass('hover');
    galleries.slice(start,start+NUM_GAL_PER_ROW).show();
    
    if( type == "photo" ) {
      photo_row--;
    } else {
      gallery_row--;
    }
    
    // check if need to change button highlights
    f_setScrollUpButton(up_button_id, type);
    f_setScrollDownButton(galleries, down_button_id, type);
  }
}

function f_build_image_arr(images,gId,useThumbs) {
  var li_html = new Array();
  var prefix = "";
  var timestamp = new Date().getTime(); // because image may have been cropped, ensure refresh of image

  if( useThumbs ) {
    prefix = "t_";
  }
  
  images.each(function (index) {
    var $this = $(this);
    var fId = $.trim($this.children('fId').text());
    var fSrc = $.trim($this.children('fSrc').text());
    var d_id = 'd_photo_' + fId;
    var s_id = 's_photo_' + fId;
    var d_img = "";
    var fTitle = "";
    var fUrl = "";
    var fCaption = "";
    var load_text = "";
    var link_start = "";
    var link_end = "";
    
    if( $this.children('fTitle').length ) {
      fTitle = $.trim($this.children('fTitle').text());
    }
    
    if( $this.children('fUrl').length ) {
      fUrl = $.trim($this.children('fUrl').text());
      
      if( !is_admin && fUrl != "" ) {
        link_start = "<a href='" + fUrl + "'>";
        link_end = "</a>";
      }
    }

    if( $this.children('fCaption').length ) {
      fCaption = $.trim($this.children('fCaption').text());
    }

    if( is_admin ) {
      d_img = '<img id="' + d_id + '" class="gallery_delete" src="images/blue_delete.png" title="" alt="delete" />';
      d_img = d_img + '<img id="' + s_id + '" class="gallery_sort handle" src="images/blue_sort.png" title="" alt="Sort" style="cursor:move;" />';
      fSrc += '?' + timestamp; // make sure to always reload image in case of crop edits
    }

    if( !useThumbs ) {
      load_text = " onload='f_photo_loaded();'";
    }

    li_html[index] = "<li id='photo_" + fId + "'>" + link_start + "<img src='gallery/" + gId + "/" + prefix +  fSrc + "' alt='" + fTitle;
    li_html[index] += "' title='" + fTitle + "'" + load_text + " />" + link_end + d_img + "<div id='photo_caption_" + fId + "' style='display: none;'>";
    li_html[index] += fCaption + "</div></li>";
  });
  
  return li_html;
}

function f_load_gal_photo(gal, photo) {
  if( gal <= 0 || photo <= 0 || is_admin ) {
    return 0;
  }
  
  $('#gallery_' + gal).data('clicked', true);
  $('#gallery-list').data('set_photo',photo);

  f_makeSimpleAjaxGet("include/get_gallery.php",{id: gal},function (data, textStatus, xHR) {
    var response = $(data).children('response');
    if( response.children('success').eq(0).length ) {
      var id = $.trim(response.children('id').text());
      var title = $.trim(response.children('title').text());
      var publish = parseInt(response.children('publish').text());
      var images = response.children('images').children('image');

      var gallery_title = $('#portfolio-gallery-title');
      var selection_title = $('#portfolio-selection-title');
      var gallery_nav = $('#gallery-nav');
      var photo_nav = $('#gallery-photo-nav');
      var photo_caption = $('#portfolio-photo-caption');
      var photo_list = null;
      var li_html = null;
      var first_photo_block = null;
      var block_min_height = null;
      var first_photo = null;
      var first_photo_h = 0;
      var first_photo_title = "";
      var first_photo_caption = null;
      var padding = 0;
      var para_clone = photo_caption.clone();
      var full_height = 0;
      var limit_height = photo_caption.height();

      var presel_photo = $('#gallery-list').data('set_photo');
      $('#gallery-list').removeData('set_photo');
      
      $('#gallery-list').data('selected-gallery',id);

      if( images.length ) {
        gallery_title.text(title);
        selection_title.html("&nbsp;");

        $('#gallery-list').hide();
        gallery_nav.hide();

        photo_nav.after("<ul id='gallery-photo-list'></ul>");
        photo_list = $('#gallery-photo-list');

        li_html = f_build_image_arr(images,id,false);
        photo_list.html(li_html.join("\n"));

        presel_idx = -1;
        // find selected photo
        for(var i = 0;i < images.length;i++,presel_idx++) {
          if(parseInt(images.eq(i).children('fId').text()) == presel_photo) {
            presel_idx++;
            break;
          }
        }
        
        if(presel_idx == -1) { presel_idx = 0; }
        
        photo_idx = presel_idx;
        
        first_photo_block = photo_list.children('li:eq(' + presel_idx + ')');
        first_photo_caption = first_photo_block.children('div:eq(0)');

        f_image_display_adjust(first_photo_block);

        first_photo_block.show();
//            first_photo_block.css('visibility','visible');
        photo_nav.show();
        
        para_clone.css({
          height: 'auto',
          'max-height': 'none',
          overflow: 'visible',
          width: '657px',
          display: 'block',
          visibility: 'hidden',
          position: 'absolute',
          left: '-658px',
          top: '0'
        });
        para_clone.attr('id','photo-caption-test');
        para_clone.insertAfter(photo_caption);

        para_clone.text(first_photo_caption.text());
        full_height = para_clone.height();    
        para_clone.remove();

        gallery_title.html('<span id="photo-gal-title">' + title + ' &gt; </span>' + first_photo_title);
        photo_caption.text(first_photo_caption.text());

        if( full_height > limit_height ) {
          if( !$('#photo-caption-more').length ) {
            photo_caption.append('<div id="photo-caption-more">More...</div>');
          }
        }
        else {
          $('#photo-caption-more').remove();
        }

        photo_caption.show();
        selection_title.hide();
        
        f_setScrollLeftButton('gallery-left');
        f_setScrollRightButton(photo_list.children('li'), 'gallery-right');
      }
    }
    else {
      // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
      var err = $.trim(response.children('error').text());
      alert(err);
    }
  });
}

/**** DOCUMENT READY *********/

$(document).ready(function () {
  var gallery_title = $('#portfolio-gallery-title');
  var selection_title = $('#portfolio-selection-title');
  var galleries = $('#gallery-list li');
  var crop_select_x1 = $('#photo-crop-x1');
  var crop_select_x2 = $('#photo-crop-x2');
  var crop_select_y1 = $('#photo-crop-y1');
  var crop_select_y2 = $('#photo-crop-y2');
  var crop_select_w = $('#photo-crop-w');
  var crop_select_h = $('#photo-crop-h');

  $.extend( gallery_title,
    { portfolio_orig_text: gallery_title.text() }
  );

  $.extend( selection_title,
    { portfolio_orig_text: selection_title.text() }
  );

  /***** AJAX COMPLETE CALLBACKS FOR GALLERY *****/

  $('#gallery-list').ajaxComplete(function(event, request, settings) {
    var xml = $(request.responseXML);

    if( settings.url == 'include/create_gallery.php' ) {
      if( $('success',xml).length ) {
        var id = $('id',xml).text();
        var title = $('title',xml).text();

        $(this).append("<li id='gallery_" + id + "'><img src='images/gallery-default-thumb.png' alt='" + title + "' title='" + title + "' /></li>");
        galleries = $('#gallery-list li');  //refresh
        f_setScrollDownButton(galleries, 'gallery-down','gallery');
      }
      else {
        alert($.trim($('error',xml).text()));
      }
    } // end if settings.url = include/create_gallery
    else if( settings.url == 'include/edit_gallery.php' ) {
      if( $('success',xml).length ) {
        var id = $('id',xml).text();
        var title = $('title',xml).text();
        
        var gal_img  = $('#gallery_' + id).children('img');
        
        gal_img.attr('alt',title);
        gal_img.attr('title',title);
        
        alert("Gallery updated successfully");
      }
      else {
        alert($.trim($('error',xml).text()));
      }
    } // end if settings.url = include/edit_gallery
    else if( settings.url == 'include/del_gallery.php' ) {
      if( $('success',xml).length ) {
        var id = $('id',xml).text();
        
        $('#gallery_' + id).remove();
        galleries = $('#gallery-list li'); // refresh
        f_setScrollUpButton('gallery-up', 'gallery');
        f_setScrollDownButton(galleries, 'gallery-down','gallery');
      }
      else {
        alert($.trim($('error',xml).text()));
      }
    } // end if settings.url = include/del_gallery
  });

  /***** NEW GALLERY SUBMIT  ******/

  $('#gallery-new-form').submit(function () {
    f_makeSimpleAjaxPost("include/create_gallery.php", $(this).serialize(), null);
    this.reset();
    return false;
  });
  
  /***** GALLERY EDIT SUBMIT *****/

  $('#gallery-edit-form').submit(function () {
    f_makeSimpleAjaxPost("include/edit_gallery.php",$(this).serialize(),null);
    $('#gallery-edit-form-cancel').click();
    return false;
  });
  
  /***** GALLERY DELETE *****/
  
  $('#gallery-edit-delete').click(function () {
    var id = $('#gallery-edit-form-id').val();
    var title = $('#gallery-edit-form-title').val();

    if( confirm("Really delete gallery " + title + "? This will also delete all associated photos and cannot be undone!") ) {
      f_makeSimpleAjaxPost("include/del_gallery.php",{id: id},null);
      $('#gallery-edit-form-cancel').click();
    }
    return false;
  });

  /***** GALLERY EDIT CANCEL  *****/

  $('#gallery-edit-form-cancel').click(function () {
    $('#gallery-edit').hide();
    $('#gallery-edit-form-id').val('-1');
    $('#gallery-edit-form-title').val('');
    $('#gallery-edit-form-publish').removeAttr('checked');
    $('#gallery-edit-photo-nav').hide();
    $('#gallery-edit-photo-list').empty();
    return false;
  });
  
  /******* PHOTO CAPTION MORE *******/
  $('#photo-caption-more').live('click', function () {
    var para_clone = $('#portfolio-photo-caption').clone();

    para_clone.css({
      height: 'auto',
      'max-height': 'none',
      overflow: 'visible',
      width: '657px',
      display: 'block',
      visibility: 'visible'
    });
    para_clone.attr('id','caption-test-para');
    para_clone.children('div').remove(); // get rid of "more"
    
    $('<div id="caption-temp" style="display: none;"></div>').appendTo('body').append(para_clone);

    $.fn.colorbox({
      inline: true,
      href: '#caption-test-para',
      onCleanup: function () {
        $('#caption-temp').remove();
      }
    });
  });

  /******* PHOTO SCROLL LEFT *******/
  $('#gallery-left').click(function () {
    f_scroll_left($('#gallery-photo-list li'), 'gallery-left', 'gallery-right');
  });

  /******* PHOTO SCROLL RIGHT *******/
  $('#gallery-right').click(function () {
    f_scroll_right($('#gallery-photo-list li'), 'gallery-left', 'gallery-right');
  });

  /******* GALLERY RETURN *******/
  $('#gallery-return').click(function () {
    var photo_caption = $('#portfolio-photo-caption');
    var photo_nav = $('#gallery-photo-nav');
    var id = $('#gallery-list').data('selected-gallery');

    gallery_title.text(gallery_title.portfolio_orig_text);
    photo_caption.text('');
    photo_caption.hide();
    selection_title.text(selection_title.portfolio_orig_text);
    selection_title.show();

    photo_nav.hide();
    $('#gallery-photo-list').remove();
    $('#gallery-list').show();
    $('#gallery-nav').show();
    
    photo_idx = 0;

    $('#gallery_' + id).removeData('clicked');
    $('#photo-caption-more').remove();
  });

  /****** GALLERY SCROLL UP *******/

  $('#gallery-up').click(function () {
    f_scroll_up(galleries, 'gallery-up', 'gallery-down', 'gallery');
  });

  /****** GALLERY SCROLL DOWN  ******/

  $('#gallery-down').click(function () {
    f_scroll_down(galleries, 'gallery-up', 'gallery-down', 'gallery');
  });
  
  /****** GALLERY EDIT PHOTO SCROLL UP ******/

  $('#gallery-edit-photo-up').click(function () {
    var photos = $('#gallery-edit-photo-list li');
    f_scroll_up(photos, 'gallery-edit-photo-up', 'gallery-edit-photo-down', 'photo');
  });

  /******* GALLERY EDIT PHOTO SCROLL DOWN ******/

  $('#gallery-edit-photo-down').click(function () {
    var photos = $('#gallery-edit-photo-list li');
    f_scroll_down(photos, 'gallery-edit-photo-up', 'gallery-edit-photo-down', 'photo');
  });

  /***** GALLERY ENTRY MOUSEOVER *****/

  galleries.live("mouseover", function () {
    $(this).children('img').addClass('hover');
    gallery_title.text($(this).children('img').attr('title'));
    selection_title.html("&nbsp;");
  });

  /****** GALLERY ENTRY MOUSEOUT ******/

  galleries.live("mouseout", function () {
    $(this).children('img').removeClass('hover');
    
    if( typeof($(this).data('clicked')) == "undefined" ) {
      gallery_title.text(gallery_title.portfolio_orig_text);
      selection_title.text(selection_title.portfolio_orig_text);
      $(this).removeData('clicked');
    }
    else {
      $(this).removeData('clicked');
    }
  });
  
  /******* GALLERY EDIT PHOTO MOUSEOVER *******/
  // version of jquery used does not support .live calls on "hover"
  // did not want to try to resolve any potential plugin incompatabilities for the feature

  $('#gallery-edit-photo-list li').live("mouseover", function () {
    $(this).children('img').addClass('hover');
    var d_id = 'd_' + $(this).attr('id');
    $('#' + d_id).show();
    var s_id = 's_' + $(this).attr('id');
    $('#' + s_id).show();
  });
  
  /****** GALLERY EDIT PHOTO MOUSEOUT ******/

  $('#gallery-edit-photo-list li').live("mouseout", function () {
    $(this).children('img').removeClass('hover');
    var d_id = 'd_' + $(this).attr('id');
    $('#' + d_id).hide();
    var s_id = 's_' + $(this).attr('id');
    $('#' + s_id).hide();
  });

  /****** GALLERY CLICK ******/

  $('#gallery-list li img:not(.gallery_delete)').live("click",function() { // galleries.children('img').live(...) did not work
    var obj_id = $(this).parent().attr('id');    
    var gal_id = parseInt(obj_id.substring(obj_id.indexOf('_') + 1));
    
    $(this).parent().data('clicked', true);

    f_makeSimpleAjaxGet("include/get_gallery.php",{id: gal_id},function (data, textStatus, xHR) {
      var response = $(data).children('response');
      if( response.children('success').eq(0).length ) {
        var id = $.trim(response.children('id').text());
        var title = $.trim(response.children('title').text());
        var publish = parseInt(response.children('publish').text());
        var images = response.children('images').children('image');

        if( is_admin ) { // is_admin global defined in include/head.php        
          $('#gallery-edit-form-id').val(id);
          $('#gallery-edit-form-title').val(title);
          if( publish ) {
            $('#gallery-edit-form-publish').attr('checked','checked');
          }
          else {
            $('#gallery-edit-form-publish').removeAttr('checked');
          }

          $('#gallery-edit-photo-list').empty(); // clean out any items from a previous gallery selection

          if( images.length ) {
            $('#gallery-edit-photo-nav').show();
            var li_html = f_build_image_arr(images,id,true); //new Array();

            $('#gallery-edit-photo-list').html(li_html.join("\n"));
          }
        
          $('#gallery-edit').show();

          photo_row = 0;
          f_setScrollDownButton($('#gallery-edit-photo-list li'), 'gallery-edit-photo-down', 'photo');
        } // end is_admin
        else { // standard viewer
          var gallery_nav = $('#gallery-nav');
          var photo_nav = $('#gallery-photo-nav');
          var photo_caption = $('#portfolio-photo-caption');
          var photo_list = null;
          var li_html = null;
          var first_photo_block = null;
          var block_min_height = null;
          var first_photo = null;
          var first_photo_h = 0;
          var first_photo_title = "";
          var first_photo_caption = null;
          var padding = 0;
          var para_clone = photo_caption.clone();
          var full_height = 0;
          var limit_height = photo_caption.height();
          
          $('#gallery-list').data('selected-gallery',id);

          if( images.length ) {
            gallery_title.text(title);
            selection_title.html("&nbsp;");

            $('#gallery-list').hide();
            gallery_nav.hide();

            photo_nav.after("<ul id='gallery-photo-list'></ul>");
            photo_list = $('#gallery-photo-list');

            li_html = f_build_image_arr(images,id,false);
            photo_list.html(li_html.join("\n"));
            
            first_photo_block = photo_list.children('li:eq(0)');
            first_photo_caption = first_photo_block.children('div:eq(0)');

            f_image_display_adjust(first_photo_block);

            first_photo_block.show();
//            first_photo_block.css('visibility','visible');
            photo_nav.show();
            
            para_clone.css({
              height: 'auto',
              'max-height': 'none',
              overflow: 'visible',
              width: '657px',
              display: 'block',
              visibility: 'hidden',
              position: 'absolute',
              left: '-658px',
              top: '0'
            });
            para_clone.attr('id','photo-caption-test');
            para_clone.insertAfter(photo_caption);

            para_clone.text(first_photo_caption.text());
            full_height = para_clone.height();    
            para_clone.remove();

            gallery_title.html('<span id="photo-gal-title">' + title + ' &gt; </span>' + first_photo_title);
            photo_caption.text(first_photo_caption.text());

            if( full_height > limit_height ) {
              if( !$('#photo-caption-more').length ) {
                photo_caption.append('<div id="photo-caption-more">More...</div>');
              }
            }
            else {
              $('#photo-caption-more').remove();
            }
    
            photo_caption.show();
            selection_title.hide();
            
            f_setScrollLeftButton('gallery-left');
            f_setScrollRightButton(photo_list.children('li'), 'gallery-right');
          }
        } // end standard viewer        
      }
      else {
        // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
        var err = $.trim(response.children('error').text());
        alert(err);
      }
    });
  });
  
  /****** PHOTO UPLOAD ******/

  if( is_admin ) {
    new AjaxUpload($('#gallery-upload-photo'), {
      action: "include/upload_photo.php",
      name: 'uploadfile',
      onSubmit: function(file, ext) {
        if( ! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)) ) {
          $('#gallery-upload-status').text('Only JPG, PNG, or GIF files are allowed');
          return false;
        }
        this.setData({id: $('#gallery-edit-form-id').val()});
        $('#gallery-upload-status').text("Uploading...");
      },
      onComplete: function(file, data) {
        var response = $(data).children('response');
        $('#gallery-upload-status').text("");
        if( $(response).children('success').length ) {
          var gallery_id = $.trim($(response).children('id').text());
          var photo_id = $.trim($(response).children('photo_id').text());
          var path = $.trim($(response).children('path').text());
          var thumb = $.trim($(response).children('thumb').text());
          var count = parseInt($(response).children('photo_count').text());

          if( count == 1 ) { // first/only photo in gallery
            $('#gallery_' + gallery_id).children('img').attr('src', path + thumb);
          }

          $('<li id="photo_' + photo_id + '"></li>').appendTo('#gallery-edit-photo-list').html('<img src="' + path + thumb + '" alt="" />');

          f_setScrollDownButton($('#gallery-edit-photo-list li'), 'gallery-edit-photo-down', 'photo');
        }
        else {
          if( $(response).children('error').length ) {
            alert($.trim($(response).children('error').text()));
          }
          else {
            alert(data);
          }
        }
      }
    });
  }

  /****** GALLERY ADMIN PHOTO CLICK ******/

  $("#gallery-edit-photo-list li").live("click", function () {
    var photo_id = $(this).attr('id');
    var pId = photo_id.substr(photo_id.indexOf('_')+1);
    
    f_makeSimpleAjaxGet("include/get_gallery_photo.php", {id: pId}, function (data, textStatus, xHR) {
      var response = $(data).children('response');
      if( response.children('success').eq(0).length ) {
        var id = $.trim(response.children('fId').text());
        var title = $.trim(response.children('fTitle').text());
        var url = $.trim(response.children('fUrl').text());
        var caption = $.trim(response.children('fCaption').text());
        var gId = $.trim(response.children('feId').text());
        var src = $.trim(response.children('fSrc').text());
        var timestamp = new Date().getTime(); // because image may have been cropped, ensure refresh of image

        $('#photo-specific-link').text('/content.php?id=what_we_build&pageid=portfolio&gal=' + gId + '&photo=' + id);
        $('#photo-detail-id').val(id);
        $('#photo-detail-title').val(title);
        $('#photo-detail-url').val(url);
        $('#photo-detail-caption').val(caption);
        $('#photo-crop-img').attr('src','gallery/' + gId + '/' + src + '?' + timestamp).load(function () {
          $.fn.colorbox({
            inline: true,
            href: '#photo-crop-update',
            onComplete: function () {
              if( ias == null ) {
                ias = $('#photo-crop-img').imgAreaSelect({
                  aspectRatio: '1.45:1',
                  instance: true,
                  hide: true,
                  zIndex: 999999,
                  onSelectChange: function(img, selection) {
                    crop_select_x1.val(selection.x1);
                    crop_select_y1.val(selection.y1);
                    crop_select_x2.val(selection.x2);
                    crop_select_y2.val(selection.y2);
                    crop_select_w.val(selection.width);
                    crop_select_h.val(selection.height);
                  }
                });
              }
//              ias.setOptions({ show: true });
            },
            onCleanup: function () {
              ias.setOptions({ hide: true });
              crop_select_x1.val("-1");
              crop_select_x2.val("-1");
              crop_select_y1.val("-1");
              crop_select_y2.val("-1");
              crop_select_w.val("-1");
              crop_select_h.val("-1");
            }
          });
        });
      }
      else {
        // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
        var err = $.trim(response.children('error').text());
        alert(err);
      }
    });
  });
  
  /******** GALLERY ADMIN PHOTO DELETE CLICK ********/

  $('#gallery-edit-photo-list li img.gallery_delete').live("click", function (data, textStatus, xHR) {
    var d_id = $(this).attr('id');
    var pId = d_id.substring(d_id.lastIndexOf('_')+1);

    var src = $('#photo_' + pId).children('img:not(.gallery_delete)').attr('src');
    src = src.substring(src.lastIndexOf('/')+1).substring(2); // clear path info and 't_' prefix
    
    if( !confirm("Really delete photo: " + src + "?") ) {
      return false;
    }

    f_makeSimpleAjaxPost("include/del_gallery_photo.php", {id: pId}, function (data, textStatus, xHR) {
      var response = $(data).children('response');
      if( response.children('success').eq(0).length ) {
        var id = $.trim(response.children('fId').text());  
        var delError = response.children('delError');
        
        if( delError.length ) {
          var errors = "";
          for(var i = 0;i < delError.length;i++) {
            errors += $.trim(delError.eq(i).text()) + "\n";
          }
          
          alert(errors);
        }
        else {
          $('#photo_' + id).remove();
        }
      }
      else {
        // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
        var err = $.trim(response.children('error').text());
        alert(err);
      }
    });

    return false;
  });
  
  /******* PHOTO DETAIL SUBMIT ******/

  $('#photo-detail').submit(function () {
    var pId = $('#photo-detail-id').val();
    var pTitle = $('#photo-detail-title').val();
    var pUrl = $('#photo-detail-url').val();
    var pCaption = $('#photo-detail-caption').val();

    $('#photo-detail-submit').attr('disabled','disabled');    
    $('#photo-crop-spinner').show();
    
    f_makeSimpleAjaxPost("include/set_gallery_photo_data.php", {
      id: pId,
      gId: $('#gallery-edit-form-id').val(),
      title: pTitle,
      url: pUrl,
      caption: pCaption,
      x1: crop_select_x1.val(),
      x2: crop_select_x2.val(),
      y1: crop_select_y1.val(),
      y2: crop_select_y2.val(),
      width: crop_select_w.val(),
      height: crop_select_h.val()
    },
    function (data, textStatus, xHR) {
      var response = $(data).children('response');
      if( response.children('success').eq(0).length ) {
        var pId = $.trim(response.children('fId').text());

        var timestamp = new Date().getTime();
        var img = $('#photo_' + pId).children('img:not(.gallery_delete)');
        var src = img.attr('src');
        var queryPos = src.lastIndexOf('?');
        
        if( queryPos > 0 ) {
          src = src.substring(0,queryPos);
        }

        // refresh thumbnail
        img.attr('src', src + '?' + timestamp);

        $('#photo-crop-spinner').hide();
        $('#photo-crop-updated').fadeIn('fast',function () {
          setTimeout("$('#photo-crop-updated').fadeOut('slow')",1000);
        });
      }
      else {
        // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
        var err = $.trim(response.children('error').text());
        alert(err);
      }
      $('#photo-detail-submit').removeAttr('disabled');
      $('#photo-crop-spinner').hide();
    },
    function (xHR, textStatus, errorThrown) {
      $('#photo-detail-submit').removeAttr('disabled');
      $('#photo-crop-spinner').hide();
    });
    return false;
  });

  /******* IF GALLERY STRUCTURE EXISTS... do setup *******/

  if( $('#gallery-list').length ) {
    if( is_admin ) { // handle overflow for sorting in admin
      $('#gallery-list, #gallery-edit-photo-list').css('overflow','visible');
      $('#gallery-list').after('<br style="clear: both" />');
      $('#gallery-nav, #gallery-edit-photo-nav').hide();
    }
    
    // set 'active' scroll button if necessary
    f_setScrollDownButton(galleries, 'gallery-down','gallery');
  
    // load gallery thumbs
    f_makeSimpleAjaxGet("include/get_gallery_thumbs.php", null, function (data, textStatus, xHR) {
      var response = $(data).children('response');
      if( response.children('success').eq(0).length ) {
        var g_thumbs = response.children('gallery');
        g_thumbs.each(function (index) {
          var gallery_id = $.trim($(this).children('feId').text());
//          var photo_id = $.trim($(this).children('fId').text());
          var photo_src = $.trim($(this).children('fSrc').text());
        
          $('#gallery_' + gallery_id + ' > img').attr('src', 'gallery/' + gallery_id + '/t_' + photo_src);
        });
      }
      else {
        // handle error here ('error:' above handles transport/parser errors, here we handle any errors trapped by our php script)
        var err = $.trim(response.children('error').text());
        alert(err);
      }
    });
  }
});

