function changeImg(change) {
  //break if no images
  if(total<1){
	return;
  }
  
  //clear image for slow connections so you know something happened
  if (img != start_img){
    //document.getElementById('main_image').style.display = 'none';
	//document.getElementById('image_name').innerHTML = "";
	//document.getElementById('image_descr').innerHTML = "";
  }
  	
  // figure out which image we're going to
  if (isNaN(change)) {
    
	if (change == 'next') {
      start_img = 0;
      img++;
      if (img > total)
        img = 1;
    } else if (change == "prev") {
      start_img = 0;
      img--;
      if (img == 0)
        img = total;
    } 
	
  } else {
	start_img = 0;
    img = parseInt(change);
  }
  //change the main image
  changeImgURL(img);
  //Show main image
  //swapTools(0);
}


//change the main image
function changeImgURL(image){
	if(typeof dataContainer[image] != "undefined"){
		//SET FADE PARAMS
		
		mainIMGobj = document.getElementById('main_image');
		filtersupport=mainIMGobj.filters;
		blenddelay=(filtersupport)? mainIMGobj.filters[0].duration*1000 : 0;
		if (filtersupport)	mainIMGobj.filters[0].apply()

		
		//IF cashed
		if("object" == typeof IMGcash[image]){
			mainIMGobj.setAttribute('src', IMGcash[image].src);
		}else{
			url = gs_img_url + dataContainer[image][0] + "_med.jpg";
			mainIMGobj.setAttribute('src', url);
			cashImage(image);
		}
		
		//VIEW STATISCTICS
		/*
		this.preloader = function (){
		}
		this.redyFync = function(){
			dataContainer[img][5]++;
		}
		var setStat = new Ajax("albumas_setViewStat.php", "klas_id=" + confKlasID + "&fot_id=" + dataContainer[img][0] + "&uid=" + confUID + "&new=" +  dataContainer[img][10], preloader, redyFync); //reqest object
		setStat.makeRequest();
		*/
	}
}

//IMAGE PARAMS
function setImgParams(){
		//IMAGE DATA
		//if(document.getElementById('img_num'))document.getElementById('img_num').innerHTML = img;
		//if(document.getElementById('img_total'))document.getElementById('img_total').innerHTML = total;
		//if(document.getElementById('image_name'))document.getElementById('image_name').innerHTML = dataContainer[img][1];
		//if(document.getElementById('image_descr'))document.getElementById('image_descr').innerHTML = dataContainer[img][2];
		
		//SIZE
		if("object" == typeof IMGcash[img]){
			var width, height;
			if(IMGcash[img].width > MaxWidth){
				this.width = MaxWidth;
				this.height = Math.floor((MaxWidth/IMGcash[img].width)*IMGcash[img].height);
			}else{
				this.width = IMGcash[img].width;
				this.height = IMGcash[img].height;
			}
			mainIMGobj.setAttribute('width', this.width);
			mainIMGobj.setAttribute('height', this.height);
		}
		
		//FADE
		if (filtersupport)	mainIMGobj.filters[0].play();
}

    
function addEvent(elm, evType, fn, useCapture) {
  // cross-browser even handling for IE5+, NS6+ and Mozilla/Gecko
  if (elm.addEvenListener) {
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent) {
    var r = elm.attachEvent('on' + evType, fn);
    return r;
  } else {
    elm['on' + evType] = fn;
  }
}

// build thumbnails
function buildThumbs() {
	if (!document.getElementById) return;
	// remove all thumbnails
	clearElem('thumbs');
	
	//set big image params
	setImgParams();
	
	//if empty gallery
	if(total<=1){
		return;
	}
	
	
	var newLink = document.createElement('a');
	newLink.id="prev";
	document.getElementById('thumbs').appendChild(newLink);
	var rod = document.createElement('img');
    rod.src ="images/trikRaudk.gif";
	rod.style.align ="absmiddle";
	var linkas = document.getElementById('prev');
    linkas.appendChild(rod);
	  	
	// if galery has more than 5 images, want to build all 5
	if (total >= 5){
		for (var i = img-2; i <= img+2; i++) {
			n = i <= 0 ? n = total + i : i > total ? n = i - total : i;
			constructThumb(n);
			cashImage(n);
		}
	
	// if galery has less than 5 images, want to only build up to the number
	} else if(total >= 1) {
		for (var n = 1; n <= total; n++) {
			constructThumb(n);
			cashImage(n);
		}
	}
	
	var newLink = document.createElement('a');
	newLink.id="next";
	document.getElementById('thumbs').appendChild(newLink);
	var rod = document.createElement('img');
    rod.src ="images/trikRaud.gif";
	rod.style.align ="absmiddle";
	var linkas = document.getElementById('next');
    linkas.appendChild(rod);
	
	//add click event on links
	addListeners();
	
	//build img number <select> options
	//buildSelector()
	
	
}


//PUT IMG IN CASH
function cashImage(img){
	if("object" != typeof IMGcash[img]){
		var url = gs_img_url + dataContainer[img][0] + "_med.jpg";
		IMGcash[img] = document.createElement('img');
		IMGcash[img].setAttribute('src', url);
	}
}


// CONSTRUCT AND PUT THUMB INTO THUMB DIV
function constructThumb(n){
	  /* 
	  	thumb structure:
	  	<div id=thumbwrap> <div class=icon1></div> <div class=icon2></div> <img src=thumb> </div> 
	  */
	  //ADD LINK
      var newLink = document.createElement('a');
      newLink.id = 'link_' + n;
      newLink.style.cursor = 'pointer';
	  document.getElementById('thumbs').appendChild(newLink);
	  
	  //ADD THUMB
      var newThumb = document.createElement('img');
      newThumb.src = gs_img_url + dataContainer[n][0] + "_thumb.jpg";
      newThumb.className = n == img ? "currThumb" : "otherThumb";
	  var linkas = document.getElementById('link_' + n);
      linkas.appendChild(newThumb);
}


//FILL SELECT options with image numbers
function buildSelector(){
	selectCtrl = document.getElementById('image_num');
	remOptions(selectCtrl);

	for (i = 0; i < total; i++) {
		selectCtrl.options[i] = new Option(i+1);
		selectCtrl.options[i].value=i+1;
	}
	
	if(total>0)selectCtrl.options[0].selected = true;
}


//REMOVE SELECT options
function remOptions(elemID){
	for (var i = elemID.options.length; i >= 0; i--) {
		elemID.options[i] = null; 
	}
}


//CLEARS all elemet childs
function clearElem(elemID){
	var elem = document.getElementById(elemID);
  	while (elem.childNodes[0]) {
    	elem.removeChild(elem.childNodes[0]);
  	}
}



// add LISTENERS to all thumb links, when clicked on do handLink function
function addListeners() {
  if (!document.getElementsByTagName) return;
  var thumb_links = document.getElementById('thumbs').getElementsByTagName('a');
  for (var i = 0; i < thumb_links.length; i++) {
    if(thumb_links[i].id=="next")addEvent(thumb_links[i], 'click', function(){changeImg("next")}, false);
  	else if(thumb_links[i].id=="prev")addEvent(thumb_links[i], 'click', function(){changeImg("prev")}, false);
  	else addEvent(thumb_links[i], 'click', handleLink, false);
  }
}



// when a link is clicked on, you get its id# and send that to changeImg function
function handleLink(e) {
  var target = window.event ? window.event.srcElement : e ? e.target : null;
  if (!target) return;
  while (target.nodeName.toLowerCase() != 'a' && target.nodeName.toLowerCase() != 'body')
    target = target.parentNode;
  
  //get the id of the link, remove the link_ part and send to changeImg
  changeImg(parseInt(target.id.replace('link_','')));
}


// rewrite the page location so you can refresh the image that you're currently on (only seems to work in FF right now)
function changeUrl() {
  window.location.replace(window.location.href.replace(/img=[0-9]+/, 'img=' + img));
}



//SLIDESHOW
function SlideShow(){
	if(doSlide==1){
		var next = img+1;
		if (next > total) next = 1;
		//if already cashed show
		if("object" == typeof IMGcash[next] && IMGcash[next].width > 0){
			changeImg(next);
		}
		//set delay
		slideTimeout = setTimeout("SlideShow()", slidespeed+blenddelay);
	}
}

//TURN SLIDESHOW ON/OFF
function switchSlideShow(){
	if(doSlide==0){
		doSlide=1;
		slideTimeout = setTimeout("SlideShow()", 1000);
		document.getElementById('slidetool').setAttribute('src', 'Images/slidepause.gif');
		document.getElementById('slidetool').setAttribute('alt', 'Sustabdyti "SlideShow" rėžimu');
		document.getElementById('slidetool').setAttribute('title', 'Sustabdyti "SlideShow" rėžimu');
	}else{
		clearTimeout(slideTimeout);
		doSlide=0;
		document.getElementById('slidetool').setAttribute('src', 'Images/slideplay.gif');
		document.getElementById('slidetool').setAttribute('alt', 'Rodyti nuotraukas "SlideShow" rėžimu');
		document.getElementById('slidetool').setAttribute('title', 'Rodyti nuotraukas "SlideShow" rėžimu');
	}
	return false;
}



//TOOLS SWITCH
function swapTools(tool){
	//hidel other all tools
	for(var i = 0; i <= 3; i++){
		document.getElementById('tool_' + i).style.display = 'none';
	}
	//show seletd tool
	document.getElementById('tool_' + tool).style.display = 'block';
	return false;
}

