var loadURL;
var loadCap;
var loadUid;
var loadIndex;
var loadW;
var loadH;
var preloadURL;

// images
imgs = new Array();
as   = new Array();
	
//thumbs
var thumbId = 0;
var currImg = null;
var imgShown = false;

function registerImg(theURL, theCap, theUid, theIndex, w, h){

	if(imgs[theUid+""] == undefined){
		imgs[theUid+""] = new Array();
		
	}
	if (imgs[theUid+""][theIndex] == undefined){
		imgs[theUid+""][theIndex] = new Array(theURL, theCap, w, h);
	}
}
	
// define id for thumbnails
function defineId(id){
	thumbId = id;
}

function popDiv(theURL, theCap, theUid, theIndex, w, h, thumbImage){
	loadURL = theURL;
	loadCap = theCap;
	loadUid = theUid;
	loadIndex = theIndex;
	loadW = w;
	loadH = h;
	
	
	imgShown = true;
	
	if(thumbImage){
		var a = document.getElementById(thumbImage);
		aImg  = a.getElementsByTagName("img");
		fillPopDiv(aImg[0].src, theCap, theUid, theIndex, w, h)
	}
			
	for (var i = 0; i < imgs[theUid].length; i++){
	  var aid = '#' + theUid + '_' + i;
	  var a = $(aid);
	  if(aid == '#' + theUid + '_' + theIndex){
	    a.css('opacity' , 1);
	    a.addClass('shown');
	  } else {
	    a.css('opacity' , .4);
	    a.removeClass('shown');
	  }
	}
	
  	startLoader(theURL);
}
		  
function fillPopDiv(theURL, theCap, theUid, theIndex, w, h){
	var popD = document.getElementById("popup-" + theUid);

  	
  	if((theIndex + 1) < imgs[theUid].length){
  		var newIndex = theIndex + 1;
  	} else {
  		var newIndex = 0;
  	}
  	
  	var newURL = imgs[theUid][newIndex][0];
	var newCap = imgs[theUid][newIndex][1];
	var newW = imgs[theUid][newIndex][2];
	var newH = imgs[theUid][newIndex][3];
	
	str = "<a href=\"javascript:popDiv('"+ newURL+"', '"+ newCap+"', '"+theUid+"', "+(newIndex)+", "+newW+", "+newH+");\">";;	  	
  	str += "<img border='0' src='" + theURL + "' alt='' width='"+w+"' height='"+h+"' id='img"+theUid+"_"+theIndex+"'/>";
	str += "</a>";		
  	str += "</div>\n";
	
  	popD.innerHTML = str;
  	popD.style.display = "block";
  	$('#img'+theUid+'_'+theIndex).intoViewport({duration:  500});
}
		  
		  
function startLoader(theURL){
  	var preload = new Image();
	preload.onload = function(){
		fillPopDiv(loadURL, loadCap, loadUid, loadIndex, loadW, loadH);
	  	var preload = new Image();
		preload.src = preloadURL;	
	};
	preload.src = theURL;
}

$(document).ready(function(){
  for (uid in imgs) { 
    for (var i = 0; i < imgs[uid].length; i++){
	  var aid = '#' + uid + '_' + i;
	  var a = $(aid);
	  a.parent('td').css('background', '#000');
	  if(i == 0){
	    a.css('opacity' , 1);
	    a.addClass('shown');
	  } else {
	    a.css('opacity' , .4);  
	  }
	  a.mouseover(function(){
	    $(this).css('opacity' , 1);
	  });
	  a.mouseout(function(){
	    var a = $(this);
	    if(a.hasClass('shown')){
	      a.css('opacity' , 1);
	    } else {
	      a.css('opacity' , .4); 
	    }
	    
	  });
	}
  }
  
});
