var currentSnapshotFilter = "recent";

// This is the *total* width of a snapshot--the image, plus its padding (on both sides).
var snapshotWidth = 120;

// Size of padding on either side of a snapshot
var snapshotPaddingWidth = 15;

// padding between the left/right arrow and the snapshot viewport
var arrowPadding = 5;

var isSnapshotDialogVisible = false;

var page = 1;
var old_page = page;

var per_page = 20;

var jsonSnapshots = {"count": 0, "items":[]};

// get the auth key out of the query string (if any)
//var auth_key = $.jqURL.get('auth');

/*
if (url_str) {
  if (url_str.lastIndexOf('/') != url_str.length-1) {
    url_str = url_str + '/';
  }
} else {
  url_str = "http://api.gigapan.org/beta/";
}
*/
     
// set up the defaults for all AJAX calls made with jQuery
$.ajaxSetup({
   url: url_str + 'rpc.php',
   type: 'POST',
   dataType: 'html'
});

// The snapshots in the current filter as javsacript objects. Index by ID.
//var jsonSnapshots = null;

function onPageLoad() {
  onPageResize(); 
}

function onPageLoadAfterFlashBrowserLoad() {
  snapshotFilter(currentSnapshotFilter, "showSnapshot(snapshot_id);");
}

// FIXME: do in CSS
function onPageResize() {
  var viewportWrapper = document.getElementById("viewport_wrapper");
  var description = document.getElementById("main_viewer_snapshots_description");
  var viewport = document.getElementById("main_viewer_snapshots_viewport");
  var moveLeft = document.getElementById("move_left");
  var moveRight = document.getElementById("move_right");

  // resize filmstrip wrapper to fit screen size
  if(viewportWrapper && description)
  {
    viewportWrapper.style.width = (document.body.clientWidth - description.clientWidth) + "px";
    var viewportWrapperWidth = parseInt(viewportWrapper.style.width);

    if (viewport && moveLeft && moveRight)
    {
      var moveLeftWidth = parseInt(moveLeft.clientWidth);
      var moveRightWidth = parseInt(moveRight.clientWidth);
      viewport.style.width = (viewportWrapperWidth - moveLeftWidth - moveRightWidth - (2 * arrowPadding)) + "px";
      viewport.style.left = (moveLeftWidth + arrowPadding) + "px";
    }

    updateDisplayStatus();
  }
}



function notifyFlashAboutUser(userid) {
   document.getElementById('flash_viewer').userIsLoggedIn(userid);
   updateDisplayStatus();
}

function loginViaFlashBrowser() {
   document.getElementById('flash_viewer').startLogin();
}

var _snapshotFilter_complete_js = null;
function snapshotFilter_process() {

if (!auth_key)
   {
   uid = gigapan_id;
   }
else {
  uid = auth_key;
}

  //alert('snapshotFilter_process()');
  var adict = {
    'recent': 'most_recent',
    'popular': 'most_popular',
    'creator': 'by_owners',
    'author': 'by_gigapan_owner',
    'self': 'by_current_user'
  };

  if (currentSnapshotFilter == 'author' || currentSnapshotFilter == 'self') {
    if (currentSnapshotFilter == 'author') {
      username = gigapanAuthor;
    } else { 
      username = currentUsername;
     
    }
    api_url = url_str + "gigapans/"+uid+"/snapshots/page/"+page+"/per_page/"+per_page+"/by_owner/"+username+".json?callback=?";
  } else {
    api_url = url_str + "gigapans/"+uid+"/snapshots/page/"+page+"/per_page/"+per_page+"/"+adict[currentSnapshotFilter]+".json?callback=?";
  }
  
  $.getJSON(api_url,
    function(data) {
      jsonSnapshots.count += data.count;
      //jsonSnapshots.items.data.items;
      
      jsonSnapshots.available = data.available;
      if (jsonSnapshots.items.length == 0) {
        jsonSnapshots.items = data.items;
      } else {
        jsonSnapshots.items = jsonSnapshots.items.concat(data.items);
      }

      dl = $("#main_viewer_snapshots_draglayer");
      //dl.html("");
      if (dl) {
        $.each(data.items, function(i,item) {
	  //alert(item[0]);
          index = i+(page-1)*per_page;
          if (auth_key) {
	  $('<img src="'+ url_str + "gigapans/"+auth_key+"/snapshots/" + item[0] + "-90x60.jpg"+'" border=0 nowrap id="'+item[0]+'" onMouseOver="onSnapshotMouseOver('+index+');" onMouseOut="onSnapshotMouseOut();" onClick="onSnapshotClick('+index+');" alt="" width="90" height="60">').appendTo(dl);
	  } else {
	  $('<img src="'+ url_str + "snapshots/" + item[0] + "-90x60.jpg"+'" border=0 nowrap id="'+item[0]+'" onMouseOver="onSnapshotMouseOver('+index+');" onMouseOut="onSnapshotMouseOut();" onClick="onSnapshotClick('+index+');" alt="" width="90" height="60">').appendTo(dl);
          }
   
	  if (item[1].comment_set) {
              var x = 83 + (index * 120);

              var auth_key_query_string = '';
              if (auth_key) {
                var auth_key_query_string = '/?auth='+auth_key;
              }
	      var bubble = $('<a href="'+url_str+'conversations/'+item[0]+auth_key_query_string+'" onmouseover="onSnapshotMouseOver('+index+'); rollover(\'bubble'+item[0]+'\',\'/images/comment_icon-12x12-orange.gif\')" onmouseout="onSnapshotMouseOut('+item[0]+'); rollover(\'bubble'+item[0]+'\',\'/images/comment_icon-12x12-white.gif\')"><img class="comment_bubble" name="bubble'+item[0]+'" style="left:'+x+'" src="/images/comment_icon-12x12-white.gif"></a>');
	    dl.append(bubble);	    
	  }
        });
      }

     if(_snapshotFilter_complete_js) {
       eval(_snapshotFilter_complete_js);
     }
     updateDisplayStatus();
    
     if (page != old_page && page < old_page && refresh) {
       page++;
       snapshotFilter_process();
     }
     else {
       old_page = page;
       refresh = false;
     }
  
    scrollRight = true;
    });

/*
   if(xmlRequest.readyState == 4) {
      if(xmlRequest.responseText != null && xmlRequest.responseText.indexOf("ERROR") >= 0) {
         //dialog_tell("Error", "There was an error completing your request (server responded with '" + xmlRequest.responseText + "')", 3);
		} else {
			var dl = document.getElementById("main_viewer_snapshots_draglayer");

         if (dl)
            {
            dl.innerHTML = xmlRequest.responseText;
            dl.style.left = 0;

            var scripts = dl.getElementsByTagName('SCRIPT');
            for(var v = 0; v  < scripts.length; v++) {
              eval(scripts[v].innerHTML);
            }

            // add comment bubbles to the snapshots that have comments
            if (jsonSnapshots) {
               for(var i = 0; i < jsonSnapshots.snapshot_order.length; i++) {
                 var snapshotId = jsonSnapshots.snapshot_order[i];
                 if(jsonSnapshots[snapshotId].numComments > 0) {

                   var x = 83 + (i * 120);
                   var auth_key_query_string = '';
                   if (auth_key) {
                      var auth_key_query_string = '/?auth='+auth_key;
                   }
		   // GDO: Ugh. FIX ME FOR PRIVATE CONVERSATIONS
	 	   var bubble = '<a href="'+url_str+'conversations/'+snapshotId+auth_key_query_string+'" onmouseover="onSnapshotMouseOver('+snapshotId+'); rollover(\'bubble'+snapshotId+'\',\'/images/comment_icon-12x12-orange.gif\')" onmouseout="onSnapshotMouseOut('+snapshotId+'); rollover(\'bubble'+snapshotId+'\',\'/images/comment_icon-12x12-white.gif\')"><img class="comment_bubble" name="bubble'+snapshotId+'" style="left:'+x+'" src="/images/comment_icon-12x12-white.gif"></a>';
                   $("#main_viewer_snapshots_draglayer").append(bubble);
                 }
               }
            }

            if(_snapshotFilter_complete_js)
               eval(_snapshotFilter_complete_js);

            updateDisplayStatus();
            }
		}
	}

*/
	return true;
}

// pre-load the comment bubble images
new Image().src = "/images/comment_icon-12x12-white.gif";
new Image().src = "/images/comment_icon-12x12-orange.gif";

function rollover(imgName, imgSrc)
   {
   if (document.images)
      {
      if (imgSrc != "none")
         {
         document.images[imgName].src = imgSrc;
         }
      }
   }


function snapshotFilter(filter, complete_js)
   {
/*
	var r = getXMLRequest();

   if (! r)
      {
      return;
      }
*/

   var snapshot_links =
      {
      'recent': 'Most Recent',
      'popular': 'Most Popular',
      'creator': 'Creator',
      'author': snapshot_author + '\'s Snapshots',
      'self': 'My Snapshots'
      };

   var old_snapshot_filter = currentSnapshotFilter;

   _snapshotFilter_complete_js = complete_js;
   currentSnapshotFilter = filter;

   if (currentSnapshotFilter != old_snapshot_filter) {
     page = 1;
     dl = $("#main_viewer_snapshots_draglayer");
     dl.html("");
     jsonSnapshots = {"count": 0, "items":[], "available":0};

     // asynchonous processes ...
     var draglayer = document.getElementById("main_viewer_snapshots_draglayer");
     draglayer.style.left = 0;

     if (filter == "self" && !isLoggedIn()) { 
	updateDisplayStatus();
     }
     else {
       snapshotFilter_process();
     }   
   } else {
       if (jsonSnapshots.count == 0) {
         snapshotFilter_process();
       }

   }


   //r.onreadystatechange = snapshotFilter_process;
   //r.send("proc=getSnapshots&gigapan_id=" + gigapan_id + "&filter=" + filter + "&auth=" + auth_key);

   //alert(filter);
   document.getElementById("snapshot_filter_" + filter).innerHTML =
   "<SPAN style=\"padding-left: 5px; padding-right: 5px;\">" +
   snapshot_links[filter] +
   "</SPAN>";

   if (old_snapshot_filter && old_snapshot_filter != filter)
      {
      document.getElementById('snapshot_filter_' + old_snapshot_filter).innerHTML
            = "<A onClick=\"snapshotFilter('" + old_snapshot_filter + "');\">" +
              snapshot_links[old_snapshot_filter] + "</A>";
      }

   return true;
   }


function scrollToSnapshot(id) {
   if(!id) return true;

   if(!jsonSnapshots) return true;

   var w = 0;
   for(var i = 0; i < jsonSnapshots.items.length; i++) {
      if(jsonSnapshots.items[i][0] == id) {
         w= i;
         break;
      }
   }
   w--;
   if (w < 0) {
     if (jsonSnapshots.items.length < jsonSnapshots.available) {
      page += 1;
      snapshotFilter_process();
     
     }
   }

   // make sure the snapshot was found (it might not be if the filter defaults to, say, "My Snapshots" and the given
   // snapshot id isn't one of those (which can happen if someone clicks on a snapshot from search results).
   if (w >=0) {
      var c = document.getElementById("main_viewer_snapshots_viewport");

      // ensure snapshot is visible in scroll filmstrip
      var halfSnapshotWidth = 0.5 * snapshotWidth;
      var scrollAmount = (c.clientWidth / 2) - (w * snapshotWidth + halfSnapshotWidth);

      snapshotScroll(scrollAmount, false);
   }

   return true;
}

// ENSURES NAMED SNAPSHOT IS VISIBLE AND HIGHLIGHTS IT IN THE VIEWER.
function showSnapshot(id) {
   if(! id) {
		return true;
   }

   scrollToSnapshot(id);

   // find the snapshot in the draglayer, so we can trigger events on it
   var dl = document.getElementById("main_viewer_snapshots_draglayer");
   var elem = null;
   for(var i = 0; i < dl.childNodes.length; i++) {
      if(dl.childNodes[i].nodeName != "IMG")
         continue;

      if(dl.childNodes[i].id == id) {
         elem = dl.childNodes[i];
         break;
      }
   }

   // show description box, then set display extent
	if(elem) {
		elem.onmouseover(null);
		elem.onclick(null);

		return true;
	}

   return false;
}

// UPDATES SNAPSHOT UI COUNTS/STATUS MESSAGES
function updateDisplayStatus() {

	var draglayer = document.getElementById("main_viewer_snapshots_draglayer");
	var draglayerLeft = ((draglayer.style.left) ? parseInt(draglayer.style.left) : 0);
	var viewport = document.getElementById("main_viewer_snapshots_viewport");
	var header = document.getElementById("main_viewer_snapshots_header");
	var range = document.getElementById("main_viewer_snapshots_position");
	var numSnapshots = 0;

	// count snapshots
	if(jsonSnapshots) {
          numSnapshots = jsonSnapshots.available;
	} else {
	  numSnapshots = 0;
	}

   // compute range
   var min_snapshot;
   var max_snapshot;

   if (draglayerLeft < 0)
      {
      var numberOfSnapshotsHiddenToTheLeft = Math.abs(Math.round(draglayerLeft / snapshotWidth));
      min_snapshot = numberOfSnapshotsHiddenToTheLeft + 1;
      max_snapshot = Math.round((Math.abs(draglayerLeft) + viewport.clientWidth) / snapshotWidth);
      }
   else
      {
      min_snapshot = 1;
      max_snapshot = Math.min(numSnapshots, getNumberOfSnapshotsWhichCanBeAllOrMostlyInView());
      }

   // update UI
   if (numSnapshots) {
	header.innerHTML = "Snapshots (" + numSnapshots + ")";
   }

   if (draglayer.clientWidth > 0) {
      if (numSnapshots == 0) {
         range.innerHTML = "";
      } else if (numSnapshots == 1){
         range.innerHTML = "Only one snapshot matches the selected filter";
      } else {
         range.innerHTML = "Snapshots " + min_snapshot + " to " + max_snapshot + " of " + numSnapshots;
      }
   } else {
      var message = "No snapshots match the selected filter ";
      var messageAddendum = "";
      if (currentSnapshotFilter == 'self')
         {
         if (isLoggedIn())
            {
            messageAddendum = "(you have not taken any snapshots of this panorama)";
            }
         else
            {
            messageAddendum = "(you are not logged in)";
            }
         }
      range.innerHTML = message + messageAddendum;
   }

   // update right/left arrows (start by enabling them, and then handle all the cases where they could be disabled)
   var leftArrow = document.getElementById("left_scroll_image");
   var rightArrow = document.getElementById("right_scroll_image");
   leftArrow.src = "/images/left_scroll.png";
   rightArrow.src = "/images/right_scroll.png";
   if (draglayer.clientWidth < viewport.clientWidth)
      {
      leftArrow.src = "/images/left_scroll_disabled.png";
      rightArrow.src = "/images/right_scroll_disabled.png";
      }
   else
      {
      if (draglayerLeft == 0)
         {
         leftArrow.src = "/images/left_scroll_disabled.png";
         }
      if (Math.abs(draglayerLeft) + viewport.clientWidth >= draglayer.clientWidth)
         {
         rightArrow.src = "/images/right_scroll_disabled.png";
         }
      }
   return true;
}

// SCROLLS FILMSTRIP BY GIVEN AMOUNT; BOUNDS TO ENSURE STRIP IS ALWAYS VISIBLE.
function snapshotScroll(amount, refresh) {
	var dl = document.getElementById("main_viewer_snapshots_draglayer");
	var c = document.getElementById("main_viewer_snapshots_viewport");

	if(dl && c) {
		var l = ((dl.style.left) ? parseInt(dl.style.left) : 0);
		var pos = l + parseInt(amount);
		var pos0 = pos;

      // there is nothing to scroll--inner layer is smaller than viewport
		if(dl.clientWidth < c.clientWidth)
			return;

		// ensure a user can't scroll past bounds of drag layer--max out such that the drag layer is always visible
		// prevent left side from going too far right
      if (pos > 0) {
         pos = 0;
      } else if (pos < c.clientWidth - dl.clientWidth) {
         pos = c.clientWidth - dl.clientWidth;
		}

      dl.style.left = pos + "px";

		if(refresh)
			updateDisplayStatus();

		return true;
	} else
		return false;
}

var _last_border_snapshot = null;
function borderSnapshot(id) {
	var t = document.getElementById(id);

	if(t) {
		if(_last_border_snapshot)
			_last_border_snapshot.style.border = "none";

		t.style.border = "1px solid #FF7B00";

		_last_border_snapshot = t;
	}
}

function displayDetails(index) {
      var d = document.getElementById("main_viewer_snapshots_description");
      //alert(jsonSnapshots.items);
      if (jsonSnapshots) {
        id = jsonSnapshots.items[index][0];
      }
      if (d)
         {
         var auth_key_query_string = '';
         if (auth_key) {
            var auth_key_query_string = '/?auth='+auth_key;
         }
         var str = ""
         str += "<DIV CLASS='wrapper'>"; 
	 if(document.getElementById("embed")) {
		str += "<DIV CLASS='ID Number'>" + id + "</DIV>";
	 }
         str += "<DIV CLASS='title'>" + jsonSnapshots.items[index][1].name + "</DIV>";
         str += "<DIV CLASS='description'>" + jsonSnapshots.items[index][1].description + "</DIV>";
         str += "<DIV CLASS='byline'>";
//         str += "Snapped by <A HREF='viewProfile.php?userid=" + jsonSnapshots.items[index][1].authorId + "'>" + jsonSnapshots.items[index][1].author + "</A>, " + jsonSnapshots.items[index][1].created;
         str += "Snapped by <A HREF='" + url_str + "profiles/" + jsonSnapshots.items[index][1].owner.id + "/'>" + jsonSnapshots.items[index][1].owner.username + "</A>, " + jsonSnapshots.items[index][1].created;

//         str += ' | <a href="/viewConversation.php?id=' + id + auth_key_query_string + '">';
         str += ' | <a href="'+url_str+'conversations/' + id + auth_key_query_string + '">';
         if (jsonSnapshots.items[index][1].comment_set && jsonSnapshots.items[index][1].comment_set.count > 0)
            {
            str += "View Comments";
            }
         else
            {
            str += "Add a Comment";
            }
         str += "</a></DIV>";
         str += "</DIV>";

         d.innerHTML = str;
	$('div.description').urlize();
         }
}

// UI CALLBACKS/EVENT HANDLERS
function snapshotScrollLeft() {
	return snapshotScroll(getNumberOfSnapshotsWhichCanBeFullyInView() * snapshotWidth, true);
}

var scrollRight = true;
function snapshotScrollRight() {
  if (scrollRight) {
    if (jsonSnapshots.count < jsonSnapshots.available) {
      page += 1;
      scrollRight = false;
      snapshotFilter_process();    
    }
  return snapshotScroll(-1 * getNumberOfSnapshotsWhichCanBeFullyInView() * snapshotWidth, true);
  }
}

function getNumberOfSnapshotsWhichCanBeFullyInView() {
   var viewport = document.getElementById("main_viewer_snapshots_viewport");

   return Math.floor(viewport.clientWidth / snapshotWidth);
}

function getNumberOfSnapshotsWhichCanBeAllOrMostlyInView() {
   var viewport = document.getElementById("main_viewer_snapshots_viewport");

   return Math.round(viewport.clientWidth / snapshotWidth);
}

function onSnapshotMouseOut(id) {
   if (!isSnapshotDialogVisible)
      {

//      return document.getElementById('flash_viewer').hideRectangle();

        return document.getElementById('flash_viewer').hideSnapInclusion(id);// but id is undefined!

      }
   return null;
}

function onSnapshotMouseOver(index)
   {
   if (!isSnapshotDialogVisible)
      {

      displayDetails(index);

/*
      return document.getElementById('flash_viewer').showRectangle(
        jsonSnapshots[id].xmin + 2,
        jsonSnapshots[id].ymin + 2,
        jsonSnapshots[id].xmax - 4,
        jsonSnapshots[id].ymax - 4,
        1, 255, 155, 255);

*/
      return document.getElementById('flash_viewer').showSnapInclusion(
	jsonSnapshots.items[index][0],
	jsonSnapshots.items[index][1].bounds.xmin,
        jsonSnapshots.items[index][1].bounds.ymin,
        jsonSnapshots.items[index][1].bounds.xmax,
        jsonSnapshots.items[index][1].bounds.ymax,
	jsonSnapshots.items[index][1].name,
	jsonSnapshots.items[index][1].description);
/*
	id,
	jsonSnapshots[id].xmin,
        jsonSnapshots[id].ymin,
        jsonSnapshots[id].xmax,
        jsonSnapshots[id].ymax,
	jsonSnapshots[id].name,
	jsonSnapshots[id].description);
*/

      }
   }

function onSnapshotClickSetViewBoundsReturn() { }

function onSnapshotClick(index) {
  id = jsonSnapshots.items[index][0]
  jsonSnapshot = jsonSnapshots.items[index][1]

/*
	var r = getXMLRequest();

	if(! r)
		return;

	r.onreadystatechange = function() {};
	r.send("proc=snapshotView&snapshot_id=" + id);

*/
      $.ajax({
        data: "proc=snapshotView&snapshot_id="+id
      });

  borderSnapshot(id);
        var bb = (jsonSnapshot.bounds.ymax - jsonSnapshot.bounds.ymin) * 0.02;
        var bb = (jsonSnapshot.bounds.ymax - jsonSnapshot.bounds.ymin) * 0.02;
	return document.getElementById('flash_viewer').setViewBounds(
    'onSnapshotClickSetViewBoundsReturn',
    jsonSnapshot.bounds.xmin - bb,
    jsonSnapshot.bounds.ymin -bb,
    jsonSnapshot.bounds.xmax +bb,
    jsonSnapshot.bounds.ymax +bb);
	
	if(document.getElementById("embed")) {
		var snapshots = document.getElementById("snapshotIDs");
	}
}

function bookmark() {
   var spacerObj = document.getElementById("flash_viewer_spacer_bottom");

   if(! isLoggedIn()) {
      login("bookmark()", spacerObj);
		return false;
	}

   $.ajax(
      {
      data:
         {
         proc: 'bookmark',
         gigapan_id: gigapan_id
         },
      success: function(retVal)
         {
         dialog_tell("Bookmark added", "Find your bookmarks in <A HREF='"+url_str+"my-bookmarks/'>My Home</A>", 3, spacerObj);
         }
      });

   return true;
}

// SNAPSHOT
function snapshot_click(xmin, ymin, xmax, ymax)
   {
   var name = document.getElementById('snapshot_name').value;
   var description = document.getElementById('snapshot_description').value;

   if (name && description)
      {
      $.ajax(
         {
         data:
            {
            proc: 'snapshot',
            gigapan_id: gigapan_id,
            name: name,
            description: description,
            xmin: xmin,
            ymin: ymin,
            xmax: xmax,
            ymax: ymax
            },
         complete: function()
            {
            document.getElementById('flash_viewer').hideSnapshotFrame();
            isSnapshotDialogVisible=false;
            dialog_hide(null);
            },
         success: function()
            {
            document.getElementById('flash_viewer').hideSnapshotFrame();
            isSnapshotDialogVisible=false;
            snapshotFilter(currentSnapshotFilter);
            }
         });
      }
   else
      {
      alert("You didn't enter a name and description for your snapshot!");
      }

   return true;
   }

// callback for flash browser to tell us coordinates
function snapshotGetContainedViewBoundsReturn(xmin, ymin, xmax, ymax)
   {
   isSnapshotDialogVisible = true;
   document.getElementById('flash_viewer').showSnapshotFrame();
   dialog_ask("Add a Snapshot",
              "Snapshot Name: <INPUT TYPE=\"text\" ID=\"snapshot_name\"><BR>Description: <TEXTAREA ID=\"snapshot_description\"></TEXTAREA><BR><span class=\"dialog_instruction\">NOTE: Although HTML is not allowed in your description, any URLs you enter beginning with \"http://\" will be automatically hyperlinked.</span><BR><BR><INPUT TYPE=\"submit\" VALUE=\"Save\" onClick=\"document.getElementById('flash_viewer').getSnapshotFrameBounds('snapshot_click');\">&nbsp;<input type=\"button\" value=\"Cancel\" onclick=\"isSnapshotDialogVisible=false;dialog_hide();document.getElementById('flash_viewer').hideSnapshotFrame()\">",
              document.getElementById("flash_viewer_spacer_bottom"),
              "isSnapshotDialogVisible=false;document.getElementById('flash_viewer').hideSnapshotFrame()");

	return true;
   }

function myGetElementById(id)
{
    if (document.getElementById)
        return document.getElementById(id);
    else if (document.all)
        return document.all[id];
    return null;
}

function snapshot() {
// flash version:
//	myGetElementById('flash_viewer').focus();
	document.getElementById('flash_viewer').startTakingSnapshot();
// web-page version:
//	if(! isLoggedIn()) {
//		login("snapshot()", document.getElementById("flash_viewer_spacer_bottom"));
//		return false;
//	}

//	return document.getElementById('flash_viewer').getContainedViewBounds('snapshotGetContainedViewBoundsReturn', 1.5);
}

// COMMENT
function comment_click() {
  var body = document.getElementById('comment_body').value;
    if (body)
      {
      $.ajax(
         {
         data:
            {
            proc: 'comment',
            gigapan_id: gigapan_id,
            body: body
            },
         success: function()
            {
            window.location.reload();
            }
         });
      }
   else
      {
      alert("You didn't enter a comment!");
      }

   return false;
}

// COMMENT
function comment_edit_submit(commentId)
   {
	var body = jQuery.trim(document.getElementById('comment_body').value);

   if (body)
      {
      $.ajax(
         {
         data:
            {
            proc: 'update_comment',
            comment_id: commentId,
            body: body
            },
         success: function()
            {
            window.location.reload();
            }
         });
      }
   else
      {
      alert("You didn't enter a comment!");
      }

   return false;
   }

function confirmCommentDelete(delete_id)
   {
	var delete_html = '<CENTER><FORM ACTION="" METHOD="POST" onsubmit="return false;"><INPUT TYPE="button" onclick="commentDelete('+delete_id+');" VALUE="Yes, delete this comment permanently."></FORM></CENTER>';

	return dialog_ask("Confirm delete", delete_html);
   }

function commentDelete(commentId)
   {
   if (commentId)
      {
      $.ajax(
         {
         data:
            {
            proc: 'delete_comment',
            comment_id: commentId
            },
         success: function()
            {
            window.location.reload();
            }
         });
      }
   else
      {
      alert("You didn't specify a comment to delete!");
      }
   }

function commentEdit(commentId)
   {
   var comment_infix;
   if (auth_key) {
     comment_infix = 'gigapans/' + auth_key + '/comments/';
   } else {
     comment_infix = 'gigapans/' + gigapan_id + '/comments/';
   }
   if(isLoggedIn())
      {
        str = url_str + comment_infix + commentId + '.json';

        $.getJSON(str + "?callback=?",
          function(data) {
            comment = data;
            if (comment)
               {
               dialog_ask("Edit Comment", '<TEXTAREA ID="comment_body">'+comment.message+'</TEXTAREA><BR><INPUT TYPE="submit" VALUE="Save" onClick="comment_edit_submit('+commentId+')">', null,'','comment_body');

               // undo the hack from rpc.php which inserts <br> tags for line breaks
               var commentBody = document.getElementById('comment_body');
               commentBody.value = commentBody.value.replace(/<br>/g,"\r");
               }
          }
        );
/*
      $.ajax(
         {
         data:
            {
            proc: 'getCommentAsJSON',
            comment_id: commentId,
            auth: auth_key
            },
         success: function(retVal)
            {
            eval("var comment = " + retVal);
            if (comment)
               {
               dialog_ask("Edit Comment", '<TEXTAREA ID="comment_body">'+comment.message+'</TEXTAREA><BR><INPUT TYPE="submit" VALUE="Save" onClick="comment_edit_submit('+commentId+')">', null,'','comment_body');

               // undo the hack from rpc.php which inserts <br> tags for line breaks
               var commentBody = document.getElementById('comment_body');
               commentBody.value = commentBody.value.replace(/<br>/g,"\r");
               }
            }
         });
      */
      }

   return false;
   }

function comment() {
  if(!isLoggedIn()) 
  {
  login("comment()", null);
  return false;
  }

  dialog_ask("Add a Comment", "<TEXTAREA ID=\"comment_body\"></TEXTAREA><BR><INPUT TYPE=\"submit\" VALUE=\"Save\" onClick=\"this.disabled=1; comment_click();\">", null,'','comment_body');

  return true;
}


function flag(cid) {
   if (confirm("Flag this comment as inappropriate?")) {
      $.ajax(
         {
         data:
            {
            proc: 'flag',
            comment_id: cid
            },
         success: function()
            {
            alert("This comment has been flagged and the moderators have been notified.");
            }
         });
   }

   return true;
}


(function($) {  
  $.fn.urlize = function() {
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
            $(this).html(
                $(this).html().replace(regexp,'<a href="$1">$1</a>')
            );
        });
        return $(this);
    }
})(jQuery);  
