var prevX = 0;
var currImage = 1;
var startThumb = 0;
var endThumb = 0;
var currPage = 0;
var countThumbs = 0;
var thumbsPerPage = 0;
var countImages = 0;  
var countPages = 0;  
var showGridStatus = false;  

 function getFlashMovie(movieName) {
  var flash;
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  if (isIE) {
     flash = document.getElementById(movieName);
  } else {
     flash = document[movieName];
  }
  return flash;
 }
 
 function flashLoadImage(s) {
   try {
   getFlashMovie("image").loadImage(s);
   } catch(err) {}
  
 }


function urlencode(s)                   
{                   
  s = escape(s);
  s=s.replace("+", "%2B");
  s=s.replace("/", "%2F");
  return s;
}

function pathurlencode(s)                   
{                   
  s = escape(s);
  s=s.replace("+", "%2B");
  return s;
}

function easyNetAlbum_fullScreen()
{
	var agt=navigator.userAgent.toLowerCase();
   	var is_ie   = (agt.indexOf("msie") != -1);
	var features;
	if (is_ie)
	{
	 	features="fullscreen=yes";
	}
	else
	{
		features="toolbar=0,scrollbars=1,location=0,border=0,status=0,menubar=0,";
		features=features + 'outerHeight=' + screen.availHeight + ',outerWidth=' + (screen.availWidth-2);
	}
	var w=window.open(location.href,'fullscreen',features);
	if (w!=null)
	{
		if (!is_ie && screen.availLeft!=null && screen.availTop!=null)
			w.moveTo(screen.availLeft,screen.availTop);
		w.focus();
	}
}
function openFullscreen(href)
{
	var agt=navigator.userAgent.toLowerCase();
   	var is_ie   = (agt.indexOf("msiexx") != -1);
	var features;
	if (is_ie)
	{
	 	features="fullscreen=no";
	}
	else
	{
		features =  'scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=yes';
		features += ',width=' + screen.availWidth + ',height=' + screen.availHeight;    
    features += ',screenX=0,screenY=0,top=0,left=0'; 
	}
	var w=window.open(href,'fullscreen2',features);
	if (w!=null)
	{
		if (!is_ie && screen.availLeft!=null && screen.availTop!=null)
			w.moveTo(screen.availLeft,screen.availTop);
		w.focus();
	}
}

function openAlbumMap(url) {  // ---> change easynetalbum to dynamic value
   window.open(webPath + '/index.php?p=albummap&a=' + url ,'mappos','resizeable=yes,width=' + getViewportWidth() + ',height=' + getViewportHeight());
}
function getViewportWidth() {
	var width = 0;
	if( document.documentElement && document.documentElement.clientWidth ) {
		width = document.documentElement.clientWidth;
	}
	else if( document.body && document.body.clientWidth ) {
		width = document.body.clientWidth;
	}
	else if( window.innerWidth ) {
		width = window.innerWidth - 18;
	}
	return width;
}
 
function getViewportHeight() {
	var height = 0;
	if( document.documentElement && document.documentElement.clientHeight ) {
		height = document.documentElement.clientHeight;
	}
	else if( document.body && document.body.clientHeight ) {
		height = document.body.clientHeight;
	}
	else if( window.innerHeight ) {
		height = window.innerHeight - 18;
	}
	return height;
}
 
function vIE(){return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;}

function calcThumbsPerPage() {
   if ((vIE() == -1) || (vIE() >= 7)) { // non IE and IE newer than 6
       rc = Math.floor((getViewportWidth() - 64) / 93);  // 66 = 2 gange pil bredde (34) ) + 4 gange padding (4)
   } else { // IE up to 6
       rc = Math.floor((getViewportWidth() - 69) / 93);  // 66 = 2 gange pil bredde (34) ) + 4 gange padding (4)
   }
   return rc;
}

function shouldMaximize() {
  rc = false;
  if ((screen.availWidth > getViewportWidth() +  20) || (screen.availHeight > getViewportHeight() +  20)){
     rc = true;
  } else {
     rc = false;
  }
  return rc;
}

function writeFlash() {
   var flashWidth = getViewportWidth() - 2; 
   var flashHeight = getViewportHeight() - 50; 
   if (isVisible("thumbs") && (showGridStatus == false)) {
      flashHeight = flashHeight - 93;
   } 
 

   // flash not yet on the screen the add it
   if (document.getElementById('noflash')) { 
      var flashParams = {
         wmode: "transparent", 
         swliveconnect: "true",
         bgcolor: '#000000'
        }; 
      var flashVars = {
        loadImage: urlencode(imagePath[currImage])
      };
      var htmlAttrs= {
        styleclass: "flashimage"
      }
      swfobject.embedSWF(flashFilename, "image", flashWidth, flashHeight, "9.0.0","common/expressInstall.swf", flashVars, flashParams, htmlAttrs);
      if (swfobject.hasFlashPlayerVersion("9")) {
          document.getElementById("image").style.zIndex = -1;
          document.getElementById("catchkeys").style.height =  flashHeight+"px";
          document.getElementById("catchkeys").style.width = flashWidth+"px";
          document.getElementById("catchkeys").style.background = "url(" + blankImage + ")";
          document.getElementById("catchkeys").style.backgroundRepeat="repeat"
          document.getElementById("catchkeys").style.display = "block";
       } else {
          document.getElementById("noflash").style.display = "block";
          document.getElementById("catchkeys").style.display = "none";
       }
   } else { // flash was already on the screen, so just resize it.
     document.getElementById("catchkeys").style.height =  flashHeight+"px";
     document.getElementById("catchkeys").style.width = flashWidth+"px";
  	document.getElementById("image").height = flashHeight+"px";
  	document.getElementById("image").width = flashWidth+"px";
     document.getElementById("catchkeys").style.display = "block";
   }
}

function isVisible(x) {
	xTog = document.getElementById(x);
	xState = xTog.style.display;

	// if(xState=='none') xState = 'table';
	if(xState=='none') rc = false;
	else rc = true;
	return rc;
}

function toggle(x) {
	xTog = document.getElementById(x);
	xState = xTog.style.display;

	// if(xState=='none') xState = 'table';
	if(xState=='none') xState = 'block';
	else xState = 'none';
	xTog.style.display = xState;
}

function toggleSet(x,state) {
	xTog = document.getElementById(x);
	if (state) {
       xState = 'block';
     } else {
       xState = 'none';
     }
	xTog.style.display = xState;
}

function toggleThumbs() {
         toggle('thumbs'); 
         toggle('thumbsinfo');
         toggle('thumbsprevlink');
         toggle('thumbsnextlink');
         writeFlash();
}

function toggleThumbsSet(x) {
  toggleSet('thumbs',x); 
  toggleSet('thumbsinfo', x);
  toggleSet('thumbsprevlink', x);
  toggleSet('thumbsnextlink', x);
         writeFlash();
}

function showRows() {
     if (showGridStatus) {
       rc = Math.floor(document.getElementById('image').offsetHeight / 93);
     } else {
       rc = 1;
     }
     return rc;
}

function thumbIsOnPageNumber(x) {
   i = thumbsPerPage * showRows();
   return Math.floor( (x + i -1) / i);
}

function showGrid() {
  showGridStatus = ! showGridStatus;
  displayThumbs( thumbIsOnPageNumber(currImage) );
  toggleThumbsSet(true); 
  
}
function displayThumbs(x) {
     var i=0;
     currPage = x;
     ShowNoOfThumbs = thumbsPerPage * showRows();
     if (x == 0) {
       startThumb = 1;
       endThumb = countThumbs;
     } else {
       startThumb = (x-1) * ShowNoOfThumbs + 1;
       endThumb = x * ShowNoOfThumbs;
       if (endThumb > countThumbs) {
          endThumb = countThumbs;
       }
     }
     for (i=1;i<=countThumbs;i++) {
         xs = String(i);

         if ((startThumb <= i) && (i <= endThumb)) {
            xState = "";
            document.getElementById("thumb" + xs).src = thumbPath[i];
         } else {
            xState = "none";
         }
   	    document.getElementById("image" + xs).style.display = xState;
     

     }
     closeThumbs = "<a href=\"javascript:void(0);\" onclick=\"toggleThumbsSet(false);\">" + 
                   "<img src='" + webPath + "/common/images/icon_fail.gif' border=0></a>";
                   if (showGridStatus) {
                     gridIcon = "icon_down";
                   } else {
                     gridIcon = "icon_up";
                   }
     gridThumbs = "<a href=\"javascript:void(0);\" onclick=\"showGrid();\">" + 
                   "<img src='" + webPath + "/common/images/" + gridIcon + ".png' border=0></a>";
     document.getElementById("thumbsinfo").innerHTML =  _language["Thumbs"] + " " + startThumb + " - " + endThumb + " " + _language["of"] + " " + countThumbs + "&nbsp;&nbsp;" + closeThumbs + gridThumbs;
     document.getElementById("thumbs").style["width"] = (getViewportWidth() - 2 - 62) +"px";
     document.getElementById("thumbsinfo").style.bottom = (document.getElementById('thumbs').offsetHeight - document.getElementById('thumbsinfo').offsetHeight +25) +"px";

     if (startThumb > 1) {
          document.getElementById("prevthumb").src = webPath + "/common/images/prevthumb.gif";
          document.getElementById("prevthumblink").href = "javascript: displayThumbs(" + (x-1) + ");";
     } else {
          document.getElementById("prevthumb").src = webPath + "/common/images/noprevnextthumb.gif";
          document.getElementById("prevthumblink").href = "javascript: displayThumbs(" + x + ");";
     }
     if (endThumb < countThumbs) {
          document.getElementById("nextthumb").src = webPath + "/common/images/nextthumb.gif";
          document.getElementById("nextthumblink").href = "javascript: displayThumbs(" + (x+1) + ");";
     } else {
          document.getElementById("nextthumb").src = webPath + "/common/images/noprevnextthumb.gif";
          document.getElementById("nextthumblink").href = "javascript: displayThumbs(" + x + ");";
     }
}

function keyboardListener(event){

   if(!event){
      //for IE
      event = window.event;
   }
		switch (event.keyCode){
			//case 27: case 88: case 67: this.close(); break;
			case 37: case 38: case 80: prevImage(); break;	
			case 39: case 40: case 78: nextImage(); break;
			case 71: case 103: showGrid(); break;
			case 72: case 104: toggle('helpinfo'); toggleSet('helpsplash',false); break;
			case 73: case 105: toggle('exifinfo'); break;
			case 84: case 116: toggleThumbs(); 
                                  break;
			default:
               	switch (event.charCode){
                       case "g", "G": showGrid(); break;
                       case "h", "H": toggle('helpinfo'); toggleSet('helpsplash',false); break;
                       case "i", "I": toggle('exifinfo'); break;
                       case "t", "T": toggleThumbs();
                                      break;
                    }

          }
}

function resizeListener(event) {
   thumbsPerPage = calcThumbsPerPage();
   countPages = Math.floor((countImages - 1) / thumbsPerPage) + 1;  
   writeFlash();
//alert("resizer" + getViewportHeight() + "/" + document.getElementById('image').offsetHeight);
   try {
     getFlashMovie("image").resize();
   } catch(err) {
   }
   
   displayThumbs( thumbIsOnPageNumber(currImage) );
   if (shouldMaximize() == false) {
      if (hideHelpOnMaximize) {
         toggleSet('helpsplash',false);
      }
   }
}

function resizeListenerNoFlash(event) {
   if (shouldMaximize() == false) {
      if (hideHelpOnMaximize) {
         toggleSet('helpsplash',false);
      }
   }
}
function nextImage() {
  if (currImage < countThumbs) {
     currImage = currImage + 1;
     displayImage(currImage);
  }
}

function prevImage() {
  if (currImage > 1) {
     currImage = currImage - 1;
     displayImage(currImage);
  }
}

function displayImage(x) {
     if (prevX > 0) {
        document.getElementById("imagethumb" + prevX).className = "imagethumb";
     } 
     document.getElementById("imagethumb" + x).className = "imagethumbactive";
     prevX = x; 
     lastGridStatus = showGridStatus ;
     showGridStatus = false;
   //  document.getElementById("thisimage").src = imagePath[x];
     flashLoadImage (imagePath[x]);
     
   	desc =    imageInfo[x][0];
	fullurl = imageInfo[x][1];
	exif =    imageInfo[x][2];
 	mappos =  imageInfo[x][3];

     if (mappos != "") {       
       var showMapposHTML = "&nbsp;&nbsp;<a href=\"javascript:void(0);\" " + 
                            " onclick=\"window.open('" + 
                            mappos + 
                            "','mappos','resizeable=yes,width=620,height=420')\">" +
                            "<img src='" + webPath + "/common/images/geotagged.gif' border=0 title='" + _language['Position on map'] + "' alt='Position on map'></a> ";
     } else {
       var showMapposHTML = "";
     } 
     if (fullurl == "") {
	     var savefullHTML = ""; 
     } else {
	     var savefullHTML = "<a href='" + fullurl + "' target='_blank'><img src='" + webPath + "/common/images/save.gif' " + 
                                  " alt=\"" + _language['Save full sized picture'] + "\" title=\"" + _language['Save full sized picture'] + "\" border=0></a>";
     }                            
     var showexifHTML = "<img src='" + webPath + "/common/images/info.gif' border=0 " + 
                          "onMouseOver=\" document.getElementById('exifinfo').style.display='block';\" " + 
                          "onMouseOut=\" document.getElementById('exifinfo').style.display='none';\" " +
                          " alt=\"" + _language['Show image information'] + "\" title=\"" + _language['Show image information'] + "\" border=0></a>";
     var showhelpHTML = "<img src='" + webPath + "/common/images/help.gif' border=0 " + 
                          "onMouseOver=\" document.getElementById('helpinfo').style.display='block';\" " + 
                          "onMouseOut=\" document.getElementById('helpinfo').style.display='none';\" " +
                          " alt=\"" + _language['Show help information'] + "\" title=\"" + _language['Show help information'] + "\" border=0></a>";

     document.getElementById("pageinfo").innerHTML = _language['Shows image'] + " " + x + " " + _language['of'] + " " + countThumbs  + "&nbsp;&nbsp;" + savefullHTML + "&nbsp;&nbsp;" + showexifHTML + showMapposHTML + "&nbsp;&nbsp;" + showhelpHTML ;

	var exifTable = exif.split("\t");
     exifHTML = "<table>";
     imageDescription = "";
     for(var icount = 1; icount < exifTable.length ; icount = icount + 2) { 
        var s1 = exifTable[icount];
        exifHTML = exifHTML + "<tr><td>" + exifTable[icount] + "</td><td>" + exifTable[icount+1] + "</td></tr>";
        if (exifTable[icount]  == "Description") {
             imageDescription = exifTable[icount+1];
        }
        
     }	
     exifHTML = exifHTML + "</table>";
     document.getElementById("exifinfo").innerHTML = exifHTML || '';
     document.getElementById("captioninfo").innerHTML = imageDescription || '';
     if (imageDescription == "") {
        toggleSet("captioninfo", false);
     } else {
        toggleSet("captioninfo", true);
     }
     currImage = x;
     
     if ((thumbIsOnPageNumber(x) !== currPage) || (lastGridStatus !== showGridStatus)) {
        displayThumbs( thumbIsOnPageNumber(x) );
     }

     if (currImage < countThumbs) {
        x = currImage + 1;
        document.getElementById("nextimage").src = imagePath[x];
     }
     if (currImage > 1) {
        x = currImage - 1;
        document.getElementById("previmage").src = imagePath[x];
     }
}

function thumbContextMenu(i) {
    show_contextmenu(event,"<a href='" + imageInfo[i][4] + "'>" + _language["Right click here and select Copy Shortcut to copy a link to this photo"] + "</a>","");
}

function displayImageInFrame(album, image, type) {
   type = typeof(type) != 'undefined' ? type : 'screen';
       
   var flashWidth = Math.floor((getViewportWidth() * 0.9)); 
   var flashHeight = Math.floor((getViewportHeight() * 0.9)) ; 
   //document.getElementById("imagepopupspan").innerHTML = "<img src='" + webPath + "/cache/" + album + "/_" + type + "/" + image + "'>";
      var flashParams = {
         allowScriptAccess: "always", 
         quality: "best",
         wmode: "transparent", 
         swliveconnect: "true",
         bgcolor: '#000000'
        }; 
      var flashVars = {
        loadImage: webPath + "/cache/" + album + "/_" + type + "/" + image
      };
      var htmlAttrs= {
        styleclass: "imagepopup"
      }
   //  document.getElementById("imagepopup").style.height = flashHeight+"px";
  //	document.getElementById("imagepopup").style.width = flashWidth+"px";
     swfobject.embedSWF(flashFilename, "imagepopup", flashWidth, flashHeight, "9.0.0", null, flashVars, flashParams, htmlAttrs);
     if (swfobject.hasFlashPlayerVersion("9")) {
         toggleSet("imagepopup", true);
         document.getElementById("imagepopup").style.height = flashHeight+"px";
         document.getElementById("imagepopup").style.width = flashWidth+"px";
         document.getElementById("imagepopupcatch").style.background = "url(" + blankImage + ")";
         document.getElementById("imagepopupcatch").style.backgroundRepeat="repeat"
         document.getElementById("imagepopupcatch").style.height =  getViewportHeight()+"px";
         document.getElementById("imagepopupcatch").style.width = getViewportWidth()+"px";
         toggleSet("imagepopupcatch", true);
         document.getElementById("imagepopupcatch").focus();
       } else {
          toggleSet("imagepopup", true);
          toggleSet("imagepopupnoflash", true);
          toggleSet("imagepopupcatch", false);
       }
}
