/* ---------------------------------------------------------------------
                              Image Album
-----------------------------------------------------------------------*/
// v 2.1.0

// Temporary decision
var tempAlbumURL; // Global vars for reloading album from any place
var tempFID; // --""--
var tempNoSearch = 0; // allow search query

var imgLibrary; // instance of library

/* 
imageLibrary class constructor

options:
  handlerURL -- handler for album images request 
  imageURL -- handler for image view request 
  commentsURL -- handler for comments list
  trail -- trail options object
    length -- trail length (default: 3) 
    optSizing -- enbale items sizing in trail (default: true)
  colorbox -- colorbox object options, see jquery.colorbox.js for details
*/           
function imageLibrary(options) {
  imgLibrary = this;
  this.handlerURL = options.handlerURL || "";
  this.imageURL = options.imageURL || "";
  this.commentsURL = options.commentsURL || "";
  
  this.scrollTimer = null;               // scrill timer ID
  this.scrollInterval = 200;             // scroll delay
  
  // trail effect options
  this.trail = options.trail || {};
  this.trail.length = this.trail.length >= 0 ? this.trail.length : 0;
  this.trail.optSizing = typeof(this.trail.optSizing) != "undefined" ? this.trail.optSizing : false;
  
  // colorbox options
  this.colorbox = {fixedWidth: "400px", /*fixedHeight: "260px",*/ modalClose: "Close"}
  if (typeof options.colorbox != "undefined")
   for (prop in options.colorbox) {
    this.colorbox[prop] = options.colorbox[prop] 
   }
   
  this.isSearch = $("#q").val() != "";                        // performed search flag                  
  
  this.albumList = $("#albumList ul");
  this.albums = $("#albumList li");
  this.initAlbums();

  this.isEmpty = this.albums.length < 1;                      // empty gallery flag; 
  
  // html containers
  this.index = $("#indexView");
  this.image = $("#imageView");

  this.init();
  
  this.currentImage = null;        // currently displayed image
  with($(".imageViewNav", this.image)) {
   find(".next a").click(imgLibrary.imageNextClick);
   find(".back a").click(imgLibrary.indexViewClick);
   find(".prev a").click(imgLibrary.imagePrevClick);
  }

}
// constants
imageLibrary.prototype.ENTIRE_ALBUM_LINK = '<div class="albumEntire"><a href="">View Entire Album</a></div>'; 
imageLibrary.prototype.LOADING_MIN = '<div class="prglLoadingMin">Loading...</div>';
imageLibrary.prototype.TOOL_TIP = '<div id="prglTip"><span class="text"></span><span class="tip"></span></div>'

// start image preload after ajax request complete 
imageLibrary.prototype.startPreloader = function() {
//  $.ajaxSetup({
//   complete: function() {
//     setTimeout(function() {
//       var s = $("#img_album_bullets").html();
//       $("#img_album_bullets").html(s.replace(/<!-- /gi, "").replace(/ -->/gi, "")).show().hide();
//     }, 2000);
//     $.ajaxSetup({complete: function(){} });
//   }
//  })
}


// Init album list
imageLibrary.prototype.initAlbums = function() {
 this.albums.click(this.albumClick);
 this.albums.hover(
  function () {$(this).addClass("gl-hover")},
  function () {$(this).removeClass("gl-hover")}
 )
}

// Makes control initialization
imageLibrary.prototype.init = function() {
  var id; // album id
  var al; // album element
  var fid = prGetParam("fid");
     
  // hide albums if nothing to show
  if (!this.isEmpty)
    $("#albumListView, .albumBorder", ".prImageLibrary").show();
  
  // check album id passed in params 
  var aid = prGetParam("id").replace(/E\d+C/gi, "") || -1;
  if ( $(this.albums).is("[keyid="+aid+"]") && !this.isSearch) {
   al = $(this.albums).filter("[keyid="+aid+"]")[0];
   id = aid; 
  }
  else
   if (this.albums[0]) {
    al = this.albums[0];
    id = $(al).attr("keyid");
   }
   else {
    al = null;
    id = -1;
   }
  
  if (!this.isEmpty) {
   this.initAlbumHover();
   this.initScroll();
  }   

  // search should ignore image permalink from URL
  if (this.isSearch)  
   fid = "";

  // show album and image
  this.albumLoad("?id="+id, fid);
  this.showAlbum(al);
  
  // show single image only
  if(fid && aid==-1) {
   this.imageLoad("?fid="+fid+"&id="+id); 
  }

//  this.startPreloader();
  this.initSearchSwitch();  
  this.initTip();
  // ie8 bugfix
  if (this.ie8)
   this.fixIE8();
}

// Toggles view between index and image view
imageLibrary.prototype.switchView = function(show) {
  if (show) {
   this.index.show();
   this.image.hide();
  }
  else {
   this.index.hide();
   this.image.show();
  }
}


// Album tooltip initialization
imageLibrary.prototype.initTip = function () {
  this.tooltip = $(this.TOOL_TIP).appendTo("body");
   
  // clear alt and title to prevent default tooltip 
  this.albums.find("img").attr({"alt":"", "title":""});
  // add handler to show gallery tooltip 
  this.albums.hover(
   function(){
    var al = $(this); 
    imgLibrary.tooltip.find(".text").html(al.find("h2>a").html());
    imgLibrary.tooltip.css ({"top": al.offset().top, "left": al.offset().left })
     .show();
   },
   function(){
    imgLibrary.tooltip.hide();
   }
  )
}

//------------------------------------------------------------------------------
// Search bar toggle
//------------------------------------------------------------------------------

// Init search toggle
imageLibrary.prototype.initSearchSwitch = function() {
  var a = $("#glShowSearch a:first");

  var hfun = function() {
   $(this).css("border-bottom-color", this.style.color);
  }
  a.hover(hfun, hfun);

  a.click(imgLibrary.switchSearch).click();                                      
}

// Toggles search bar
imageLibrary.prototype.switchSearch = function() {
  var frm = $(".prImageLibrary .searchImages");  
  var a = $("#glShowSearch a:first");
  
  // hide on first run
  if (a.html() == "") {
   if (!imgLibrary.isSearch) {
    frm.hide();
    a.html(a.attr("glshow"));    
   }
   else
    a.html(a.attr("glhide"));
   return false;   
  }
  
  if (frm.is(":hidden")) {
    frm.slideDown("fast")
    a.html(a.attr("glhide"));   
  }   
  else {
   frm.slideUp("fast");   
   a.html(a.attr("glshow"));   
  }   
  return false;
} 


//------------------------------------------------------------------------------
// Scroll methods
//------------------------------------------------------------------------------

// Scroll initialization
imageLibrary.prototype.initScroll = function() {
  var alWidth = $("#albumList").innerWidth();
  var iw = $(this.albums[0]).outerWidth();          // item width
  var iw0 = this.trail.normalOuterWidth;            // active item width
  
  // remove border from last item and calculate overall width
  var w = $(this.albums[this.albums.length-1]).addClass("last").outerWidth();
  w += iw * (this.albums.length-2) + iw0;
  w = Math.max(alWidth, w);
  
  this.albumList.width(w); 
  
  // scroll html elements
  this.scroll =  $("#scroll");
  var scrollWrap = this.scroll.parents("#scrollWrap"); 
  var scrollHandle = this.scroll.find(".ui-slider-handle");

  // set handle's width
  var shWidth = Math.round(this.scroll.width()/w * alWidth );
  if (scrollHandle.width() <  shWidth) {
   scrollHandle.width(shWidth);
   scrollWrap.css("padding-right", shWidth);  

   // force Safari to redraw element   
   if (jQuery.browser.safari) {
    this.scroll.find("a").html( this.scroll.find("a").html() );
   }
  }

  var maxVal = w-alWidth;
  // create scrollbar
  if (!maxVal)
   this.scroll.hide();
  else
   this.scroll.slider({
     max: maxVal,
     step: 1,
     change: imgLibrary.scrollChange,
     slide: imgLibrary.scrollChange
   });
  
  // click in "max value area"
  scrollWrap.click(
   function() {imgLibrary.scroll.slider("value", maxVal) }
  );

  // init mouse events for scroll  
  $(".albumBar .prev a").mousedown(function() { imgLibrary.scrollStart(-1) });
  $(".albumBar .next a").mousedown(function() { imgLibrary.scrollStart(1) });
  $(".albumBar .prev a, .albumBar .next a")
   .mouseup(this.scrollStop).mouseout(this.scrollStop)
   .click(function() {return false});
  
  this.initWheelScroll();
}

// Init mouse wheel handler
imageLibrary.prototype.initWheelScroll = function() {
  var el = $("#albumList")[0];  
  
  if(el.addEventListener) {
    el.addEventListener("DOMMouseScroll", this.wheelScroll, false);  // FF
    el.addEventListener("mousewheel", this.wheelScroll, false);      // Opera
  }
  else 
   if(el.attachEvent)
    el.attachEvent("onmousewheel", this.wheelScroll);                // IE
}

// Mouse wheel handler
imageLibrary.prototype.wheelScroll = function(e) {
  e = e ? e : window.event;
  var raw = e.detail ? -e.detail : e.wheelDelta;

  if (raw > 0)
   imgLibrary.scrollPrev();
  else
   imgLibrary.scrollNext()
        
  // canceling event 
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
}


// Start scrolling on mousedown
imageLibrary.prototype.scrollStart = function(direction) {
  var f;
  if (direction > 0)
   f = imgLibrary.scrollNext;
  else
   f = imgLibrary.scrollPrev;
   
  f.call();
  imgLibrary.scrollTimer = setInterval(f, imgLibrary.scrollInterval);
  return false;
} 

// Stop mousedown scrolling
imageLibrary.prototype.scrollStop = function() {
  if (imgLibrary.scrollTimer) {
   clearInterval(imgLibrary.scrollTimer);
   imgLibrary.scrollTimer = null;
  }
}

// Scroll to left
imageLibrary.prototype.scrollPrev = function() {
 imgLibrary.scroll.slider('value', imgLibrary.scroll.slider("value")-$(imgLibrary.albums[0]).width() );
 return false;
}

// Scroll to right
imageLibrary.prototype.scrollNext = function() {
 imgLibrary.scroll.slider('value', imgLibrary.scroll.slider("value")+$(imgLibrary.albums[0]).width() );
 return false;
}

// Scroll on change event
imageLibrary.prototype.scrollChange = function(e, ui) {
  imgLibrary.scrollTo (ui.value);
}

// Scroll to specifed position
imageLibrary.prototype.scrollTo = function(pos) {
 if (pos < this.scroll.slider("option", "min") || pos > this.scroll.slider("option", "max"))
  return;
  
 this.albumList.css("left", -pos);
}


//------------------------------------------------------------------------------
// Album view related methods
//------------------------------------------------------------------------------

// Displays current album
imageLibrary.prototype.showAlbum = function(album) {
 if (!album) 
  return false;
  
 var html = album.innerHTML.replace("<!--", "").replace("-->", "");
 html = html.replace(/<\/?a[^>]*>/gi, "");  // remove links from album
 
 var dataPanel = $("#albumView .dataPanel"); 
 dataPanel.html(html);
 $("#albumView .glPermalink a").attr("href", $("a", album).attr("href") );

 // if search field is not empty
 if(this.isSearch) { 
   $(".albumInfo", dataPanel).hide().after(this.ENTIRE_ALBUM_LINK);
  
   // show entire album event 
   $(".albumEntire a", dataPanel).click(function(){
     tempNoSearch = 1; // Flag forbids using a search word for index list
     imgLibrary.albumLoad(tempAlbumURL,tempFID); // Loading index list
     $(this).remove(); 
     $(".albumInfo", dataPanel).show(); 
     return false;
   });
 }

 // scroll list if album is invisible  
 var v = this.scroll.slider("value");
 var alWidth = $("#albumList").innerWidth();
 var aLeft = $(album).offset().left - $("#albumList ul").offset().left;
 if (v+alWidth <  aLeft) 
  this.scroll.slider("value", Math.round(aLeft - alWidth/2 + $(album).outerWidth()/2 ));

 var a = $(this.albums).filter(".gl-active");
 if (a)
  a.removeClass("gl-active").find("span.gl-active").remove();
  
 $(album).addClass("gl-active").append('<span class="gl-active"></span>')
  .width("auto");
}

//------------------------------------------------------------------------------
// Album trail effect related methods
//------------------------------------------------------------------------------

// Init album trail effect
imageLibrary.prototype.initAlbumHover = function() {
  // min item width depends on item count and min-width property
  var w = this.albums.width();  // item's width
  var mw = parseInt(this.albums.css("min-width").replace("px", ""));
  var al = $("#albumList").innerWidth();
  if (this.trail.optSizing)
    this.trail.minWidth = Math.min (w, Math.max(mw, Math.round(al/this.albums.length)) );
  else
    this.trail.minWidth = w;
  
  // widths for active/hover state
  $(this.albums[0]).addClass("width-test");
  this.trail.normalWidth = $(this.albums[0]).width();
  this.trail.normalOuterWidth = $(this.albums[0]).outerWidth();
  $(this.albums[0]).removeClass("width-test");

  with (this) {
   trail.widthDiff = Math.round( (trail.normalWidth-trail.minWidth)/(trail.length+1) );    // width difference between trail siblings  
   trail.lastIndex = -1;         // index of last hovered element
   trail.alInitWidth = -1;       // album list width
   trail.cssReset = {"margin-left":0, "left":0};
  }
  
  this.albums.width(this.trail.minWidth);

  // possible class names
  this.trail.classMask = ""
  for (var i=0; i<=this.trail.length; i++)
   this.trail.classMask += " glTrail-"+i;
  this.trail.classMask = jQuery.trim(this.trail.classMask);
   
  // event handlers
  this.albumList.mouseleave(this.stopAlbumEffect);
  this.albums.mouseenter(this.showAlbumEffect);
}  

// Show trail effect for item
imageLibrary.prototype.showAlbumEffect = function() {
 // returns sum of width deltas
 function get_diff_sum(n) {
  return (2*(t.normalWidth-t.widthDiff) - t.widthDiff*(n-1))*n/2
 }

 var t = imgLibrary.trail;
 var el = $(this);
 var elIndex = imgLibrary.albums.index(this);

 // album list initial width
 if (parseInt(t.alInitWidth) < 0) {
  t.alInitWidth = imgLibrary.albumList.width();
 }

 // clear prev item 
 if (t.lastIndex >= 0) {
  var e = (t.lastIndex > elIndex) ? 
   imgLibrary.albums[t.lastIndex+t.length] : imgLibrary.albums[t.lastIndex-t.length];
  if (e)
   $(e).width(t.minWidth).removeClass(t.classMask).css(t.cssReset); 
 }
 t.lastIndex = elIndex;

 // reset active element width
 var aEl = imgLibrary.albums.filter(".gl-active");
 if (aEl.attr("class").indexOf("glTrail") == -1)
  aEl.width(t.minWidth);
  
 // sets album list width according new hovered elements
 t.scrollDiff = get_diff_sum(el.nextAll().slice(0, t.length).length)
   + get_diff_sum(el.prevAll().slice(0, t.length).length);  
 imgLibrary.albumList.width(t.alInitWidth + t.scrollDiff);
  
 // set trail elements width 
 // right part and element itself 
 for (var i=elIndex; i<=elIndex+t.length; i++) {
   var it = imgLibrary.albums[i];
   var j = Math.abs(i-elIndex);
   
   if (it) {
    $(it).removeClass(t.classMask).addClass("glTrail-"+j)
     .css(t.cssReset);
    if (t.optSizing)
      $(it).width(t.normalWidth - t.widthDiff*j);
   }
 }
 // left part
 for (var i=elIndex-1; i>=0; i--) {
   var it = imgLibrary.albums[i];
   var j = Math.abs(i-elIndex);
   
   var css = {}
   // for trail items
   if (j <= t.length) {
    var k = t.widthDiff*j;
    if (t.optSizing) 
      css.width = parseInt(t.normalWidth - k)+"px";
    css["margin-left"] = -Math.abs(t.normalWidth - t.minWidth - k) + "px";
    $(it).removeClass(t.classMask).addClass("glTrail-"+j)
   }
   // for all
   $(it).css("left",0);
   var m = Math.abs($(it).offset().left+$(it).outerWidth() - $(it).next().offset().left);
   css.left = -m+"px"; 

   $(it).css(css);
 }
}

// Stop trail effect
imageLibrary.prototype.stopAlbumEffect = function() {
 with (imgLibrary) {
  albumList.css("margin-left", 0)
   .width(trail.alInitWidth);
 
  albums.css(trail.cssReset)
    .width(trail.minWidth)
    .removeClass(trail.classMask)
  albums.filter(".gl-active").width("auto");

  trail.lastIndex = -1;
 }
}


//------------------------------------------------------------------------------
// Index view related methods
//------------------------------------------------------------------------------

// Album onclick event handler
imageLibrary.prototype.albumClick = function() {
  var target_url = $("a", this)[0].href;

  imgLibrary.albumLoad(target_url);
  imgLibrary.showAlbum(this);
   
  return false;
}

// Prepares request URL 
imageLibrary.prototype.getAlbumURL = function(url) {
  var res = url.split("#")[0]; // remove anchor (IE specific) from url.

  if (imgLibrary.handlerURL)
    res = imgLibrary.handlerURL + '?' + res.split("?")[1]; // remove path from url.
            
  if (prGetParam("fid"))
    res += "&fid="+prGetParam("fid");

  if(imgLibrary.isSearch && tempNoSearch == 0)
    res += "&q="+$("#q").val();

  return res;
}

// Loads album content from specified url
imageLibrary.prototype.albumLoad = function(albumURL, fid) {
  //// Temp decision
  tempFID = fid;
  tempAlbumURL = albumURL;
  //////////////////
  var reqURL = this.getAlbumURL(albumURL);
  imgLibrary.ajaxLoad({ reqURL: reqURL, callback: this.albumLoadSuccess, silentMode: Boolean(fid), 
   fid: fid });
}

// Successful album load handler
imageLibrary.prototype.albumLoadSuccess = function(data, options) {
  tempNoSearch = 0; // Allow to use a keyword

  this.index.html(data);
  $(".photoRow", this.index).find(".photo_item:last").addClass("last");
  
  //paging onclick
  $("#pagingBottom a", this.index).click(function() {
    window.scrollTo(0, $(".galleryLoading").offset().top );
    imgLibrary.albumLoad(this.href);
    return false;
  });  

  // images onclick
  $(".photo_item a", this.index).click(this.imageClick);
  
  // further loading image if specified
  if(options.fid) {
   this.imageLoad("?fid="+options.fid); 
  }
  
  if (!options.silentMode)
    this.switchView(true);
}


//------------------------------------------------------------------------------
// Image view related methods
//------------------------------------------------------------------------------

// album image click event
imageLibrary.prototype.imageClick = function() {
 imgLibrary.imageLoad( $(this).parents(".photo_item")[0] );
 
 return false;
}

// ajax load image page
imageLibrary.prototype.imageLoad = function(img) {
 var url;
 
 if (typeof(img) == "object") {
  this.currentImage = img;
  url = $(".photoContent a", img)[0].href;
 }
 else {
  url = img;
  
  var imgs = $(".photo_item", this.index);
  for (var i=0; i<imgs.length; i++)
   if (imgs[i].innerHTML.indexOf(img)>-1) {
    this.currentImage = imgs[i];
    url = $(".photoContent a", imgs[i])[0].href;
    break;
   }
 }
 
 if (this.imageURL)
  url =  this.imageURL + "?" + url.split("?")[1];
  
 this.ajaxLoad({ reqURL: url, callback: imgLibrary.imageSuccess})
} 

// Successful ajax image load
imageLibrary.prototype.imageSuccess = function(data) {
 // set comments handler to tab
 var s = data.replace("#commentsInfo", this.getCommentsURL() );
 $("#imageView .dataPanel").html(s);
 
 // control prev/next links appearance
 $(".imageViewNav .prev, .imageViewNav .next", this.image).removeClass("disabled disabled-prev disabled-next");
 if (this.currentImage) {
  var idx = $(".photo_item", this.index).index(this.currentImage);
  var cur = $("#pagingBottom .right span", this.index);
  
  // prev
  var nav = $(".imageViewNav .prev", this.image); 
  if (idx==0 && cur.prevAll("a").length == 0)
   nav.addClass("disabled disabled-prev");
  
  // next
  nav = $(".imageViewNav .next", this.image);   
  if (idx==$(".photo_item", this.index).length-1 && cur.nextAll("a").length == 0)
   nav.addClass("disabled disabled-next");
 }
 
 var comments = prGetParam("comments");
 $("#imageTabs").tabs({
   selected: comments ? 1 : 0,
   cache: true,
   load: this.commentsInit
 });
 
 // lightbox download. if Policy already accepted don't apply it.
 var dndLink = $("#imageView .glDownload a"); 
 if (dndLink.colorbox)                   // test on colorbox plugin 
   if (document.cookie.indexOf("prAccept=1") == -1) 
     dndLink.colorbox({},function(){ 
      $("#prSubmitDnd").click(imgLibrary.imageDownloadClick);
     });
   else 
    dndLink.removeAttr("target");
 
 this.switchView(false);
}

// Download button click handler for File Policy form
imageLibrary.prototype.imageDownloadClick = function() {
 $("#imageView .glDownload a").unbind("click.colorbox").removeAttr("target");
 setTimeout(function(){$("#modalClose").click();}, 50);
}

// Switch view back to index
imageLibrary.prototype.indexViewClick = function() {
 imgLibrary.switchView(true);
 return false;
}

// Go to next image
imageLibrary.prototype.imageNextClick = function() {
 imgLibrary.imageGo(1);  
 return false;
}

// Go to previous image
imageLibrary.prototype.imagePrevClick = function() {
 imgLibrary.imageGo(-1);  
 return false;
}

// Go to image by delta
imageLibrary.prototype.imageGo = function(delta) {
 var imgs = $(".photo_item", this.index);
 var i = imgs.index(imgLibrary.currentImage) + delta;
 
 if (i<0) {
  this.indexGo(-1);
  return; 
 }

 if (i>imgs.length-1) {
  this.indexGo(1);
  return; 
 }

 this.imageLoad(imgs[i]);
}

// Go to index page
imageLibrary.prototype.indexGo = function (delta) {
  var cur = $("#pagingBottom .right span", this.index);
  var next;
  
  if (delta > 0)
   next = cur.nextAll("a")[0];
  if (delta < 0)
   next = cur.prevAll("a")[0];
  
  if (next) {
   imgLibrary.ajaxLoad({ 
    reqURL: this.getAlbumURL(next.href), 
    callback: function(data, options) {
      imgLibrary.albumLoadSuccess(data, options);
      imgLibrary.indexGoSuccess(delta); 
    }
   });
  }
}

// Show image from newely loaded index page 
imageLibrary.prototype.indexGoSuccess = function(delta) {
 var imgs = $(".photo_item", this.index);

 if (!imgs.length) 
  return;
   
 if (delta > 0) 
  this.imageLoad(imgs[0]);
 if (delta < 0)
  this.imageLoad(imgs[imgs.length-1])
}


//------------------------------------------------------------------------------
// Comments methods
//------------------------------------------------------------------------------

// Init comments events
imageLibrary.prototype.commentsInit = function () {
 $("#commentsForm form").submit(imgLibrary.commentsSubmit);
}

// Return url for comments request
imageLibrary.prototype.getCommentsURL = function () {
 var url;
 if (this.currentImage) {
  var href = $("a", this.currentImage).attr("href").match(/[?&]fid=(\d+)/i);
  url = this.commentsURL + "?fid=" + href[1];
 }
 else 
  if (location.search.indexOf("fid")>-1)
   url = this.commentsURL+location.search
  else 
   url = "";
  
 return url;
}

// Comments form submit event handler
imageLibrary.prototype.commentsSubmit = function () {
 var params = {};

 // remove default values (pr_comments.js) 
 $(".field", this).each(function(){
  var inp = $("input:visible, textarea:visible", this).get(0); 
  if (inp.value == $(this).attr("replyValue")) inp.value = '';
 });
 
 // build post params
 $(":input", this).each(function() {
   params[this.name]=this.value;
 })
 
 // sending post request
 var commentId = $("#pr_commentParentId").val(); 
 $.post(imgLibrary.getCommentsURL(), params, function(data, status){
  // commentsAutoApprove flag should be setted in form code
  // as <script type="text/javascript">imgLibrary.commentsAutoApprove = true;</script>
  if (imgLibrary.commentsAutoApprove)
    $("#commentsInfo").html(data)
  else {
    $("#commentsForm").html($(data).find("#commentsForm").html());  
    imgLibrary.commentsFields(commentId);  
  }
  imgLibrary.commentsInit();
 })
 
 // show loader 
 $(this).html(imgLibrary.LOADING_MIN);
 return false;
}

// Process comments form fields
imageLibrary.prototype.commentsFields = function(commentId) {
 $(".field", "#commentsForm").each(function () {
   // hint values in reply-to mode
   if (commentId > 0) {
    var s = $(this).attr("replyValue");
    var inp = $("input:visible, textarea:visible", this).eq(0);
    if (!inp.val()) 
      inp.val(s);
    inp.focus(function () { if (this.value == s) this.value=''})
      .blur(function () { if (this.value == '') this.value=s});
   }
   else
    $("input, textarea", this).val("");
 })
}

// Modified function replyToComment (pr_comments.js)
function replyToComment(commentId){
  // hides clicked link       
  $("#commentsInfo .cmtReply:hidden").show();       
  $("#replyForm"+commentId).parent().prev(".cmtReply").hide();        

  // moves form
  $("#commentsForm").remove().appendTo("#replyForm"+commentId);
  $("#pr_commentParentId").val(commentId);
  $("form", "#replyForm"+commentId).submit(imgLibrary.commentsSubmit);
  
  // process form fields
  imgLibrary.commentsFields(commentId);
  
  return false;
}


//------------------------------------------------------------------------------
// Low level routines for ajax requests
//------------------------------------------------------------------------------

// Perfoms ajax request
// options = {reqURL, callback, silentMode}
imageLibrary.prototype.ajaxLoad = function(options) {
  if (!options.silentMode) {
   $(".gallery-hol").hide();
   $(".galleryMessage").hide();
   $(".galleryLoading").show();
  }

  $.ajax({
    url: options.reqURL,
    success: function (data) { imgLibrary._ajaxSuccess(data, options) },
    error: function() { imgLibrary._ajaxError(options); }
  });
}

// Successful ajax load handler
imageLibrary.prototype._ajaxSuccess = function(data, options) {
  if (!options.silentMode) {
   $(".galleryLoading").hide();
   $(".gallery-hol").show();
  }
  
  options.callback.call(this, data, options);
}

imageLibrary.prototype.ERROR_TEXT = 'Error while loading request.&nbsp; <button>Try again</button>';

// Failure ajax load handler
imageLibrary.prototype._ajaxError = function(options) { 
  $(".galleryMessage").html(this.ERROR_TEXT).show()
    .find("button").click(function(){ imgLibrary.ajaxLoad(options) });

  $(".galleryLoading").hide();
}

//------------------------------------------------------------------------------
// IE8 bug fix
//------------------------------------------------------------------------------
// fixes IE8 overflow+opacity bug
imageLibrary.prototype.fixIE8 = function() {
  var al = $("#albumList");
  al.css({ "position": "absolute", 
           "clip":"rect(0,"+ String(al.width()-1) +"px,"+ String(al.height()-1) +"px,0)" });
}

