var _replaceContext = false;
var _mouseOverContext = false;
var _noContext = false;
var global_photo_id = '';
var global_gallery_id = '';
var global_offset_value = '';
var rpp = 4;
var zero_gallery = 0;
var editors_created = new Array();

function ajax_deleteImage() {
  old_gallery_id = global_gallery_id;

  var is_active = 0;
  if (zero_gallery == 1) { 
    global_gallery_id = 0; 
    if (null != $('rows')) { rpp = $('rows').value; }
    if (null != $('is_active')) { is_active = $('is_active').value; }
  }


  if (confirm('Are you sure?') && global_photo_id != '') {
    deleteImage(['photo_id__'   + global_photo_id,
                 'gallery_id__' + global_gallery_id,
                 'rpp__' + rpp, 'offset__' + global_offset_value,
		 'is_active__' + is_active,
                 'display_style', 'NO_CACHE'],
                ['gallery_total_count' + global_gallery_id,
                 'total_inactive_count', 'total_active_count',
		 'photo_total', 'photo_total_link',
                 'thumbblock' + global_gallery_id,
                 'thumbblocknav_bak' + global_gallery_id,
                 'thumbblocknav_fwd' + global_gallery_id]);
  }
  if (_divContext && _divContext.style.display != "none") CloseContext();
  global_gallery_id = old_gallery_id;
}


function getWidth() {
  var x = 0;
  if (self.innerHeight) { x = self.innerWidth; } 
  else if (document.documentElement && document.documentElement.clientHeight) {
    x = document.documentElement.clientWidth;
  } else if (document.body) { x = document.body.clientWidth; }

  return x;
}

function getHeight() {
  var y = 0;
  if (self.innerHeight) { y = self.innerHeight; } 
  else if (document.documentElement && document.documentElement.clientHeight) {
    y = document.documentElement.clientHeight;
  } else if (document.body) { y = document.body.clientHeight; }

  return y;
}

function center_content(theDiv) {
  if (document.getElementById) {
    var windowHeight = getHeight();
    var windowWidth  = getWidth();
    var div_width    = $(theDiv).getWidth();
    var div_height   = $(theDiv).getHeight();
    if ((windowHeight > 0) && (windowWidth > 0)) {
      var contentElement = document.getElementById(theDiv);

      contentElement.style.position = 'absolute';
      contentElement.style.top  = ((windowHeight / 2) - 
                                  (div_height / 2)) + 'px';
      contentElement.style.position = 'absolute';
      contentElement.style.left  = ((windowWidth / 2) - 
                                   (div_width / 2)) + 'px';
    }
  }
}


function drop_content(theDiv) {
  if (document.getElementById) {
    var windowHeight = getHeight();
    var div_height   = $(theDiv).getHeight();
    if (windowHeight > 0) {
      var contentElement = document.getElementById(theDiv);

      if (windowHeight - div_height > 0) {
        contentElement.style.position = 'fixed';
        contentElement.style.top  = (windowHeight-div_height) + 'px';
      } else {
        contentElement.style.position = 'static';
      }
    }
  }
}



function switch_profileTabs(active_tab) {
  $('profile_general').hide();
  $('profile_password').hide();
  $('profile_email').hide();
  $('profile_other').hide();
  $('email_mod_status').innerHTML = '';
  clearStats();
  $(active_tab).show();
}


function admin_deleteGallery(gid) {
  if (confirm('Are you sure?')) {
    arg1 = "search_gallery_id__" + gid;
    arg2 = "gallery" + gid;
    deleteGalleryTable([arg1,'short__1'],['gallery_delete_results',arg2]);
    return true;
  }
}

function admin_deleteImage(pid) {
  if (confirm('Are you sure?')) {
    arg1 = "search_photo_id__" + pid;
    arg2 = "photo" + pid;
    deletePhotoCell([arg1,'short__1'],['photo_delete_results',arg2]);
    return true;
  }
}


function admin_resolveAbuse(rid) {
  if (confirm('Are you sure you want to mark this report resolved?')) {
    arg1 = "search_report_id__" + rid;
    arg2 = "abuse" + rid;
    resolveAbuse([arg1],['abuse_results',arg2]);
    return true;
  }
}


function admin_deleteAd(aid) {
  if (confirm('Are you sure?')) {
    arg1 = "link_id__" + aid;
    arg2 = "link" + aid;
    deleteAd([arg1],['ad_results',arg2]);
    return true;
  }
}


function showFAQ(elementID) {
  if ( $(elementID).visible() )  { $(elementID).hide(); }
  else { $(elementID).show(); }
}

editFAQ = function editFAQ(faqID) {
  if ($('errors') != null) { $('errors').innerHTML = ''; }

  loadFAQ(['faq_id__' + faqID, 'NO_CACHE'],
        ['faq_id', 'message', 'error_message', 'faq_id_display',
         'last_modified', 'question', 'answer']);
  $('faq_edit_popup').appear( {duration: 0.5} );
}


function ajax_setImage(image_state) {
  var url = '/perl-bin/photo_ajax.mp?photo_id=' + 
	     global_photo_id + '&is_active=' + image_state;
  var the_image = $('photo_' + global_photo_id);
  var active_images   = 0;
  var inactive_images = 0;
  var no_counters     = 0;
  if (null != $('total_active_count')) {
    active_images   = parseInt($('total_active_count').innerHTML);
    inactive_images = parseInt($('total_inactive_count').innerHTML);
  } else {
    no_counters = 1;
  }

  new Ajax.Request(url, {
	method: 'get',
	onSuccess: function(transport) {
	  if (transport.responseText.match(/-1/)) {
	    the_image.setOpacity(0.3);
	    if (no_counters == 0) {
	      $('total_active_count').innerHTML   = active_images - 1;
	      $('total_inactive_count').innerHTML = inactive_images + 1;
	    }
	  } else if (transport.responseText.match(/1/)) {
	    the_image.setOpacity(1.0);
	    if (no_counters == 0) {
	      $('total_active_count').innerHTML   = active_images + 1;
	      $('total_inactive_count').innerHTML = inactive_images - 1;
	    }
	  }
	}
    });

  if (_divContext && _divContext.style.display != "none") CloseContext();
}


function ajax_previewImage() {
  if (global_photo_id != '') {
    window.location.href=global_server + '/' + global_user + '/' + 
	global_gallery_id + '/' + global_photo_id;
  }
}


function sendPhotoDiv() {
  if (global_photo_id != '') {
    getPhotoShareDetails(['photo_id__' + global_photo_id, 'NO_CACHE'],
	['send_image_title', 'send_image_preview']);
    $('photoshare_popup_div').appear({ duration: 0.5 });
    center_content('photoshare_popup_div');
  }

  if (_divContext && _divContext.style.display != "none") CloseContext();
}


function generateLinkCode(html_type) {
  if (global_photo_id != '') {
    getLinkDetails(['photo_id__' + global_photo_id, 
	 	    'type__' + html_type, 'NO_CACHE'],
	['what', 'intro', 'link_image_title','link_preview_image', 
	 'link_small_width', 'link_small_height', 'link_small', 
	 'link_medium_width', 'link_medium_height', 'link_medium', 
	 'link_large_width', 'link_large_height', 'link_large', 
	 'link_original_width', 'link_original_height', 'link_original']);
    $('link_popup_div').appear({ duration: 0.5 });
    center_content('link_popup_div');
  }

  if (_divContext && _divContext.style.display != "none") CloseContext();
}


function InitContext() {
  _divContext.onmouseover = function() { 
	_mouseOverContext = true; 
  };
  _divContext.onmouseout = function() { 
	_mouseOverContext = false; 
  }
  document.body.onmousedown = ContextMouseDown;
  document.body.oncontextmenu = ContextShow;
}


function isUnsignedInteger(s) {
  return (s.toString().search(/^[0-9]+$/) == 0);
}


function ContextMouseDown(event) {
  if (_noContext || _mouseOverContext) return;
  if (event == null) event = window.event;

  var the_photo_id = 0;
  var target = event.target != null ? event.target : event.srcElement;

  if ((target != null) && (target.id.substring(0,6) == 'photo_')) { 
    the_photo_id = isUnsignedInteger(target.id.substring(6)) ?
			target.id.substring(6) : 0;  
  }

  if ( (event.button == 2) && (target.id.substring(0,6) == 'photo_') &&
       (the_photo_id > 0)) {
    _replaceContext = true;
  } else if (!_mouseOverContext) {
    _divContext.style.display = 'none';
  }
}


function CloseContext() {
  _mouseOverContext = false;
  _divContext.style.display = 'none';
}


function ContextShow(event) {
  if (_noContext || _mouseOverContext) return;
  if (event == null) event = window.event;
  var target = event.target != null ? event.target : event.srcElement;

  if (_replaceContext) {
    _oldImage    = target.id;
    global_photo_id = _oldImage.substr(6, _oldImage.length-6);
    $('image_title').innerHTML = $(_oldImage).title;
    
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ?
        document.body.scrollLeft : document.documentElement.scrollLeft;

    _divContext.style.display = 'none';
    _divContext.style.left = event.clientX + scrollLeft + 'px';
    _divContext.style.top = event.clientY + scrollTop + 'px';
    _divContext.style.display = 'block';
    _replaceContext = false;
    return false;
  }
}


function opacify(nameOfElement, level) {
  if (_replaceContext) { return; }
  theElement = document.getElementById(nameOfElement);
  theElement.style.opacity = level / 100.0;
  theElement.style.filter  = "progid:DXImageTransform.Alpha(opacity=" + level + ")";
  theElement.style.filter  = "alpha(opacity=" + level + ")";
}


function editNotes(templateName) {
  window.open("/account/notes.mp?template=" + templateName, "note_edit",
	"toolbar=0,location=0,menubar=0,directories=0,resizable=1," +
	"height=400,width=600");
}


function submitMoveForm() {
  var theFormArea = document.getElementById('photoList');
  var boxen = theFormArea.getElementsByTagName("input");
  for (var i = 0; i < boxen.length; i++) {
    if ((boxen[i].getAttribute("type") == "checkbox") &&
        (boxen[i].checked)) {
      document.getElementById("move_photo_id").value =
	document.getElementById("move_photo_id").value +
	boxen[i].value + '||';
    }
  }
  document.getElementById('photo_move').submit();
  return true;
}

function formButtonClick(theForm, theButton, theMessage) {
  theButton.disabled = true;
  theButton.value = theMessage;
  theForm.submit();
  return true;
}

function selectText(nameOfElement) {
  theElement = document.getElementById(nameOfElement);
  theElement.focus();
  theElement.select();
}


function doCheckUncheckAll (formID, state) {
  var theForm = document.getElementById(formID);
  i = 0;
  for (i = 0; i < theForm.length; i++) {
    if (theForm[i].type == 'checkbox') {
      theForm[i].checked = state;
    }
  }
}

function checkForSelected (formID) {
  var theForm = document.getElementById(formID);
  i = 0;
  hasSelections = false;
  while ((i < theForm.length) && !hasSelections) {
    hasSelections = theForm[i].checked;
    i++;
  }

  if (! hasSelections) {
    alert ('No items have been selected.');
    return false;
  } else {
    return true;
  }
}


function operateOnSelected (formID, actionStr) {
  var theForm   = document.getElementById(formID);
  var theAction = document.getElementById('formaction');
  if (checkForSelected(formID)) {
    if (actionStr == 'delete') {
      if (confirm('Are you sure?\nAny photos in these galleries will ' +
	  'also be deleted.') == false) {
        return false;
      }
    }
    theAction.value = actionStr;
    theForm.submit();
    return true;
  } else { 
    return false;
  }
}

create_editors = function(photo_id, prop_type) {
  var ed1;
  var ed2;

  if (editors_created[photo_id] != 1) {
   ed1 = new Ajax.InPlaceEditor('photo_title' + photo_id,
        '/perl-bin/photo_ajax.mp', {
        callback: function(form, value) {
                return 'photo_id=' + photo_id + '&title=' +
                encodeURIComponent(value) },
        cols: 30,
        highlightendcolor: '#FFFFFF',
        cancelControl: 'button',
        okText: 'update',
	externalControlOnly: true,
        externalControl: 'edit_title' + photo_id
    });
  

   ed2 = new Ajax.InPlaceEditor('description' + photo_id,
        '/perl-bin/photo_ajax.mp', {
        callback: function(form, value) {
                return 'photo_id=' + photo_id + '&description=' +
                encodeURIComponent(value) },
        cols: 50,
        rows: 3,
        highlightendcolor: '#FFFFFF',
        cancelControl: 'button',
        okText: 'update',
	externalControlOnly: true,
        externalControl: 'edit_desc' + photo_id
    });

    editors_created[photo_id] = 1;
  }

  if ((prop_type == 'title') && (ed1 != null)) {
    ed1.enterEditMode('click');
  } else if ((prop_type == 'description') && (ed2 != null)) {
    ed2.enterEditMode('click');
  }
};


function update_photo_props(prop_type, photo_id) {
  var url = '/perl-bin/photo_ajax.mp?photo_id=' + 
	     photo_id + '&prop_type=' + prop_type +
	     '&' + prop_type + '=' ;

  $('update' + photo_id).innerHTML = '';
  if (prop_type == 'category_id') {
    url = url + $('category_sel_' + photo_id).value;
  } else {
    url = url + $('gallery_sel_' + photo_id).value;
  }
  new Ajax.Updater('update' + photo_id, url, { method: 'get' });
}
