// This function does the form submit that uploads a photo to a folder.
// Called when file upload element "onchange" event occurs. "window" in this
// code refers to an IFRAME.   The portfolio and its folders are in the parent
// window's document. 
function upload(e) {
  // Hide the old iframe.
  var id = e.id;
  var iframe = window.parent.document.getElementById('iframe' + id);
  iframe.style.visibility = 'hidden';
  iframe.style.width = '0px';
  iframe.style.height = '0px';

  // Create new iframe with a file upload element for next upload.  The reason
  // it is done this way is so that on a slow connection (or with big images) several
  // images can be uploaded at the same time.
  var info = id.split(':');
  var folder = info[0];
  var uploadedImages = info[1];
  var newId = folder + ':' + (++uploadedImages);
  var new_iframe = window.parent.document.createElement('iframe');
  new_iframe.id = 'iframe' + newId;
  new_iframe.src = iframe.src.substr(0,iframe.src.lastIndexOf("id=")-1)+";id="+newId;
  new_iframe.frameBorder = '0';
  new_iframe.scrolling = 'no';
  new_iframe.width = '230px';
  window.parent.document.getElementById('iframeDiv'+folder).appendChild(new_iframe);

  // Create a new img in the folder to hold the results of this upload.
  // This image is the child of a new anchor, which will be linked
  // to the large version of the image when the upload is completed successfully.
  var imgcontainer = window.parent.document.createElement('div');
  imgcontainer.className = "imagecontainer";
  imgcontainer.id = "uploadedImage"+id;
  var image = window.parent.document.createElement('img');
  image.className = "loading";
  image.src = "assets/snippets/shoebox/images/loading_ani.gif";
  imgcontainer.appendChild(image);
  var folder = window.parent.document.getElementById(folder);
  folder.insertBefore(imgcontainer, folder.childNodes.item(0));

  // Submit the form.
  document.iform.imgnum.value = id;
  document.iform.submit();
}

// Deletes an image.
var ID_SETTYPE_CIRCLE = 2;

// send an AJAX request to delete this photo after confirming the user really wanted to
function deletePhoto( photoid, setidtype, setid ) {
  var imgContainer = document.getElementById(photoid);
  var photo = imgContainer.getElementsByTagName('img')[0];

  var confirm_msg;
  if (setidtype == ID_SETTYPE_CIRCLE) {
    confirm_msg = "Removing this photo ("+photo.title+") will remove";
    confirm_msg += "\n it from this critique circle only. Your photo will remain in your folder";
    confirm_msg += " and all comments associated with it will remain as well.";
    confirm_msg += "\nPlease confirm the removal of this photo from this critiq circle.";
  }
  else {
    confirm_msg = "Deleting this photo ("+photo.title+") will remove";
    confirm_msg += "\n it from your portfolio.";
    confirm_msg += "\nPlease confirm the deletion of the photo.";
  }

  if (confirm(confirm_msg)) {
    var req = new Ajax.Request('/async',{  
        method: 'get',
        parameters: "cmd=deletePhoto;photoid="+photoid+";setidtype="+setidtype+";setid="+setid,
        onComplete: function (req) { 
	    if (req.responseText.indexOf("success") > 0) {
                new Effect.Shrink(imgContainer);
                setTimeout(function() {
                    imgContainer.parentNode.removeChild(imgContainer); 
                    delete imgContainer;
		    initLightbox(window, null, setid, null, null);
                }, 1000);
            } else {
                var message = req.responseXML.getElementsByTagName('message').item(0);
                alert ("Problem deleting photo: " + message.textContent);
            }
        }
    });
  }
}

// submit the replace photo input
function replacePhoto() {
  document.infoform.submit();
  return;
}

// Updates a field of the photo information
function changePhotoInfo(field, photoid) {
    new Ajax.Request('/async',{
        method: 'get',
        parameters: "cmd=changePhotoInfo;photoid="+photoid
                    +";field="+field.id+";value="+escape(field.value),
			 onComplete: function (req) {
                      	  if ((field.id == 'phototitle') && $('photo'+photoid)) {
                 	     $('photo'+photoid).title = field.value;
			     lightbox_image_anchors[currentItem].title = field.value;
			   }
		         }
    });
}

// adds this photographer to this user's watch list
function watchPhotographer(watch, me, photographer) {

  cmd = (watch) ? 'addwatch' : 'removewatch';
  
  new Ajax.Request('/async',{
    method: 'get',
	parameters: "cmd="+cmd+";u="+me+";photographer="+photographer,
	onComplete: function (req) {
	$('watch').toggle();
	$('watching').toggle();
      }
    });
}

// toggle the description field being shown or hidden
function showDescription() { 
  if ($('setdesc').style.display == 'block') {
    $('setdesc').style.display = 'none';
    $('setdescanchor').title = $('setdescanchor').title.replace("Hide", "Show");
  }
  else {
    $('setdesc').style.display = 'block';
    $('setdescription').style.visibility = 'hidden';
    setTimeout(adjustTextarea, 10);
  }
}

// set the scroll and overflow 
function adjustTextarea() {
  if (!window.opera) { // opera scrollHeight doesn't work anyway
    $('setdescription').style.height = $('setdescription').scrollHeight + 'px';
    $('setdescription').style.overflow = 'hidden';
  }
  $('setdescription').style.visibility = 'visible';
}

// response from the AJAX reqest for description text being edited
function descEdited(transport, element) {
  if (transport) {
    var desc = transport.responseText.stripTags();
    if ((desc.indexOf('success') == 0) && desc.length < 10)
      desc = '';

    $(element).value = desc;

    $('setdesc').style.display = 'none';
  }
} 

var descriptionEditor = null;

// send an AJAX request to edit the description (triggered by a focus change)
function editDescription(setid) {

  showDescription();

  var nrows = $('setdescription').scrollHeight / 20;
  nrows = (nrows < 5) ? 5 : nrows;
  if (descriptionEditor == null) {
    var preventCaching = ';rdn=' + Math.round(Math.random() * 100);
    descriptionEditor = new Ajax.InPlaceEditor('setdescription', '/async?cmd=setdescription;setid=' + setid + preventCaching, 
					       {rows: nrows, cols:80,
						   onComplete: function(transport, element) {descEdited(transport, element);} });
  }
  descriptionEditor.enterEditMode('click');
}

var objTooltip = null;

// Pops up a tooltip.
function tooltip(element) {
    if (objTooltip == null) {
        objTooltip = document.createElement('div');
        objTooltip.style.visibility = "hidden";
            objTooltip.className="tooltip"; 
        element.appendChild(objTooltip);
	switch(element.id) {
        case "tooltip_circleNew":
	   tip = '<p>'
	         +' Enter multiple circles by separating them with a comma or semicolon. <p>'
	         +' The drop down list shows again after typing a comma or semicolon and typing the first. '
   	         +' letter of the next circle name. <p>'
	         +' Select from the drop down list by clicking or hitting tab to complete. <p>'
	         +' Click the "+" button to add the photo to the circle(s) ';
	   break;	
        case "tooltip_circle":
	   tip = '<p>To add the photo to CritiQ Circle(s), enter the names of the Circles.'
                 +' It can be an existing CritiQ Circle or a new one.  If there'
                 +' is no circle already by that name, you will be creating'
                 +' a new Critiq Circle. You can create as many CritiQ Circles '
                 +' as you want.</p>Type the first letter and a list will appear of existing circles. '
      	         +' Select from this list (click or tab) or type a new name. '
	         +' <p><br>Click the "+" button to add the photo to the circle(s). '
	         +' <p>Enter multiple circles by separating them with a comma or semicolon.';
	   break;	
        case "tooltip_circleremove":
	   tip = '<p>To remove the photo from a CritiQ Circle, enter the '
                 +' name of the circle. Typing the first letter will bring up a list ' 
                 +' of all CritiQ Circles this photo is currently in. Select one of these '
	         +' names and then click the "-" button to remove this photo from the specified '
	         +' circle.</p>';
	   break;	
        case "tooltip_replace":
	   tip = '<p>Select a new photo (file on your computer)'
   	         +' to replace this current photo, maintaining all comments etc.</p>';
	   break;	
        }
       	objTooltip.innerHTML = tip;
        objTooltip.style.visibility = "visible";
    } else {
        objTooltip.style.visibility = "hidden";
        element.removeChild(objTooltip);
        delete objTooltip;
        objTooltip = null;
    }
    return false;
}    


// move a photo to a different folder (set)
function movePhoto( photoid, oldsetid, setid ) {
  var imgContainer = document.getElementById(photoid);
  var req = new Ajax.Request('/async',{  
      method: 'get',
      parameters: "cmd=movePhoto&photoid="+photoid+"&oldsetid="+oldsetid+"&setid="+setid,
      onComplete: function (req) { 
         if (req.responseText.indexOf("success") > 0) {
              new Effect.DropOut(imgContainer);
              setTimeout(function() {
                  imgContainer.parentNode.removeChild(imgContainer); 
                  delete imgContainer 
              }, 1000);
          } else {
              var message = req.responseXML.getElementsByTagName('message').item(0).textContent;
	      if (message == undefined)
		message = req.responseXML.getElementsByTagName('message').item(0).text;
              alert ("Problem moving photo: " + message);
          }
      }
  });
}

// This is called back from the Ajax completion routine to toggle the
// state of the "favorite" star.
function setStar(e) {
  var dir = "/assets/snippets/shoebox/images/";	
  var star = e.descendants()[0];

  if (star.alt == "not favorite") {
    star.alt = "favorite";
    star.src = dir+"star.gif";
    star.title = stxt[8];
  }
  else {
    star.alt="not favorite";
    star.src=dir+"nostar.gif";
    star.title = stxt[9];
  }
}

// This is the onclick handler for the interesting star icon.  Clicking
// the icon toggles the "interestingness" state of the photo for the current
// user.
function toggleInteresting(e, photoid) {
  if ((photoid==undefined || photoid == 0) 
      && currentItem != undefined 
      && currentItem >= 0 
      && lightbox_image_anchors != undefined
      && lightbox_image_anchors[currentItem] != undefined )
    photoid = lightbox_image_anchors[currentItem].photoid;
    
  if (photoid != 0) {
    var preventCaching = ';rdn=' + Math.round(Math.random() * 100);
      new Ajax.Request('/async',{  
          method: 'get',
	   parameters: "cmd=toggleInteresting;photoid="+photoid+preventCaching,
           onComplete: function (req) {
	     setStar($("starAnchor"+photoid));
	     // if not the star associated with the thumbnail, must be in lightbox mode, 
	     // set this star as well
   	     if (e.id != "starAnchor"+photoid)
	       setStar($('favoriteButtonAnchor'));
          }
      });
  }
}

// add onmouseover and onmouseout to any non-anchor that requires a :hover as 
// IE < 7 doesn't support :hover on anything but anchors. getAttribute('className') 
// is IE specific so other browsers will not match and therefore not add these 
// onmouseover and onmouseout events.
function provideIEhover(doc) {

  var uls = doc.getElementsByTagName("UL");
  for (var i=0; i < uls.length; i++) {
    if ((uls.item(i).getAttribute('className') == 'movePhoto') ||
	(uls.item(i).getAttribute('className') == 'moveShort')) {
      var lis = uls.item(i).getElementsByTagName("LI");
      for (var j=0; j < lis.length; j++) {
	var li =lis.item(j);
	li.onmouseover=function() {
	  this.className += " ieHover";
	}
	li.onmouseout=function() {
	  this.className = this.className.replace(new RegExp(" ieHover\\b"), "");
	}
      }
    }
  }

  // set up the imageContainer hover class
  var containers = doc.getElementsByTagName("div");
  for (var i=0; i < containers.length; i++) {
    if (containers.item(i).getAttribute('className') == 'imagecontainer') {
      var container = containers.item(i);
      container.onmouseover=function() {
	this.className += " ieContainerHover";
      }
      container.onmouseout=function() {
	this.className = this.className.replace(new RegExp(" ieContainerHover\\b"), "");
      }
    }
    else if (containers.item(i).getAttribute('className') == "imagecontainerSmall largebox"){
      var container = containers.item(i);
      container.onmouseover=function() {
	this.className += " largeboxIE";
      }
      container.onmouseout=function() {
	this.className = this.className.replace(new RegExp(" largeboxIE\\b"), "");
      }
    }
    else if ((containers.item(i).getAttribute('className') == "imagecontainerSmall") ||
	     (containers.item(i).getAttribute('className') == "imagecontainerSmall imagecontainerSmaller")){
      var container = containers.item(i);
      container.onmouseover=function() {
	this.className += " ieContainerSmallHover";
      }
      container.onmouseout=function() {
	this.className = this.className.replace(new RegExp(" ieContainerSmallHover\\b"), "");
      }
    }
    else if (containers.item(i).getAttribute('className') == 'foldercontainer') {
      var container = containers.item(i);
      container.onmouseover=function() {
	this.className += " iefoldercontainerHover";
      }
      container.onmouseout=function() {
	this.className = this.className.replace(new RegExp(" iefoldercontainerHover\\b"), "");
      }
    }
  }
}


// Called from photo information display when user clicks 
// the "Put in Circle" button.
function addPhotoToCircle(element, photoid) {
  var elem = document.getElementById(element);
  var circle = elem.value.toLowerCase();
  var matches = circle.match('^ *([a-z0-9\ \\\'\\-\\,\\;]+) *$');
  if (!matches) {
    alert("Only letters, digits, spaces, and the following punctuation characters, please: ' (quote) - (dash). Use a comma or semicolon to separate circle names");
    return;
  }
  circle = matches[1];
  circle = circle.replace(new RegExp(' *[,|;] *', "g" ),',');
  circle = circle.replace(new RegExp(',$'),'');
  circle_escaped=escape(circle);

  var preventCaching = ';rdn=' + Math.round(Math.random() * 100);

  new Ajax.Request('/async',{
    method: 'get',
    parameters: "cmd=addPhotoToCircle;photoid="+photoid+";circle="+circle_escaped+preventCaching,
    onComplete: function (req) { 
      var currentCircles=document.getElementById('currentcircles');
      circlenames = circle.split(',');
      for (var k = 0; k < circlenames.length; k++) {
	// check to see if it already was in this circle
	var matches = currentCircles.innerHTML.match('>'+circlenames[k].replace('\'',"\\'")+'<');
	if (!matches) 
	  currentCircles.innerHTML += ' <a href="/set?circle='+escape(circlenames[k])+'">'+circlenames[k]+"</a>";
      }
      elem.value = '';
    }
  });
}

// send an AJAX request to remove this photo from the circle
function removePhotoFromCircle(element, photoid) {
  var elem = document.getElementById(element);
  var circle = elem.value.toLowerCase();
  var matches = circle.match('^ *([a-z0-9\ \'\-]+) *$');
  if (!matches) {
    alert("Only letters, digits, spaces, and the following punctuation characters, please: '-/");
    return;
  }
  circle = matches[1];
  circle_escaped=escape(circle);
  new Ajax.Request('/async',{
    method: 'get',
    parameters: "cmd=removeFromCircle;photoid="+photoid+";circle="+circle_escaped,
    onComplete: function (req) { 
      var currentCircles=document.getElementById('currentcircles');
      if (circle.indexOf(' ') != -1)
	circle = '"'+circle+'"';
      circle = circle.replace(new RegExp('"', "g" ),'');

      var current = currentCircles.innerHTML;
      var hostn = '';
      var matches = current.match('.*http://(.{3})\\.photocritiq\\.com.*');
      if (matches) 
	hostn = "http:\\/\\/"+matches[1]+"\\.photocritiq\\.com";

      var removeCircle = new RegExp("<A href=\\\""+hostn+"/set\\?setid=[0-9]*\\\">"+circle+"</A>", 'i');
      var current = currentCircles.innerHTML.replace(removeCircle, '');
      
      // now check to see if this was just recently added, so has different format
      removeCircle = new RegExp(" <a href=\\\""+hostn+"/set\\?circle="+circle_escaped+"\\\">"+circle+"</a>",'i');
      currentCircles.innerHTML = current.replace(removeCircle, '');
      elem.value = '';
    }
  });
}

function getDimensions() {
  var dimensions = Element.getDimensions('inner_content');
  var width = dimensions.width;
  var height = dimensions.height;
}

// initialize the drop down list of gallery views
function initGallery(gviews, title, fetching) {

  new Ajax.Autocompleter('searchGalleries','searchCompletions','/async?cmd=listGalleries', 
			 {afterUpdateElement: function(i, value) {saveSelection(i, value);}} );
  new Ajax.InPlaceCollectionEditor( "viewSelector", "/async?cmd=ping", 
				    { collection: [['viewcounts0', gviews['viewcounts0']],
						   ['viewcountssm', gviews['viewcountssm']],
						   ['viewcountslg', gviews['viewcountslg']],
						   ['discussions', gviews['discussions']],
						   ['interesting', gviews['interesting']],
						   ['recent uploads', gviews['recent uploads']]], 
					clickToEditText: title, 
					savingText: fetching, 
					highlightcolor: '#CAB88E', 
					highlightendcolor: '#DDDDCC',
					callback: function(form, value) {switchViews(form, value);} } );

}

// initialize the drop down list of critique circle views
function initCritiqueCircles() {

  new Ajax.Autocompleter('searchGalleries','searchCompletions','/async?cmd=listCritiqueCircles', 
			 {afterUpdateElement: function(i, value) {saveSelectionCircles(i, value);}} );
  if (0) {
  new Ajax.InPlaceCollectionEditor( "viewSelector", "/async?cmd=ping", 
				    { collection: [['recent discussions','Critique Circles - with recent submits']], 
					clickToEditText: 'Click to select a different view', 
					savingText: 'Fetching new photos...',
					highlightcolor: '#CAB88E', 
					highlightendcolor: '#DDDDCC',
					callback: function(form, value) {switchViewsCircles(form, value);} } );
  }
}

// switch to the view indicated by the drop down 
function switchViews(form, value) {
  var href = "/galleries?view=" + value;
  window.open (href, '_parent');
}

var selectedUser = 0;
function saveSelection(i, value) {
  var matches = value.innerHTML.match(">([0-9]*)<");
  if (matches) {
    selectedUser = matches[1];
    var href = "/folders?userid=" +selectedUser;
    window.open (href, '_parent');
  }
}

function switchViewsCircles(form, value) {
  var viewType = 'recent';
  var href = "/groups/index.php?board=6.0";
  window.open (href, '_parent');
}

function saveSelectionCircles(i, value) {
  var matches = value.innerHTML.match(">([0-9]*)<");
  if (matches) {
    selectedBoard = matches[1];
    var href = "/groups/index.php?board="+selectedBoard+".0";
    window.open (href, '_parent');
  }
}

function gotoGallery(element) {
  var elem = $(element);

  var href = "/folders?userid=" +selectedUser;
  window.open (href, '_parent');
}

var scrollListStart = 0;

// request a list of gallery names
function getGalleryList(name) {
  new Ajax.Request('/async',{
    method: 'get',
    parameters: "cmd=listActiveGalleries",
    onComplete: function (req) {
       $('galleryList').innerHTML = req.responseText.substr(44, req.responseText.length);
       showMoreClouds(-32);
       showGalleryList(name);
       // set the height to this first filled in height, it was auto initially
       $('galleryList').style.height = Element.getHeight('galleryList') + "px";
    }
    });
}

// request list of names and insert a div moving the gallery over to make room to show this list
function showGalleryList(name) {
  if ($('galleryList').innerHTML == '') {
    getGalleryList(name);
    return;
  }
  if ($('leftColumn').style.display == "block") {
    $('leftColumn').style.display = "none";
    $('galleryMain').style.marginLeft = "0px";
    $('folders').style.borderLeft = "none";
    $('showList').innerHTML = '<a href="javascript:showGalleryList(\''+name+'\');" title="'+showbtntitle+'">'+showbtn+'</a>';
    //   $('showList').style.borderRight = "none";
  }
  else {
    $('leftColumn').style.display = "block";
    $('galleryMain').style.marginLeft = "176px";
    $('folders').style.borderLeft = "solid #bb7700 1px";
    $('showList').innerHTML = '<a href="javascript:showGalleryList(\''+name+'\');" title="'+hidebtntitle+'">'+hidebtn+'</a>';

    // Critique circles are currently initialized without ajax so must set height here
    if ($('galleryList').style.height == '') 
      $('galleryList').style.height = Element.getHeight('galleryList') + "px";

    //    $('showList').style.borderRight = "solid #bb7700 1px";
  }
}

// show the next page of the list of galleries
function showMoreClouds(maxClouds) {

  var clouds = $('glist').getElementsByTagName("li");

  scrollListStart += maxClouds;
  if (scrollListStart < 0) scrollListStart = 0;
  if (maxClouds < 0) maxClouds = Math.abs(maxClouds);

  for (var i=0; i < clouds.length; i++) {
    if ((i < scrollListStart) || (i > (scrollListStart + maxClouds))) 
      clouds.item(i).className = "hideCloud";
    else 
      clouds.item(i).className = "showCloud";
  }
  $('pageUp').style.visibility = (scrollListStart > 0) ? "visible" : "hidden";
  $('pageDown').style.visibility = ((scrollListStart + maxClouds) < clouds.length) ? "visible" : "hidden";
}

var doingresize = false;

function homepageResize() {
  if (!doingresize) {
    doingresize = true;
    centerGallery();
    doingresize = true;
  }
}

// display a special div in the middle of the home page with a special message (from homepage.php)

function displaySpecial(whichone, resize) {
  var t = $('103');  // home page always has set 103
  var Scontainer = 'specialContainer';
  var special = document.getElementById(Scontainer);

  if (t != undefined) {
    var imgs = t.getElementsByClassName("imagecontainerSmall");
    numInRow = 0;
    var secondRow = 0;
    var firstRow = imgs[0].offsetTop;
    for (var i=0; i < imgs.length; i++) {
      if (imgs[i].offsetTop > firstRow) {
	secondRow = imgs[i].offsetTop;
	break;
      }
      else numInRow++;
    }
    // set a cookie to the number of pictures in a row on this viewers browser
    // this is for the home page to know how many photos were displayed for this user as the area is clipped
    // to display a proper grid
    var date = new Date();
    var days = 1;
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = 'pqimgsrow='+numInRow+expires+"; path=/";

    if (doingresize) return;

    var numRows = 5;
    // reset the anchors based on how many are displayed (assuming 5 rows)
    var numInPage = numInRow * numRows;
    
    // decrease rows if not enough images
    while (numInPage > imgs.length) {
      numRows -= 1;
      numInPage = numInRow * numRows;
    }

    initAnchors(window, '103', '', (numInPage + 1), '');
    
    // if dislaying special container
    if (whichone == 'special') {
      var numRemoved = 2;
      numInPage -= numRemoved;
      var w = Math.round((numInRow / numRemoved) - 1);
      for (var i=0; i < imgs.length; i++) {
	if (imgs[i].offsetTop >= secondRow) {
	  if (w-- == 0) {
	    t.insertBefore($(Scontainer), $(imgs[i]));
	    break;
	  }
	}
      }    
      for (var i= imgs.length - 1; numRemoved-- > 0; i--) 
	  t.removeChild(imgs[i]);

      $(Scontainer).style.display = 'block';
      $(Scontainer).style.visibility = 'visible';
      $('topmenu').style.top = '10px';
    }

    while (imgs.length > numInPage)
      t.removeChild(imgs[imgs.length-1]);

    if ((jumpNextPhoto) && (lightbox_image_anchors.length > numInPage)) {
      jumpNextPhoto = '/index.php?photoid=' + lightbox_image_anchors[numInPage].photoid;
      lightbox_image_anchors.length = numInPage;
    }
  }
}

// toggle photo info display
function hideQuickPhotoInfo(photoid) {
  var id = "photodescription" + photoid;

  if ($(id)) 
    $(id).style.display = 'none';
}

// toggle photo info display
function showQuickPhotoInfo(photoid) {

  var id = "photodescription" + photoid;
  var pageWidth = $('folders').offsetWidth / 2;
  var offset = ($("" + photoid).offsetLeft < pageWidth) ? $("" + photoid).offsetWidth - 10 : 0 - 300 + 10;

  if ($(id)) {
    $(id).style.left = ($("" + photoid).offsetLeft + offset) + 'px';
    $(id).style.top = $("" + photoid).offsetTop + 'px';
    $(id).style.display = 'block';
  }
}
