/* ---------------------------------------------------------------------
                              Image Album
-----------------------------------------------------------------------*/
var imgLibrary; // instance of library

var active_id;  // active album

img_thmb = new Array();
img_title = new Array();
img_linkto = new Array();
img_keyid = new Array();
var moving = 0;
var num_elements = 0; // num of elements in list. Calculating in fnction below
var speed = 300; // speed of scrolling
var img_thmb_none = "images/transp.gif";


// imageLibrary class constructor
// properties:
//  handlerURL -- ajax handler page
//  perPage -- albums per scroller page
function imageLibrary(options) {
  imgLibrary = this;
  options = options || {};
  this.handlerURL = options.handlerURL || "";
  
  this.perPage = parseInt(options.perPage || $("table.list_items td.img_items").length);
  this.makeBlocks();
  num_elements = this.perPage;
  
  // arrows events
  $("#right_arrow img, #left_arrow img", "table.list_items")
   .mouseup(album_moving_stop)
   .mouseout(album_moving_stop);
  $("#right_arrow img", "table.list_items").mousedown(function() { album_moving_start();show_album_next_more(); });
  $("#left_arrow img", "table.list_items").mousedown(function() { album_moving_start();show_album_prev_more(); });

  $("div#albumlist").removeClass("albums_listNonJS");
  $("div#albumlist").addClass("albums_list");

  get_system_arrays();
  this.isEmpty = img_keyid.length<1;                      // empty gallery flag; 
  
  active_id = get_active_id();
  current_pos = get_current_pos();
  show_bullets();

  if(img_thmb.length > num_elements) $("div#scroll").removeClass("scroll_hide");
  $("div#scroll").addClass("scroll");

  show_album();

  // hide albums while displaying tagged items
  if (prGetParam("t")) 
   $(".albums_gallery").hide();

  // hide albums if nothing to show
  if (this.isEmpty)
    $(".prImageLibrary .albums_gallery").hide();
  
  if (active_id) {
   this.startPreloader();
   getDataByAjax("?id="+active_id);
  }
}

// create html blocks for album thumbnails 
imageLibrary.prototype.makeBlocks = function () {
 for (var i=0; i<this.perPage-1; i++) {
  b = $(".list_items .img_items:first");
  b.after(b.clone());
  b = $(".list_items .img_title:first");
  b.after(b.clone());
  b = $(".list_items tr:last td:first");
  b.after(b.clone());
 }
}

// 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(){} });
  }
 })
}

// Getting the values from HTLM elements
function get_system_arrays() {
  $("#img_album_bullets li").each(function(i){
    img_thmb[i] = get_img_src( $("div.thmb a", this).html() );
    img_title[i] = $(this).children("div.title").html();
    img_linkto[i] = $(this).children("div").children("a").attr("href");
    img_keyid[i] = $(this).attr("keyid");
  });
}

// Set values in album container
function show_album() {
  // helper function for cells class name
  function set_cell_class(action, className, index) {
   $(".list_items tr").each(function() {
     $("td", this).not("[class*=arrow]").eq(index)[action+"Class"](className);
   })
  }
  
  $("#scroll img").removeClass("sel");
  $("#scroll img").removeClass("loaded");

  var pos = "";
  var tbl = $("table.list_items");
  for(var i=0;i<num_elements;i++) {
    pos = i+current_pos;
    if(pos >= 0 && pos < img_thmb.length) {
//      set_cell_class("remove", "hidden", i)
      set_cell_class("remove", "empty", i)
      
      $("td.img_items", tbl).eq(i).find("img").css("background-image", "url('"+img_thmb[pos]+"')");
      $("td.img_items", tbl).eq(i).find("a").attr("href", img_linkto[pos]);
      $("div.img_title", tbl).eq(i).html(img_title[pos]);
      
      // dots
      $("#scroll img#scroll"+Math.floor(current_pos/num_elements)).addClass("sel");
      for( var act_scroll=0; active_id && act_scroll < img_keyid.length; act_scroll++)
       if (img_keyid[act_scroll] == active_id) {
         $("#scroll img#scroll"+Math.floor(act_scroll/num_elements)).addClass("loaded");
         break;
       }
       
      set_cell_class( img_keyid[pos]==active_id? "add" : "remove", "sel", i)
    }
    else {
      // set_cell_class("add", "hidden", i) 
      // Set unused cells empty. Uncomment string above to hide unused cell.
      set_cell_class("add", "empty", i);
      set_cell_class("remove", "sel", i)
    }
  }
  // FF2 table height bug fix
  if ($.browser.mozilla) {
   var m = navigator.userAgent.match(/Firefox\/(\d+)/i);
   if (m[1] < 3)
    $("table.list_items").height(Math.round(Math.random()*100));
  }
  
  // Hide the left arrow if number of items of albums is less then number of showed items
  if(pos-num_elements < 0) {
    $("#left_arrow").addClass("hidden");
    moving=0; // When the element become hidden, the onmouseup event is not working for it. So we should force var moving = 0;
  }
  else
    $("#left_arrow").removeClass("hidden");

  // Hide the right arrow if number of items of albums is less then number of showed items
  if(pos+1 >= img_thmb.length) {
    $("#right_arrow").addClass("hidden");
    moving=0;
  }
  else
    $("#right_arrow").removeClass("hidden");
    
  // ajax loading        
  $("td.img_items, td.img_title", ".list_items").unbind().not(".empty").click(albumClick);
  
  // sets current id to search form
  var sfid = $(".searchForm input[name=id]");
  if (sfid.length) sfid.attr("value", active_id);
}

// Get image SRC from html code
function get_img_src(image_html) {
  var src = image_html.match(/src=["']([^"']+)["']/i);
  return src ? src[1] : '';
}

function show_album_prev() {
  if(current_pos - num_elements >= 0)
    current_pos -= num_elements; 
  show_album();
}

function show_album_next() {
  if(current_pos + num_elements < img_thmb.length)
    current_pos += num_elements; 
  show_album();
}

function show_album_prev_more()
{
  if(moving == 1)
  {
    show_album_prev();
    setTimeout("show_album_prev_more()",speed);
  }
}

function show_album_next_more()
{
  if(moving == 1)
  {
    show_album_next();
    setTimeout("show_album_next_more()",speed);
  }
}

function album_moving_start() {
  moving = 1;
}

function album_moving_stop() {
  moving = 0;
}

// placing the bullets in scroll bar
function show_bullets() {
  for(var i=0;i<(img_thmb.length/num_elements);i++)   {
    var img = $("div#bullet_source img").clone().appendTo("div#scroll");
    img.attr("id","scroll"+i);
    img.attr("title", "Go to page "+(i+1));
    img.attr("onclick","current_pos="+i+"*num_elements;show_album();return false;");
    if(jQuery.browser.msie) 
     document.getElementById("scroll"+i).setAttribute("onclick", function() {
      current_pos=this.getAttribute("id").substring(6,10)*num_elements;show_album();
     });
  }
}

function get_active_id() {
   var rid=-1;
   var aid=prGetParam("id").replace(/E\d+C/gi, "") || -1;
   if(aid>-1){
        for(var i = 0; i < img_keyid.length; i++)
            if(img_keyid[i] == aid) {rid=aid; break;}
   }
   if(rid==-1&&img_keyid[0]) rid=img_keyid[0];
   return rid;
}

/* Calculating active position */
function get_current_pos() {
  for(var i=0; i<img_keyid.length; i++)
    if(img_keyid[i] == active_id) 
     return Math.floor(i/num_elements)*num_elements 
}

// album onclick event handler
function albumClick() {
  var target_url = $("a", this).get(0).href;

  getDataByAjax(target_url);
  var p = target_url.match(/[?&]id=(\d+)/i);
  active_id =  p ? p[1] : null // album id from link URL 
  show_album();
  return false;
}

// loads album content from specified url
function getDataByAjax(target_url) {
  var reqURL = target_url.split("#")[0]; // remove anchor (IE specific) from url.

  if (imgLibrary.handlerURL)
    reqURL = imgLibrary.handlerURL + '?' + reqURL.split("?")[1]; // remove path from url.
            
  if (prGetParam("fid"))
    reqURL += "&fid="+prGetParam("fid");    
 
  $("#loading_img").removeClass("nondisplay");
  $(".albumBorder").addClass("nondisplay");
  $.ajax({
    type:"GET",
    url: reqURL,
    success: loadSuccess,
    error: function() { loadError(reqURL); }
  });
}

// Success ajax-loader handler
function loadSuccess(data) {
  var input_file = data.substring(data.indexOf("<!--ALBUM START-->"),data.indexOf("<!--ALBUM END-->"));
  $("#album_items")[0].innerHTML = input_file;
  $("#loading_img").addClass("nondisplay");
  $(".albumBorder").removeClass("nondisplay");
  
  bindPagingLinks();
}

// Fail ajax-loader handler
function loadError(target_url) { 
  var ERROR_TEXT = 'Error while loading album. <button onclick="getDataByAjax(\''+target_url+'\');">Try again</button>';

  $("#loading_img").addClass("nondisplay");
  $(".albumBorder").removeClass("nondisplay");
  $("#album_items").html(ERROR_TEXT);
}

// set onclick handler for paging links
function bindPagingLinks() {
  $(".prImageLibrary div#pagingBottom a").click(function(){
    window.scrollTo(0, $("#loading_img").offset().top );
    getDataByAjax(this.href);
    return false;
  });

  $(".prImageLibrary div#pagingTop a").click(function(){
    window.scrollTo(0, $("#loading_img").offset().top );
    getDataByAjax(this.href);
    return false;
  });
}

