function ThumbnailPage() {
  this.CurrentFolderName = null;
  this.Cookie = null;
  this.ProEmail = null;
  this.MaxFavorites = 500;
  this.DivNames = ["eventset_contentbox", "page_listing_contentbox", "thumbs_contentbox", "content_thumbs"];
  this.CurMode = 'DEF';
  this.BreadcrumbContext = null;
  this.MaxFavoritesNotified = false;
  this.VisitedEventAccessIds = [];
  this.CurEvent = null;
  this.CurPage = null;

  this.EL = null;
  this.ID = null;
  this.FMs = [];

  this.Init = ThumbnailPageInit;
  this.Resize = ThumbnailPageResize;
  this.PrevThumbs = ThumbnailPagePrevThumbs;
  this.NextThumbs = ThumbnailPageNextThumbs;
  this.JumpToPage = ThumbnailPageJumpToPage;
  this.Order = ThumbnailPageOrder;
  this.ViewCart = ThumbnailPageViewCart;
  this.SelectAll = function() { this.ID.SelectAll(); }
  this.DeselectAll = function() { this.ID.DeselectAll(); }
  this.UpdateView = TPUpdateView;
  this.ToggledFavoriteness = ThumbnailPageToggledFavoriteness;
  this.TPImageIdToFolderEPILoc = ThumbnailPageTPImageIdToFolderEPILoc;
  this.ShowDiv = ThumbnailPageShowDiv;
  this.MaxFIndex = ThumbnailPageMaxFIndex;
  this.FIndexToTPImageId = ThumbnailPageFIndexToTPImageId;
  this.GetEvents = ThumbnailPageGetEvents;
  this.SubmitEmailAddress = ThumbnailPageSubmitEmailAddress;
  this.UpdateBreadcrumbs = TPUpdateBreadcrumbs;
  this.UpdateFMs = TPUpdateFMs;
  this.UpdateCurEvent = TPUpdateCurEvent;

  this.ViewEmpty = TPViewEmpty;
  this.ViewEventSetNav = TPViewEventSetNav;
  this.ViewPageListing = TPViewPageListing;
  this.ViewThumbs = TPViewThumbs;
  this.ViewImagePopup = TPViewImagePopup;
  this.ShowErrorDialog = TPShowErrorDialog;
  this.DrawEventSetNav = TPDrawEventSetNav;
  this.DrawPageListing = TPDrawPageListing;
  this.DrawThumbs = TPDrawThumbs;
  this.DrawThumbsBackground = TPDrawThumbsBackground;
  this.DrawImagePopup = TPDrawImagePopup;
  this.UpdateCookie = TPUpdateCookie;
  this.GetCookieVal = TPGetCookieVal;
}

function ThumbnailPageInit(events, cart_cookie, ready_counts, pro_email) {
  if (! document.cookie.match(/Valid=Test/)) {
    jAlert(
      'It appears that cookies are not enabled in your browser.<br>' +
      'Please set your computer to allow cookies in order to continue.<br><br>' +
      '<b>What is a cookie?</b><br>' +
      'A cookie is a small amount of data that is sent to your browser by<br>' +
      'our server to remember what you are ordering. The cookie will expire<br>' +
      '(be removed) once your order is placed, or after 30 days.<br><br>' +
      '<b>Why do I need to enable cookies?</b><br>' +
      'We use cookies to manage the ordering process. Cookies allow you to place<br>' +
      'items in your shopping cart and return later (up to 30 days) to complete your order.<br><br>' +
      'Our cookie is used exclusively on this site, and is deleted once the order is<br>' +
      'placed, or after 30 days.<br><br>' +
      '<b>How do I enable cookies on my browser?</b><br>' +
      'There are several different browsers you could be using.  Please consult "Help"<br>' +
      'on your browser toolbar on how to allow cookies.<br>',
      'Cookies Not Enabled',
      function() { history.back(); }
    );
    return;
  }

  $('body').data('page_loader', new PageLoader());
  $('body').data('image_desc_loader', new ImageDescLoader());

  TP = this;
  TP.ViewEmpty();
  var EL = new EventLoader;
  TP.EL = EL;
  var ID = new ImageDisplayer;
  TP.ID = ID;
  TP.EL.Events = events;
  for (var i = 0; i < this.EL.Events.length; i++) {
    var event = this.EL.Events[i];
    event.Index = i;
    event.StartSeq = EL.ImageCount;
    EL.ImageCount += event.ImageCount;
    this.EL.AccessIdEventI[event.AccessId] = i;
  }

  this.Cookie = cart_cookie;

  if (ready_counts['ready'] == 0) {
    var contact_the_photographer;
    if (pro_email != "") {
      contact_the_photographer = '<a href="mailto:'+pro_email+'" style="color:#6974b6;"><b>contact the photographer</b></a>.'
    }
    else {
      contact_the_photographer = 'contact the photographer.'
    }
    if (ready_counts['unready'] > 0) {
      var event_access_ids = [];
      for (var i = 0; i < TP.EL.Events.length; i++) {
	var event = TP.EL.Events[i];
	if (! event.Ready) event_access_ids.push(event.AccessId);
      }
      $('#error_title').html('<div style="padding:10px;"><strong>Events not ready</strong></div>');
      var event_has = event_access_ids.length == 1 ? 'This event has' : 'These events have';
      var message_html =
	'<div style="width:400px;height:200px;padding:10px;">' +
        event_has+' not yet been been published by the photographer.<br><br>' +
        'If you wish to be notified when the images are available for viewing, ' +
        'please enter your email address below.<br><br>' +
        'Email address:<br><br>' +
        '<form id="available_email_form">' +
          '<input id="available_email_textbox" type="textbox" size="20" style="padding-right: 5px;"/>' +
          '&nbsp;<button id="available_email_submit" style="padding-left: 5px;">Submit</button>' +
        '</form>' +
	'</div>';

      $('#error_message').html(message_html);
      $('#available_email_form').submit(function() {
        TP.SubmitEmailAddress($('#available_email_textbox').val(), event_access_ids, 'available');
        return false;
      });
      $('#available_email_submit').click(function() {
        TP.SubmitEmailAddress($('#available_email_textbox').val(), event_access_ids, 'available');
        return false;
      });

      $('#errorbox_a').nyroModalManual({
        width: 400,
        height: 200,
        endRemove: function() { history.back(); }
      });
    }
    else if (ready_counts['expired'] > 0) {
      var this_event_is = (ready_counts['expired'] > 1) ?
	'These events are' : 'This event is';
      jAlert(
        this_event_is+' expired.<br><br>' +
	'For more information, please '+contact_the_photographer,
        'Event Expired',
        function() { history.back(); }
      );
    }
    else if (ready_counts['unpublished'] > 0) {
      var this_event_is = (ready_counts['unpublished'] > 1) ?
	'These events are' : 'This event is';
      jAlert(
        this_event_is+' unavailable.<br><br>' +
	'For more information, please '+contact_the_photographer,
        'Event Unavailable',
        function() { history.back(); }
      );
    }
    else if (TP.GetCookieVal('pro_access_id') != null) {
      jAlert(
	'There are no events currently active.<br><br>' +
	'For more information, please '+contact_the_photographer,
	'No Active Events',
	function() { history.back(); }
      );
    }
    else {
      jAlert(
	'The password you\'ve entered is incorrect.<br><br>' +
	'For more information, please '+contact_the_photographer,
	'Invalid Password',
	function() { history.back(); }
      );
    }
    return;
  }

  this.ProEmail = pro_email;

  for (i = 0; i < events.length; i++) {
    var event_access_id = events[i].AccessId;
    var re = new RegExp('H'+event_access_id+'=v&1');
    if (document.cookie.match(re)) {
      TP.VisitedEventAccessIds[event_access_id] = 1;
    }
  }


  this.ID.GetCurrentEvent = function() {
    var event_access_id = TP.GetCookieVal('event_access_id');
    if (event_access_id == null) return null;
    var e_idx = EL.AccessIdEventI[event_access_id];
    var events = TP.GetEvents();
    if (events == null) return null;
    return events[e_idx];
  }
  this.ID.DisplayRow = document.getElementById("image_displayer_row_thumbs");
  this.ID.ToggleFavoriteness = function(image_desc) {
    if (TP.CurrentFolderName == "favorites") return;
    var favorites = TP.FMs['favorites'];
    if (! favorites.IsMember(image_desc.Index) &&
	favorites.GetNumMembers() >= TP.MaxFavorites) {
      if (! TP.MaxFavoritesNotified) {
	jAlert('Sorry, you can only select '+TP.MaxFavorites+' images at once.  Please deselect some images, or click "Order Products" and return here to select more images.');
	TP.MaxFavoritesNotified = true;
      }
      return;
    }
    favorites.ToggleMembership(image_desc);
    TP.ToggledFavoriteness();
  };
  this.ID.GetFIndexTPImageId = function(f_idx) {
    if (TP.CurrentFolderName == null) return null;
    if (TP.FMs[TP.CurrentFolderName] == null) return null;
    return TP.FMs[TP.CurrentFolderName].GetFIndexTPImageId(f_idx);
  };
  this.ID.TPImageIdToEPILoc = function(tp_image_id) {
    return EL.TPImageIdToEPILoc(tp_image_id);
  };
  this.ID.GetPageLength = function(e_idx, p_idx) {
    return TP.EL.Events[e_idx].PageOverviews[p_idx].ImageCount;
  };

  this.ID.Resize();

  var cur_ivid = TP.GetCookieVal('cur_ivid', '[0-9]');
  var password = TP.GetCookieVal('password');

  this.CurrentFolderName = 'main';

  this.EL.Init(
    password,
    cur_ivid,
    true,
    function(cur_tp_image_id) {
      TP.UpdateFMs();
      var pro_access_id = TP.GetCookieVal('pro_access_id');
      var u = TP.GetCookieVal('u');
      var uv_password = password;
      if (pro_access_id != null && u != null && (u & 16 == 0))
	uv_password = null;
      TP.UpdateView(uv_password, cur_tp_image_id);
      if (cur_tp_image_id != null) {
	var epi_loc = TP.EL.TPImageIdToEPILoc(cur_tp_image_id);
	if (epi_loc != null)
	  TP.ID.UpdateMenu(epi_loc.EventIndex, epi_loc.PageIndex);
      }
    },
    function(error_title, error_message) {
      TP.UpdateFMs();
      TP.UpdateView(password, null);
    }
  );

  $('.gallery_link').click(function() {
    TP.DrawEventSetNav(null, null);
    TP.ViewEventSetNav("GAL");
    TP.CurMode = "GAL";
    TP.BreadcrumbContext = "GAL";
    TP.UpdateBreadcrumbs();
    return false;
  });
  $('.searchres_link').click(function() {
    var password = TP.GetCookieVal('password');
    TP.ViewEventSetNav("SRCH");
    return false;
  });
  $('.eventlisting_link').click(function() {
    TP.DrawEventSetNav(null, null);
    TP.ViewEventSetNav("ELIST");
    return false;
  });
  $('.pagelisting_link').click(function() {
    TP.ViewPageListing();
    return false;
  });

  window.onbeforeunload = function() {
    if (TP.FMs['favorites'] != undefined &&
	TP.FMs['favorites'].GetNumMembers() > 0) {
      return 'Clicking "OK" will cause your image selections to be discarded.';
    }
    return;
  }
}

function TPViewEmpty() {
  this.CurMode = 'DEF';
  TP.UpdateBreadcrumbs();
  this.ShowDiv({});
}

function TPViewEventSetNav(cur_page) {
  this.CurMode = cur_page == null ? 'GAL' : cur_page;
  TP.UpdateCookie({"cur_page": this.CurMode});
  TP.UpdateBreadcrumbs();
  this.ShowDiv({ "eventset_contentbox": 1 });
}

function TPViewPageListing() {
  this.CurMode = "PLIST";
  TP.UpdateCookie({"cur_page": this.CurMode});
  TP.UpdateBreadcrumbs();
  this.ShowDiv({ "page_listing_contentbox": 1 });

  var event_access_id = TP.GetCookieVal('event_access_id');
  if (event_access_id != null) TPNotifyHit(event_access_id);
}


function TPViewThumbs(skip_jump_page) {
  var TP = this;

  TP.CurMode = 'THUMB';
  TP.UpdateCookie({"cur_page": TP.CurMode});
  TP.UpdateBreadcrumbs();
  TP.ShowDiv({ "thumbs_contentbox": 1, "content_thumbs": 1 });

  TP.ID.DisplayRow = document.getElementById("image_displayer_row_thumbs");
  TP.CurrentFolderName = 'main';

  TP.Resize();

  if (skip_jump_page == null || ! skip_jump_page)
    TP.JumpToPage(TP.CurPage.Index);

  var thumb_num = 0;
  var image_desc = TP.ID.PageImageDescs[thumb_num];
  if (image_desc != null) {
    TP.ID.UpdateSelectedImageDesc(image_desc);
    TP.UpdateCookie({cur_page: 'THUMB', cur_ivid: image_desc.FavoriteId});
  }
  else {
    TP.UpdateCookie({cur_page: 'THUMB'});
  }

  if (TP.ID.Thumbnails[thumb_num] != null) {
    var y_offset = 0;
    var obj = TP.ID.Thumbnails[thumb_num].Canvas;
    y_offset = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
      y_offset += obj.offsetTop;
    }
    var viewport_height;
    if (typeof window.innerWidth != 'undefined') {
      viewport_height = window.innerHeight;
    }
    else if (typeof document.documentElement != 'undefined' &&
	     typeof document.documentElement.clientWidth != 'undefined' &&
	     document.documentElement.clientWidth != 0) {
      viewport_height = document.documentElement.clientHeight;
    }
    else {
      viewport_height = document.getElementsByTagName('body')[0].clientHeight;
    }
    window.scroll(0, y_offset + 180 - viewport_height);
  }

  TPNotifyHit(TP.CurEvent.AccessId);
}

function TPViewImagePopup() {
  this.CurMode = "POPUP";
  TP.UpdateCookie({"cur_page": this.CurMode});
  TP.UpdateBreadcrumbs();

  var event_access_id = TP.GetCookieVal('event_access_id');
  if (event_access_id != null) TPNotifyHit(event_access_id);
}

function TPShowErrorDialog(next_page) {
  TP.UpdateBreadcrumbs();
}

function TPUpdateBreadcrumbs() {
  var visible_breadcrumbs = {};
  if (this.BreadcrumbContext == "GAL") {
    if (this.CurMode == "GAL") visible_breadcrumbs = {"gallery": 1};
    else visible_breadcrumbs = {"gallery": 1, "pagelisting": 1};
  }
  if (this.BreadcrumbContext == "SRCH") {
    if (this.CurMode == "GAL" || this.CurMode == "SRCH")
      visible_breadcrumbs = {"gallery": 1, "searchres": 1};
    else visible_breadcrumbs = {"gallery": 1, "searchres": 1, "pagelisting": 1};
    $('.searchres_link').each(
      function() {
	var search = $(this).metadata().search;
	if (search != null)
	  $(this).html('<strong>Search Results: '+search+'</strong>');
	else
	  $(this).html('<strong>Search Results</strong>');
      } 
    );
  }
  if (this.BreadcrumbContext == "ELIST") {
    if (this.CurMode == "ELIST") visible_breadcrumbs = {"eventlisting": 1};
    else visible_breadcrumbs = {"eventlisting": 1, "pagelisting": 1};
  }
  if (this.BreadcrumbContext == "PLIST")
    visible_breadcrumbs = {"pagelisting": 1};

  var breadcrumbs = ["gallery", "searchres", "eventlisting", "pagelisting"];
  for (var i = 0; i < breadcrumbs.length; i++) {
    if (visible_breadcrumbs[breadcrumbs[i]] != null)
      $('.'+breadcrumbs[i]+'_breadcrumb').show();
    else $('.'+breadcrumbs[i]+'_breadcrumb').hide();
  }
}

function TPDrawEventSetNav(cur_event_i, search) {
  var event_set_i_keys = {};
  if (search == null) {
    for (var event_i in TP.EL.Events) {
      if (cur_event_i == null) event_set_i_keys[event_i] = 1;
      else if (event_i == cur_event_i) event_set_i_keys[event_i] = 1;
    }
  }
  else {
    if (TP.EL.PasswordEventIs[search] != null) {
      var re = new RegExp(search, 'i');
      for (var event_i in TP.EL.Events) {
	var event = TP.EL.Events[event_i];
	if ((cur_event_i == null || event_i == cur_event_i) && event.Title.match(re)) {
	  event_set_i_keys[event_i] = 1;
	}
      }
      for (var i in TP.EL.PasswordEventIs[search]) {
	var event_i = TP.EL.PasswordEventIs[search][i];
        if (cur_event_i == null || event_i == cur_event_i) {
	  event_set_i_keys[event_i] = 1;
	  var event = TP.EL.Events[event_i];
	}
      }
      TP.BreadcrumbContext = 'SRCH';
      TP.CurMode = 'SRCH';
      $('.searchres_link').each(
	function() {
	  $(this).metadata().search = search;
	}
      );
    }
    else {
      this.EL.Init(
        search,
        null,
	false,
        function(cur_tp_image_id) {
	  TP.UpdateFMs();
	  if (cur_tp_image_id == null && cur_event_i != null)
	    cur_tp_image_id = TP.EL.Events[cur_event_i].StartSeq;
	  if (cur_tp_image_id != null) {
	    var epi_loc = TP.EL.TPImageIdToEPILoc(cur_tp_image_id);
	    if (epi_loc != null)
	      TP.ID.UpdateMenu(epi_loc.EventIndex, epi_loc.PageIndex);
	  }
	  TP.UpdateCookie({ cur_page: 'SRCH' });
	  TP.DrawEventSetNav(cur_event_i, search);
        },
	function(error_title, error_message) {
	  TP.DrawEventSetNav(cur_event_i, search);
	}
      );
      return;
    }
  }

  TP.UpdateBreadcrumbs();

  var event_set_is = [];
  for (var event_i in event_set_i_keys) {
    event_set_is.push(event_i);
  }
  event_set_is.sort(function(a, b) { return a - b; });
  if (event_set_is.length == 1) {
    var event = TP.EL.Events[event_set_is[0]];
    if (! event.Locked) {
      $('body').css('cursor', 'wait');
      $('body').data('page_loader').load_page_overviews(
	event,
	function() {
	  $('body').css('cursor', 'auto');
	  TP.UpdateCurEvent(event);
	  TP.UpdateCookie({ cur_page: 'PLIST' });
	  TP.DrawPageListing(event);
	  TP.ViewPageListing();
	},
	function() {
	  $('body').css('cursor', 'auto');
	  var contact_the_photographer;
	  if (TP.ProEmail != "")
	    contact_the_photographer = '<a href="mailto:'+TP.ProEmail+'" style="color:#6974b6;"><b>contact the photographer</b></a>.'
	  else
	    contact_the_photographer = 'contact the photographer.'
          jAlert('Error loading event information.  Please try again later, or '+contact_the_photographer+'.');
	}
      );
      return;
    }
  }

  var event_set_html =
    '<div style="margin: 0 auto; text-align: left; width: 100%; position: relative;">' +
      '<table width="100%">' +
	'<tr>' +
	  '<td width="185">' +
	    'Enter your <b>Guest Password</b> or <br /><b>Event Title</b> ' +
	    'for search here:' +
	  '</td>' +
	  '<td align="left">' +
	    '<form id="eventsetnavSearchForm">' +
	      '<input id="eventsetnavSearchInput" size="20" />' +
	      '<img src="/_img/clear.gif" width="5" height="1">' +
	      '<button id="eventsetnavSearchSubmit">Search</button>' +
	    '</form>' +
	  '</td>' +
	  '<td width="250" style="border: dotted #666666 thin; padding: 5px;">' +
	    '<img src="/_img/ecom/gallery-lock.png" hspace="5" width="30" height="30" align="left" style="padding-right: 10px; padding-left: 10px;">' +
	    '<small>This lockbox icon shows that the event requires a password in order to view.</small>' +
	  '</td>' +
	'</tr>' +
      '</table>' +
    '</div>';
  for (var i = 0; i < event_set_is.length; i++) {
    var event_i = event_set_is[i];
    var event = TP.EL.Events[event_i];
    if (event.OmitGallery && event.Locked) continue;
    if (event.Ready) {
      if (event.Locked)
        event_set_html += '<a class="eventsetnavPwbox {index: '+event_i+'}" href="#eventsetnavPwbox">';
      else
        event_set_html += '<a class="eventsetnavPass {index: '+event_i+'}" href="#">';
    }
    else {
      event_set_html += '<a class="eventsetnavNotbox {access_id: \''+event.AccessId+'\'}" href="#eventsetnavNotbox">';
    }
    event_set_html +=
      '<div class="gallery_bg">' +
	'<div style="height: 100px; padding-bottom: 10px;">';
    if (event.ExampleImageRef) event_set_html +=
	  '<img src="http://i.digiproofs.com/g/'+event.ExampleImageRef+'.png" />';
    else event_set_html +=
	  '<img src="http://i.digiproofs.com/a/a9db016876c79fb717d2aaba760266f8" />';
    event_set_html +=
	'</div>';
    if (event.Title.length > 57) {
      event_set_html +=
	'<span style="word-wrap: break-word;" title="'+event.Title.replace(/"/g, '&quot;')+'">' +
	  event.Title.substr(0, 54)+'...' +
	'</span>';
    }
    else {
      event_set_html += event.Title;
    }
    event_set_html +=
      '</div>' +
    '</a>';
  }
  event_set_html +=
    '<div style="display:none;" id="eventsetnavPwbox" />';
  event_set_html +=
    '<div style="display:none;" id="eventsetnavNotbox" />';

  $('#eventset_container').html(event_set_html);

  $('.eventsetnavPwbox').nyroModal({
    width: 440,
    height: 200,
    processHandler: function(settings) {
      var contact_the_photographer;
      if (TP.ProEmail != "") {
	contact_the_photographer = '<a href="mailto:'+TP.ProEmail+'" style="color:#6974b6;"><b>contact the photographer</b></a>.';
      }
      else {
	contact_the_photographer = 'contact the photographer.';
      }
      $('#eventsetnavPwbox').html(
      '<div id="eventsetnavPwboxContent">' +
	'<table border="0" width="100%" cellspacing="0" cellpadding="0">' +
	  '<tr>' +
	    '<td background="/_pro/_img/nyro-background.jpg" align="center" valign="middle" style="height: 38px;">' +
	      '<strong>Enter Guest Password</strong>' +
	    '</td>' +
	  '</tr>' +
	  '<tr>' +
	    '<td align="center"><br />' +
	      '<input id="eventsetnavPasswordText" type="text" name="password" size="25" value="" />' +
	      '<button class="continue_button {index: '+$($(settings.from).get()).metadata().index+'}" id="password_button">Continue</button>' +
	      '<br /><br />' +
	      'If you need a password please '+contact_the_photographer +
	    '</td>' +
	  '</tr>' +
	'</table>' +
      '</div>');
      $('.continue_button').click(function() {
	TP.DrawEventSetNav(
	  $($(this).get()).metadata().index,
	  $('#eventsetnavPasswordText').val().toLowerCase()
	);
	$.nyroModalRemove();
	return false;
      });
    }
  });

  $('.eventsetnavNotbox').nyroModal({
    width: 400,
    height: 200,
    processHandler: function(settings) {
      $('#eventsetnavNotbox').html(
    '<div style="padding:10px;width:400px;height:200px;">' +  
	'This event has not yet been been published by the photographer.<br><br>' +
	'If you wish to be notified when the images are available for viewing, ' +
	'please enter your email address below.<br><br>' +
	'Email address:<br><br>' +
	'<form class="available_email_form {access_id: \''+$($(settings.from).get()).metadata().access_id+'\'}" action="#">' +
	  '<input id="available_email_textbox" type="textbox" size="20" style="padding-right: 5px;"/>' +
	  '&nbsp;<button class="available_email_submit {access_id: \''+$($(settings.from).get()).metadata().access_id+'\'}" style="padding-left: 5px;">Submit</button>' +
	'</form>' +
	'</div>'
      );

      $('.available_email_form').submit(function() {
	TP.SubmitEmailAddress($('#available_email_textbox').val(), [$($(this).get()).metadata().access_id], 'available');
	$.nyroModalRemove();
	return false;
      });
      $('.available_email_submit').click(function() {
	TP.SubmitEmailAddress($('#available_email_textbox').val(), [$($(this).get()).metadata().access_id], 'available');
	$.nyroModalRemove();
	return false;
      });
    }
  });

  $('.eventsetnavPass').click(function() {
    TP.DrawEventSetNav($($(this).get()).metadata().index, search);
    return false;
  });

  $('#eventsetnavSearchForm').submit(function() {
    TP.DrawEventSetNav(null, $('#eventsetnavSearchInput').val().toLowerCase())
    return false;
  });
  $('#eventsetnavSearchSubmit').click(function() {
    TP.DrawEventSetNav(null, $('#eventsetnavSearchInput').val().toLowerCase())
    return false;
  });

}

function TPDrawPageListing(event) {
  if (event == null || ! event.Loaded) return;

  var TP = this;
  TP.UpdateCurEvent(event);

  var event_listing_html = '';
  if (event.WelcomeMessageId != null &&
      this.EL.WelcomeMessages[event.WelcomeMessageId] != null) {
    event_listing_html +=
      '<tr><td align="center">'+this.EL.WelcomeMessages[event.WelcomeMessageId]+'</td></tr>';
  }

  var expiration_warning = "";
  if (event.Expiration != null) expiration_warning =
    "<br><br>ATTENTION - This event will expire "+event.Expiration;

  event_listing_html +=
      '<tr><td align="center" valign="center">' +
	'<br />' +
	'<div style="width: 580px; height: 70px; border-top: 1px solid gray; border-bottom: 1px solid gray;">' +
	  '<div style="position: relative; float: left; width: 290px; padding-top: 12px; padding-left: 5px; text-align: left;">' +
	    'If you would like a reminder of this event\'s expiration, enter your email address here and click <strong>Submit</strong>.' +
	    expiration_warning +
	  '</div>' +
	  '<div style="position: relative; float: left; width: 280px; padding-top: 12px;">' +
	    '<form id="email_form">' +
	    '<input id="email_textbox" type="textbox" size="20" style="padding-right: 5px;"/>' +
	    '&nbsp;<button id="email_submit" style="padding-left: 5px;">Submit</button>' +
	    '</form>' +
	  '</div>' +
	'</div>' +
      '</td></tr>' +
      '<br />';

  var event_description = event.EventDescription == null ? "" : event.EventDescription;
  event_listing_html +=
      '<tr><td>&nbsp;</td></tr>' +
      '<tr><td><h3 id="event_name" style="text-transform: capitalize; text-align: center;">'+event.Title+'</h3></td></tr>' +
      '<tr>' +
	'<td><div style="width:580px; padding-left:135px; padding-bottom:5px;">'+event_description+'</div></td>' +
      '</tr>' +
      '<tr>' +
      '<td align="center">' +
      '<table width="500" align="center">' +
	'<tr>'+
	  '<td class="page_listing_page_background" style="text-align: left; padding-top: 15px; padding-left: 10px;">' +
	    '<big><i>Page Listing</i> <strong>&darr;</strong></big>' +
	  '</td>' +
	'</tr>';
  for (var i = 0; i < event.PageOverviews.length; i++) {
    var page_overview = event.PageOverviews[i];
    event_listing_html +=
	'<tr>' +
	  '<td>' +
	    '<table style="width:500px; margin-left:5px;">' +
	      '<tr>' +
		'<td class="page_listing_page_title_left" style="text-align:left;">' +
		  '<a href="#" class="page_title {index: '+i+'}">'+page_overview.Title+'</a>' +
		'</td>' +
		'<td class="page_listing_page_title_right">' +
		  '<span class="pagestats">('+page_overview.ImageCount+' images)</span>' +
		'</td>' +
	      '</tr>' +
	    '</table>' +
	  '</td>' +
	'</tr>';
  }
  event_listing_html +=
      '</table>';

  $('#event_listing').html(event_listing_html);

  $('#email_form').submit(function() {
    TP.SubmitEmailAddress(
      $('#email_textbox').val(),
      [event.AccessId],
      'expiring'
    );
    return false;
  });
  $('#email_submit').click(function() {
    TP.SubmitEmailAddress(
      $('#email_textbox').val(),
      [event.AccessId],
      'expiring'
    );
    return false;
  });

  var TP = this;
  $('.page_title').click(function() {
    TP.CurrentFolderName = 'main';
    TP.JumpToPage($(this).metadata().index, null, function() { TP.ViewThumbs(true) });
    return false;
  });
}

function TPDrawThumbs() {
}

function TPDrawImagePopup(tp_image_id) {
}

function ThumbnailPageSubmitEmailAddress(email, event_access_ids, type) {
  email = email.substr(0, 128);
  var filter=/(^[\-_\.a-zA-Z0-9]+)@((([0-9]{1,3}\.){3}([0-9]{1,3})((:[0-9])*))|(([a-zA-Z0-9\-]+)(\.[a-zA-Z0-9\-]+)+(\.[a-zA-Z]{2})?((:[0-9])*)))/;
  if (email == "" || email.search(filter)) {
    jAlert("Please provide a complete and valid email address.");
    return false;
  }

  $.ajax({
    type: 'GET',
    url: '/ecom/email_add.pl',
    data: {
      email: email,
      event_access_ids: event_access_ids.join(','),
      type: type
    },
    dataType: 'json',
    success: function(data, status) {
      jAlert(data.message, data.title);
    }
  });
}

function ThumbnailPageShowDiv(show_div_names) {
  for (var div_name_idx in this.DivNames) {
    var div_name = this.DivNames[div_name_idx];
    var div = document.getElementById(div_name);
    if (show_div_names[div_name] != null) {
      div.style.visibility = "visible";
      div.style.display = "block";
    }
    else {
      div.style.visibility = "hidden";
      div.style.display = "none";
    }
  }
}

function ThumbnailPageResize() {
  this.ID.Resize();
  this.ID.Draw();
}

function ThumbnailPageJumpToPage(page_idx, image_desc_idx, completed_callback) {
  var TP = this;

  var event = TP.CurEvent;
  var page_overview = event.PageOverviews[page_idx];

  var event_key = event.AccessId;
  if (event.Password != null) event_key += '-' + unescape(event.Password);
  var range =
    (page_overview.StartSeq - event.StartSeq) + '-' +
    (page_overview.StartSeq + page_overview.ImageCount - event.StartSeq - 1);
  var cgi_desc_sets = [event_key, range, event.StartSeq].join('_');

  $('body').data('page_loader').load_page_overviews(
    event,
    function() {
      $('body').css('cursor', 'auto');
      TP.CurPage = page_overview;
      var image_desc_loader = $('body').data('image_desc_loader');
      var cur_key = 'P'+TP.CurPage.PageId;
      image_desc_loader.set_cur_key(cur_key);
      image_desc_loader.get_desc_set(
	cgi_desc_sets,
	cur_key,
	null,
	'main-'+event.Index+'-'+page_idx,
	function(key, image_descs) {
	  var image_desc;
	  if (image_desc_idx == null) {
	    image_desc = image_descs[0];
	  }
	  else {
	    image_desc = image_descs[image_desc_idx - TP.CurPage.StartSeq];
	  }
	  TP.ID.UpdateSelectedImageDesc(image_desc);
	  TP.UpdateCookie({ cur_ivid: image_desc.FavoriteId });
	  TP.ImageDescsLoaded(key, image_descs, completed_callback);
	  TP.ID.UpdatePageLinks();
	  TP.ID.UpdateMenu(event.Index, page_idx);
	},
	function() { }
      );
    },
    function() { }
  );
}

function ThumbnailPageNextThumbs() {
  var TP = this;
  this.JumpToPage(TP.CurPage.Index + 1);
}

function ThumbnailPagePrevThumbs() {
  var TP = this;
  this.JumpToPage(TP.CurPage.Index - 1);
}


function TPUpdateFMs() {
  var TP = this;
  if (this.FMs.length == 0) {
    this.FMs['main'] = new FolderManager;
    this.FMs['main'].Init(this.EL.ImageCount);
    this.FMs['main'].Tag = 'main';

    this.FMs['favorites'] = new FolderManager;
    this.FMs['favorites'].Init();
    this.FMs['favorites'].Tag = 'favorites';
  }
  else {
    this.FMs['main'].NumMembers = this.EL.ImageCount;
  }
}

function TPUpdateView(password, cur_tp_image_id) {
  var pro_access_id = TP.GetCookieVal('pro_access_id');
  var event_access_id = TP.GetCookieVal('event_access_id');
  var num_events_visible = TP.EL.Events.length;

  var default_landing_page;
  if (pro_access_id != null) {
    this.BreadcrumbContext = "GAL";
  }
  else if (num_events_visible == 0) {
    this.BreadcrumbContext = "(ERR)";
  }
  else if (num_events_visible == 1) {
    this.BreadcrumbContext = "PLIST";
  }
  else {
    this.BreadcrumbContext = "ELIST";
  }

  var u = TP.GetCookieVal('u');
  var deep_link = ((u != null) && (u & 16) != 0 && (u & 8) != 0) ? true : false;
  if (pro_access_id != null && ! deep_link) {
    default_landing_page = "GAL";
  }
  else if (deep_link) {
    default_landing_page = "PLIST";
  }
  else {
    default_landing_page = "ELIST";
  }

  this.UpdateBreadcrumbs();


  var cur_page = TP.GetCookieVal('cur_page', '[A-Z]');
  if (cur_page == null) cur_page = default_landing_page;
  this.CurMode = cur_page;


  var esn_e_idx, e_idx;
  if (cur_tp_image_id == null) {
    if (
        this.CurMode == "PLIST" ||
        this.CurMode == "THUMB" ||
        this.CurMode == "POPUP"
    ) this.CurMode = default_landing_page;
    for (i = 0; i < TP.EL.Events.length; i++) {
      var event = TP.EL.Events[i];
      if (event.PageOverviews != null) {
	cur_tp_image_id = event.StartSeq;
	break;
      }
    }
  }
  else {
    esn_e_idx = TP.EL.TPImageIdToEventI(cur_tp_image_id);
  }
  e_idx = TP.EL.TPImageIdToEventI(cur_tp_image_id);

  if (
    TP.EL.Events[e_idx].Locked && (
      this.CurMode == "PLIST" ||
      this.CurMode == "THUMB" ||
      this.CurMode == "POPUP"
    )
  ) this.CurMode = default_landing_page;

  if (
    (this.BreadcrumbContext == "GAL" || this.BreadcrumbContext == "SRCH") &&
    this.CurMode == "ELIST"
  ) {
    this.CurMode = default_landing_page;
  }

  if (
    this.BreadcrumbContext == "ELIST" &&
    (this.CurMode == "GAL" || this.CurMode == "SRCH")
  ) this.CurMode = default_landing_page;

  if (
    this.BreadcrumbContext == "PLIST" &&
    (this.CurMode == "GAL" || this.CurMode == "SRCH" || this.CurMode == "ELIST")
  ) this.CurMode = default_landing_page;

  if (this.CurMode == "SRCH") this.BreadcrumbContext = "SRCH";

  TP.UpdateBreadcrumbs();


  if (this.CurMode == "GAL") {
    TP.DrawEventSetNav(null, null);
    TP.ViewEventSetNav("GAL");
    TP.DrawThumbsBackground(0, 4);
  }
  if (this.CurMode == "SRCH") {
    TP.DrawEventSetNav(null, password);
    TP.ViewEventSetNav("SRCH");
    TP.DrawThumbsBackground(0, 4);
  }
  if (this.CurMode == "ELIST") {
    TP.DrawEventSetNav(null, null);
    TP.ViewEventSetNav("ELIST");
    TP.DrawThumbsBackground(0, 4);
  }
  if (this.CurMode == "(ERR)") {
    TP.ShowErrorDialog("HOME");
    return null;
  }

  if (e_idx != null) {
    var event = TP.EL.Events[e_idx];
    if (event != null && ! event.Locked && ! event.Loaded) {

      var post_load_callback;
      if (this.CurMode == "PLIST") {
        post_load_callback = function() {
          TP.DrawPageListing(event);
          TP.ViewPageListing();
          TP.DrawThumbsBackground(0, 4);
        };
      }
      if (this.CurMode == "THUMB") {
        post_load_callback = function() {
	  TP.CurEvent = event;
	  for (var i = 0; i < event.PageOverviews.length; i++) {
	    if (
	      i == TP.CurEvent.PageOverviews.length - 1 ||
	      TP.CurEvent.PageOverviews[i + 1].StartSeq > cur_tp_image_id
	    ) {
	      TP.CurPage = TP.CurEvent.PageOverviews[i];
	      break;
	    }
	  }
          TP.DrawPageListing(TP.CurEvent);
          TP.DrawThumbs();
          TP.ViewThumbs();
        };
      }
      if (this.CurMode == "POPUP") {
        post_load_callback = function() {
          TP.DrawImagePopup(cur_tp_image_id);
          TP.ViewImagePopup();
        };
      }

      if (post_load_callback != null) {
        $('body').css('cursor', 'wait');
        $('body').data('page_loader').load_page_overviews(
          event,
          function() {
            $('body').css('cursor', 'auto');
            post_load_callback();
          },
          function() {
            $('body').css('cursor', 'auto');
	    var contact_the_photographer;
	    if (TP.ProEmail != "")
	      contact_the_photographer = '<a href="mailto:'+TP.ProEmail+'" style="color:#6974b6;"><b>contact the photographer</b></a>.';
	    else
	      contact_the_photographer = 'contact the photographer.';
            jAlert('Error loading event information.  Please try again later, or '+contact_the_photographer+'.');
          }
        );
      }
    }
  }

}

function TPDrawThumbsBackground(first_i, last_i) {
  if (first_i >= 100) { return; }
  var TP = this;
  TP.ID.FrameThumbs(first_i, last_i);
  TP.ID.FillThumbs(first_i, last_i);
  setTimeout(
    function() { TP.DrawThumbsBackground(first_i + 5, last_i + 5) },
    100
  );
}

ThumbnailPage.prototype.ImageDescsLoaded = function(key, image_descs, post_load_callback) {
  var TP = this;

  if (key == 'P'+TP.CurPage.PageId) {
    if (image_descs.length > 100)
      image_descs.splice(100, image_descs.length - 100);
    TP.ID.PageImageDescs = image_descs;
    if (post_load_callback != null) post_load_callback();
    TP.ID.FillThumbs();
  }
}

function ThumbnailPageToggledFavoriteness() {
}

function TPUpdateCurEvent(event) {
  var TP = this;
  TP.UpdateCookie({ event_access_id: event.AccessId });
  TP.CurEvent = event;
}

function TPUpdateCookie(args) {
  var TP = this;
  if (TP.Cookie == null) return;

  for (var key in args) {
    var val = args[key];

    var exists_re = new RegExp(key+"&[A-Za-z0-9 ]+");
    var undef_re = new RegExp(key+"&undefined");
    if (this.Cookie.match(/Cart=;/)) {
      this.Cookie = this.Cookie.replace(/Cart=;/, "Cart="+key+"&"+val+";");
    }
    else if (this.Cookie.match(exists_re)) {
      this.Cookie = this.Cookie.replace(exists_re, key+"&"+val);
    }
    else if (this.Cookie.match(undef_re)) {
      this.Cookie = this.Cookie.replace(undef_re, key+"&"+val);
    }
    else {			      
      var re = new RegExp('Cart=(.*?);');
      this.Cookie = this.Cookie.replace(re, "Cart=$1&"+key+"&"+val+";");
    }
  }

  document.cookie = this.Cookie;
}

function TPAddHitCookie(event_access_id) {
  var date = new Date();
  date.setTime(date.getTime() + 86400000);
  document.cookie = 'H'+event_access_id+'=v&1; expires='+date.toGMTString()+'; path=/';
}

function TPNotifyHit(event_access_id) {
  if (TP.VisitedEventAccessIds[event_access_id] != null) return;
  TP.VisitedEventAccessIds[event_access_id] = 1;

  $.ajax({
    type: 'POST',
    url: '/ecom/inc_event_hits.pl',
    data: { event_access_ids: event_access_id },
    dataType: 'json',
    success: function(data) {
      if (data.Result == 'Success') {
	TPAddHitCookie(event_access_id);
      }
      else {
	delete TP.VisitedEventAccessIds[event_access_id];
      }
    },
    error: function() {
      delete TP.VisitedEventAccessIds[event_access_id];
    }
  });
}

function TPGetCookieVal(key, pattern) {
  if (pattern == null) pattern = '.';
  var re = new RegExp(key+'&('+pattern+'*?)[;&]');
  var matches = re.exec(this.Cookie);
  if (matches != null && matches.length > 1) return matches[1];
  else return null;
}

function ThumbnailPageOrder() {
  var access_ids = [];
  for (var access_id in this.EL.AccessIdEventI) {
    access_ids.push(access_id);
  }
  $('#event_access_ids').val(access_ids.join(','));
  var order_form = document.getElementById("order_form");
  var FMs = this.FMs;
  for (var i = 0; i < FMs['favorites'].GetNumMembers(); i++) {
    var ivid = FMs['favorites'].GetFIndexIvid(i);
    var input = document.createElement("input");
    input.type = "hidden";
    input.name = "select";
    input.value = ivid;
    order_form.appendChild(input);
  }

  window.onbeforeunload = null;
  order_form.submit();
}

function ThumbnailPageViewCart() {
  if (TP.FMs['favorites'].GetNumMembers() == 0) window.onbeforeunload = null;
  var access_ids = [];
  for (var i in TP.EL.AccessIdEventI) {
    var event_i = TP.EL.AccessIdEventI[i];
    access_ids.push(TP.EL.Events[event_i].AccessId);
  }

  var form = '<form method="post" action="/ecom/product_add.pl">' +
    '<input type="hidden" name="event_access_ids" value="' +
    access_ids.join(',') + '"></input></form>';
  $('#form_div').html(form);
  $('#form_div > form').submit();
  return false;
}

function ThumbnailPageTPImageIdToFolderEPILoc(tp_image_id, folder) {
  if (folder == null) folder = this.CurrentFolderName;
  if (folder == null) return null;

  if (folder == 'main') {
    return this.EL.TPImageIdToEPILoc(tp_image_id);
  }
  if (this.FMs[folder] == undefined) return null;
  var f_idx = this.FMs[folder].GetTPImageIDFIndex(tp_image_id);
  return { EventIndex: 0, PageIndex: 0, ImageIndex: f_idx };
}

function ThumbnailPageFIndexToTPImageId(f_idx, folder) {
  if (folder == null) folder = this.CurrentFolderName;
  if (folder == null) return null;
  if (this.FMs[folder] == undefined) return null;
  return this.FMs[folder].GetFIndexTPImageId(f_idx);
}

function ThumbnailPageMaxFIndex() {
  if (this.CurrentFolderName == null) return null;
  return this.FMs[this.CurrentFolderName].GetNumMembers() - 1;
}

function ThumbnailPageGetEvents(folder) {
  if (folder == null) folder = this.CurrentFolderName;
  if (folder == null) return null;
  if (folder == 'main') {
    return this.EL.Events;
  }
  var num_images = this.FMs[folder].GetNumMembers();
  return [
    {
      Title: 'Favorites',
      ImageCount: num_images,
      StartSeq: 0,
      PageOverviews: [
	{
	  PageId: null,
	  Title: null,
	  ImageCount: num_images,
	  StartSeq: 0
	}
      ]
    }
  ];
}

function ThumbnailPageShare() {
  var event_access_id = TP.GetCookieVal('event_access_id');
  if (event_access_id == null) return;
  var event_idx = TP.EL.AccessIdEventI[event_access_id];  
  var events = TP.GetEvents();
  var event = events[event_idx];
  var subject = encodeURIComponent("You're invited to view my photos from " + event.Title);

  var password = TP.GetCookieVal('password');
  var url = location.protocol + '//' + location.host;
  if (location.port)
    url += ":" + location.port;
  url += '/ecom/g.pl?a=' + event_access_id;

  var body = "I wanted to share these photos from " + event.Title + "\n\n" +
	     "To see the photos copy the following link into your browser:\n\n";

  if (password)
    url += '&p=' + password;

  body = encodeURIComponent(body + url);

  var message = "mailto:?subject=" + subject + "&body=" + body
  document.location.href = message;
  return false;
}
