// iView - Image Viewer
var ivStyle = 'OP';	//OPacity  TRansparency	 NOne STyled

var ivLoadingDiv;
var ivLoadingID = 'ivLoading'; 
 
var ivStyledDiv;
var ivStyledID = 'ivStyled'; 

var ivMaskDiv;
var ivMaskID = 'ivMask'; 
 
var ivTransDiv;
var ivTransID = 'ivTrans'; 

var ivMainDiv;
var ivMainID = 'ivMain';

var ivIE6 =  (document.all && !window.opera && !window.XMLHttpRequest);
var ivIE6Timer;
var ivIE6MainTop;	// SO IE6Fix can update the property



var ivOpacity = 15;	

var ivLinks = new Array();
var ivLinkCount = 0;
var ivCaptions = new Array();
var ivCurLinkIndex = 0;;

var ivImgCache = new Image();
var ivImgPreLoad = new Image();
var ivImgInfo;

var ivSSEnabled = true;;
var ivSSTickCounter = 0;
var ivSSTickChange=5;
var ivSSTimer = false;
var ivSSTickInterval = 50;
var ivSSRunning = false;
var ivSSWrap = true;
var ivLanguage='EN';
var ivTextBack;
var ivTextNext;
var ivTextStop;
var ivTextPlay;
var ivTextClose;

var ivPrevHTML ;
var ivNextHTML;
var ivSSPlayHTML;
var ivSSStopHTML;
var ivSSPlayDisabledHTML
var ivLastWidth=0;
var ivLastHeight=0;
var ivLastTop=10000;
var ivLockTop=true;
var ivLockHeight = ! ivLockTop;

var ivHTTPObject;
var ivHTTPUrl;
// ================================================================================
// Image Cache OnLoad handler
ivImgPreLoad.onload = function() {
  
}
// ---------------------------------------------------------
ivImgCache.onload = function() {
	 
	if(ivLoadingDiv) document.body.removeChild(ivLoadingDiv);
  	var ivCanPlay = ( ivSSEnabled &&  ivLinkCount>1 );

 	// When the cache finishes loading, swap the main img with it
 	//alert('W:'+ivImgCache.width+', H:'+ivImgCache.height)
	var imgW = ivImgCache.width;
	var imgH = ivImgCache.height;

	// Get the available screen size
     scH = ivClientHeight();
     scW = ivClientWidth();

	var ivTBHeight = 30;
	if (ivCanPlay) ivTBHeight += 20;
	// Figure out the max image height and width we can get in the popup window
	var maxH = parseInt(scH*.8) - ivTBHeight;
	var maxW = parseInt(scW*.8);


	var factor;
	// and re-factor the image dimensions to fit
	if (imgH>maxH) {
       	factor = maxH/imgH;
       	imgH=parseInt(imgH*factor);;
       	imgW=parseInt(imgW*factor);;
 	}
	if (imgW>maxW) {
       	factor = maxW/imgW;
       	imgH=parseInt(imgH*factor);;
       	imgW=parseInt(imgW*factor);;
 	}
	var divWidth =imgW +12;;
	
	// Not too small!
	if (divWidth < 400)   divWidth  =400;
	// Try to keep multiple image  widths the same
	if (divWidth < ivLastWidth)   divWidth  =ivLastWidth;
	ivLastWidth = divWidth;
	

	var textHeight = 0;

     if (ivCaptions[ivCurLinkIndex] && ivCaptions[ivCurLinkIndex].length){
		var charsPerLine = divWidth/6 ;
		var lines=Math.round(ivCaptions[ivCurLinkIndex].length/charsPerLine + .5);
		var textHeight = (20 * lines);
          maxH -=  textHeight;
 	}

	//alert(lines);
	var divHeight =imgH + ivTBHeight + textHeight;

	// Try to keep multiple image  height the same
	if (ivLockHeight){
		if (divHeight < ivLastHeight)   divHeight  =ivLastHeight;
		ivLastHeight= divHeight;	
	}
	
	var divLeft = parseInt( (scW-divWidth)/2);
	var divTop = parseInt( (scH-divHeight)/2);
	
	// Try to keep top the same
	if (ivLockTop){
		if (divTop > ivLastTop)   divTop  =ivLastTop;
		ivLastTop= divTop;
	}
	var divStyle='';


    ivIE6MainTop = divTop;
	ivMainDiv.style.left =  divLeft + 'px';
    ivMainDiv.style.top = divTop + 'px';
    ivMainDiv.style.width = divWidth + 'px';
    ivMainDiv.style.height = divHeight + 'px';


	var ivTDWidth = (ivCanPlay)  ?  parseInt(100/4) :  parseInt(100/3);
	var tdStyle = 'style="width:' + ivTDWidth + '%;"';
	// Toolbar
     var tbHtml  = '<div id="ivToolbar"  ><table><tr>';
	
	// PREV
	var ivPrev =  (ivLinkCount>1 && ivCurLinkIndex > 0 && ! ivSSRunning)? ivPrevHTML : '&nbsp;';
	tbHtml  += '<td ' + tdStyle + ' id="ivTDPrev">' + ivPrev + '</td>';

     // CLOSE
	var ivClose =  '<a href="#" title="Close Viewer"  id="ivClose" onclick="ivClose();return false;">' + ivTextClose + '</a>'  ;
	tbHtml  += '<td ' + tdStyle + 'id="ivTDClose">' + ivClose + '</td>';

	var imgNo = ivCurLinkIndex + 1;
	ivImgInfo = '<span id="ivImgInfo">(' + imgNo + '/' + ivLinkCount+ ')<span>&nbsp;';
	
	var ivLast = ivLinks.length-1;
	//alert(  ivCurLinkIndex + ':'+ ivLast + ':' + ivCanPlay );
	// PLAY/STOP
	if ( ivCanPlay ){
		
		if (ivCurLinkIndex < ivLast || ivSSWrap ) var ivPlay =   (ivSSRunning) ? ivSSStopHTML : ivSSPlayHTML ;
		else  var ivPlay=ivSSPlayDisabledHTML;
		tbHtml  += '<td ' + tdStyle + 'id="ivTDPlay">' + ivImgInfo + ivPlay + '</td>';
	}

	// NEXT
	var ivNext =  (ivLinkCount>1 && ivCurLinkIndex < ivLinks.length-1 && ! ivSSRunning) ? ivNextHTML : '&nbsp;';
	tbHtml  += '<td ' + tdStyle + 'id="ivTDNext">' + ivNext + '</td>';

	tbHtml  += '</tr></table>';

	if ( ivCanPlay) tbHtml  += '<div id="ivSSTicker" ></div> ';
	// Caption
	var ivCaption ='';	
	if (ivCaptions[ivCurLinkIndex] && ivCaptions[ivCurLinkIndex].length){
      	 ivCaption =  '<div id="ivCaption">' + ivFormatCaption(ivCaptions[ivCurLinkIndex]) + '</div>';
	}

     tbHtml  += '</div>';

	 var html = '';
     html += tbHtml;
     var imgStyle='width:' + imgW + 'px; height:' + imgH + 'px;';
     html += '<center><img id="ivImage" style="' + imgStyle + '"  src="' +  ivImgCache.src + '"></center>' + ivCaption;

	 // alert(html);
     ivMainDiv.innerHTML = html;
}
// ------------------------------------------------------------
function ivFormatCaption(caption){
	arText =  caption.split('|'); 
	if (arText.length==1) var html =  '<b>' + caption + '</b>';
	else  var html = '<b>' + arText[0] + ': </b> ' + arText[1];
 	return(html);
}
// ------------------------------------------------------------
function ivSetLanguage(){

	if (ivLanguage=='EN'){
		ivTextBack='Back';
		ivTextNext='Next';
		ivTextStop='Stop';
		ivTextPlay='Play';
		ivTextClose ='Close';
	}
	else if (ivLanguage=='FR'){
		ivTextBack='Revers';
		ivTextNext='Suivant';
		ivTextStop='Arręter';
		ivTextPlay='Commencer';
		ivTextClose ='Fermer';
	}
	
	ivPrevHTML = '<a href="#" title="Previous Image"  id="ivPrev" onclick="ivSkipImage(-1);return false;">' + ivTextBack + '</a>';
	ivNextHTML = '<a href="#" title="Next Image"  id="ivNext" onclick="ivSkipImage(1);return false;">' + ivTextNext + '</a>';
	ivSSPlayHTML = '<a href="#" title="Play"  id="ivSSPlay" onclick="ivSSPlay();return false;">' + ivTextPlay + '</a>';
	ivSSStopHTML = '<a href="#" title="Stop"  id="ivSSStop" onclick="ivSSStop();return false;">' + ivTextStop + '</a>';
	ivSSPlayDisabledHTML = '<span id="ivSSPlayDisabled" >' + ivTextPlay + '</span>';
}
	
// ------------------------------------------------------------
// View image(s) based on <A> tags, ie <a href="imageFile" onclick = "return(iView(this));">thumbnail</a>
function iView(thisLink, ignoreOthers){
	if (! ivBrowserOK()) return(true);   // ie no good browsers so show via new page
		
	ivSetLanguage();
	// Gathe rall page links with iView onclick handler
	if (ignoreOthers){
			ivLinks[0]=thisLink;
			elImg= thisLink.getElementsByTagName("IMG")
			if (elImg) ivCaptions[0]=elImg[0].alt;
      ivCurLinkIndex= 0;
      ivLinkCount=1;
  }
  else	ivGatherLinks(thisLink);
	ivKeyCheckEnable(true);
	ivSetBackground(true);

	ivShowImage(ivCurLinkIndex);

 	return(false);	// ie OK so dont show via new page
}
// ------------------------------------------------------------
// View specific image ie <a href="imageFile" onclick = "return(iViewFile('imageFile'));">thumbnail</a>
function iViewURL(pageURL){
 	//alert(pageURL)
	if (! ivBrowserOK()) return(true);   // ie no good browsers so show via new page

	ivKeyCheckEnable(true);
	ivSetBackground(true);

	ivHTTPObject = ivGetHTTPObject();
 	if (ivHTTPObject != null) {
  		ivHTTPUrl = pageURL;
			var date = new Date();
			var timestamp = date.getTime();
      if (ivHTTPUrl.indexOf('?') == -1)ivHTTPUrl += "?";
			else  ivHTTPUrl += "&";
			ivHTTPUrl += "ts=" +timestamp;
     	ivHTTPObject.open("GET", ivHTTPUrl, true);
			ivHTTPObject.send(null);
			ivHTTPObject.onreadystatechange = ivShowURLContent ;
	}

	return(false);
 
}
// --------------------------------------------------
function ivShowURLContent(  ){
		var ivHtml;
  	if(ivHTTPObject.readyState == 4){
       	if (ivHTTPObject.responseText){
     			ivHtml =   ivHTTPObject.responseText ;
	   		}
	   		else{
       			ivHtml = 'Error reading  httpObject.responseText' ;
     		}
		}
		else  ivHTML = 'File: ' + ivHTTPUrl + ' - Ready State: ' + ivHTTPObject.readyState;
		alert(ivHTML);
}
// --------------------------------------------------
function ivGetHTTPObject(){
var XMLHttp=null
	if (window.XMLHttpRequest)   XMLHttp=new XMLHttpRequest()  ;
	else if (window.ActiveXObject) XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	return(  XMLHttp);
}
// ------------------------------------------------------------
// View specific image ie <a href="imageFile" onclick = "return(iViewFile('imageFile'));">thumbnail</a>
function iViewFile(filePath){
 	//alert(filePath)
     ivLinks[0] = new ivLinkObject(filePath);
	ivSetLanguage();
     ivCurLinkIndex=0;
	if (! ivBrowserOK()) return(true);   // ie no good browsers so show via new page

	ivKeyCheckEnable(true);
	ivSetBackground(true);

	ivShowImage(ivCurLinkIndex);

 	return(false);	// ie OK so dont show via new page
}
// ------------------------------------------------------------
function iViewFiles( fileDir,  arFiles , arCaptions , currentIndex ){
  	var fileIndex = 0;
  	var filePath;
  	ivLinkCount=0;
     for (f=0; f< arFiles.length; f++){
       	if (arFiles[f]){
            	filePath = fileDir + arFiles[f];

			ivLinks[fileIndex] = new ivLinkObject(filePath);
			if (arCaptions[f]) ivCaptions[fileIndex]   =arCaptions[f];
			else  ivCaptions[fileIndex]   ='';
			fileIndex++;
			ivLinkCount++;
		}
	}
ivSetLanguage();
     ivCurLinkIndex=currentIndex;
	if (! ivBrowserOK()) return(true);   // ie no good browsers so show via new page

	ivKeyCheckEnable(true);
	ivSetBackground(true);

	ivShowImage(ivCurLinkIndex);

 	return(false);	// ie OK so dont show via new page
}
// ------------------------------------------------------------
// Fake link object used by ivViewFiles
function ivLinkObject(myHref){
	this.href = myHref;
}
// ------------------------------------------------------------
function ivSkipImage(skip){
	var ivLast = ivLinks.length-1;
	ivCurLinkIndex += skip;
	if (ivSSRunning && ivSSWrap ){
		if (ivCurLinkIndex > ivLast)  ivCurLinkIndex=0;
		if (ivCurLinkIndex < 0)  ivCurLinkIndex=ivLast;  
	}
	else{	
		if (ivCurLinkIndex > ivLast)  ivCurLinkIndex=ivLast;
		if (ivCurLinkIndex < 0)  ivCurLinkIndex=0;
	}
	//alert('Last: '  + ivLast + '  Current: ' + ivCurLinkIndex);
	 
	ivShowImage(ivCurLinkIndex);
}
// ------------------------------------------------------------
// SHow a specific image
function ivShowImage(linkIndex){
	var thisLink =ivLinks[linkIndex];
     var el = document.getElementById(ivMainID);
     if (! el){
	    ivMainDiv = document.createElement('div');
		if (ivMainDiv){
			ivMainDiv.setAttribute('id', ivMainID);
			//ivMainDiv.style.backgroundColor  = "transparent";
			ivMainDiv.style.left = "0";
	        ivMainDiv.style.top = "0";
	        ivMainDiv.style.width = "0";
	        ivMainDiv.style.height = "0";
	        ivMainDiv.style.zIndex  = "254";
			ivMainDiv.className= 'ivMain' + ivStyle;
			 
			if( ivIE6  ) ivMainDiv.style.position = "absolute";  	// For IE we use absolute and adjust it via a timer
			else ivMainDiv.style.position = "fixed";   // or else we use 'proper' fixed positioning
			
		    document.body.appendChild(ivMainDiv);
  		}
	}
	
	// Creat Loading div
	var ivImgLoadingHtml = '<div id="ivImgLoading">loading...</div>';
	ivLoadingDiv = document.createElement('div');
	ivLoadingDiv.setAttribute('id', ivLoadingID);
	ivLoadingDiv.style.zIndex  = "255";
	document.body.appendChild(ivLoadingDiv);
	ivLoadingDiv.innerHTML = ivImgLoadingHtml;
  
	ivImgCache.src =  thisLink.href;
	
 
  	if (ivCurLinkIndex < ivLinkCount-1) ivImgPreLoad.src =  ivLinks[ivCurLinkIndex+1].href;;
	
 	//alert(ivImgCache.src);
}
// ------------------------------------------------------------
// Get all the iView links from a page
function ivGatherLinks(thisLink){
	var el;
	var linkIndex=0;
	ivLinkCount=0;
	var onClickStr;
	var elImg;
	var arEls = document.getElementsByTagName("A");
	for (i=0; i< arEls.length ; i++){
		el = arEls[i];
    onClickStr = new String(el.onclick);

    if (onClickStr && onClickStr.indexOf("iView")>1){
			ivLinks[linkIndex]=el;
			elImg= el.getElementsByTagName("IMG")
				if (elImg) ivCaptions[linkIndex]=elImg[0].alt;

        if (el==thisLink) ivCurLinkIndex= linkIndex;
        linkIndex++;
        ivLinkCount++;
		}
	}
}
// ------------------------------------------------------------
// Enable/disable Key handler(s)
function ivKeyCheckEnable(check){
 	if (check) document.onkeypress=ivKeyCheck;
	else document.onkeypress=null;

}
// ----------------------------------
function ivKeyCheck(ev){
	ev=ev||event;
	var kc = ev.which || ev.keyCode;
	//alert(kc );
	if(kc  == 27){
   		ivClose();
   		return false
  	}
  	else if(kc == 110 || kc == 39)  ivSkipImage(1); // N  in IE and -> in FF
  	else if(kc == 98 || kc == 37)  ivSkipImage(-1); //B  in IE and <- in FF
}
// ----------------------------------
function ivSetBackground(set){
	if (ivStyle=='OP') ivSetBGOpacity(set);
	else if (ivStyle=='TR') ivSetBGTrans(set);
	else if (ivStyle=='ST') ivSetBGStyled(set);
}
// ----------------------------------
function ivSetBGStyled(set){
	if (set){
		// Look for an existing popup div
		var elExists = document.getElementById(ivStyledID);
	
		// If popup doesnt exist, create it
		if (! elExists) {
			ivStyledDiv = document.createElement('div');;
			ivStyledDiv.setAttribute('id', ivStyledID);
			document.body.appendChild(ivStyledDiv);
 
			if( ivIE6   ) ivStyledDiv.style.position = "absolute";  	// For IE we use absolute and adjust it via a timer
			else ivStyledDiv.style.position = "fixed";   // or else we use 'proper' fixed positioning
			
			ivStyledDiv.style.left = "0";
	        ivStyledDiv.style.top = "0";
	        ivStyledDiv.style.width = "100%";
	        ivStyledDiv.style.height = "100%";
	        ivStyledDiv.style.zIndex  = "250";
			
		}
	}
	else{
	  	if(ivStyledDiv) document.body.removeChild(ivStyledDiv);
	}
}
// ----------------------------------
function ivSetBGTrans(set){
	if (set){
		// Look for an existing popup div
		var elExists = document.getElementById(ivTransID);
	
		// If popup doesnt exist, create it
		if (! elExists) {
			ivTransDiv = document.createElement('div');;
			ivTransDiv.setAttribute('id', ivTransID);
			document.body.appendChild(ivTransDiv);

			if( ivIE6   ) ivTransDiv.style.position = "absolute";  	// For IE we use absolute and adjust it via a timer
			else ivTransDiv.style.position = "fixed";   // or else we use 'proper' fixed positioning
			
			ivTransDiv.style.left = "0";
	        ivTransDiv.style.top = "0";
	        ivTransDiv.style.width = "100%";
	        ivTransDiv.style.height = "100%";
	        ivTransDiv.style.zIndex  = "250";
			
		}
	}
	else{
	  	if(ivTransDiv) document.body.removeChild(ivTransDiv);
	}
}
// ----------------------------------
function ivSetBGOpacity(set){
  	ivMaskDiv = document.getElementById(ivMaskID);
	if (ivMaskDiv){
       	if (set){
			ivMaskDiv.style.position='relative';
			ivMaskDiv.style.height = "100%";

			ivSetOpacity(ivOpacity, ivMaskID ) ;
			if( ivIE6  ) {   // Fix for IE Fixed Pos prob
				ivIE6Timer = window.setInterval(ivIEFix, 500);
	 		}
		}
		else {
			ivSetOpacity(100, ivMaskID )
			if( ivIE6  ) {   // Fix for IE Fixed Pos prob
				clearInterval(  ivIE6Timer );
		 	}
		}
	}
}
// ----------------------------------
//change the opacity for different browsers
function ivSetOpacity(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
}
// ----------------------------------
function ivBrowserOK(){
 	 var W3CDOM = (document.createElement && document.getElementsByTagName);
	 return(W3CDOM);
}
// --------------------------------------
function ivClose(){
  	ivKeyCheckEnable(false);
  	ivSSStop();
  	if (ivIE6Timer) clearInterval(ivIE6Timer);
	//alert(ivMainDiv);
     if(ivMainDiv) document.body.removeChild(ivMainDiv);
	
	ivSetBackground(false);
}
// -------------------------------------
function ivIE6Fix(){
     var elMask = document.getElementById(ivMaskID);
     if (elMask){
 		//var arScroll = ivGetScrollXY();
	  	var scrollTop = ivScrollTop(); //arScroll[1];
	  	var newTop = (0  + scrollTop ) + 'px';
		elMask.style.top = newTop;
        	
        var elMain = document.getElementById(ivMainID);
		newTop = (ivIE6MainTop  + scrollTop ) + 'px';
        elMain.style.top = newTop;
     }
     else clearInterval(ivIE6Timer)
}
// -----------------------------------------
function ivClientWidth() {
	return ivFilterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function ivClientHeight() {
	return ivFilterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function ivScrollLeft() {
	return ivFilterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function ivScrollTop() {
	return ivFilterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function ivFilterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
// ------------------------------------------------------------
// Start Slideshow
function ivSSPlay(){
	if (!  ivSSTimer ){
		ivSSTickCounter = 0;
		ivSSTimer = window.setInterval("ivSSTick()",  ivSSTickInterval);
		ivSSRunning = true;
		
		ivSSUpdateTicker();
		var el = document.getElementById('ivTDPlay');
		if(el) el.innerHTML = ivImgInfo + ivSSStopHTML;

	}
}
// ------------------------------------------------------------
// Stop  Slideshow
function ivSSStop(){
  	if ( ivSSTimer ){
		clearInterval(  ivSSTimer );
		ivSSTimer = null;
		ivSSRunning = false;
          ivSSTickCounter=0;
    		var elPlay = document.getElementById('ivTDPlay');
		if(elPlay) elPlay.innerHTML = ivImgInfo + ivSSPlayHTML;
		ivSSUpdateTicker();
	}
}
// ------------------------------------------------------------
function ivSSTick(){

 	if (ivSSTickCounter == (ivSSTickChange * 1000/ivSSTickInterval )){
     	ivSSTickCounter = 0;
		ivSkipImage(1);
     }
     else{
           ivSSTickCounter++;
     }
     ivSSUpdateTicker();

}
// -------------------------------------
function ivSSUpdateTicker(){
  	var ivLast = ivLinks.length-1;
	if (ivCurLinkIndex==ivLast && ! ivSSWrap ) ivSSStop();;
	var el = document.getElementById('ivSSTicker');
	var divWidth = Math.floor(100/  (ivSSTickChange * 1000/ivSSTickInterval ) ) *    ivSSTickCounter  + "%";
     if (el)  el.style.width = divWidth;
     
	el = document.getElementById('ivTDNext');
	if(el) el.innerHTML = (ivSSRunning) ? '&nbsp;' : ivNextHTML;

	el = document.getElementById('ivTDPrev');
	if(el) el.innerHTML = (ivSSRunning) ? '&nbsp;' : ivPrevHTML;

}
// -----------------------------------------------------------