//CODE DEVELOPED BY OPENDOC 2005 - WWW.OPENDOC.IT//
// Global variables
var sourceImg; //image to load
var cordx; 	//Coordinate x of initilal image
var cordy;	//Coordinate y of initilal image
var isCSS, isW3C, isIE4, isNN4;
var isIE6CSS;
var IE = document.all?true:false
var vbMouseDown;
vbMouseDown=false;

var zoom_level=0; // Actual zoom level

var quadx;	//number of orizzontal tile 
var quady;	//number of vertical tile 

var dimOrigx;	//Image dimension in pixel for the actual level zoom
var dimOrigy;	
var passox;		//Step of movement for each tile
var passoy;

var width_viewmap;	//width of the window on the document
var height_viewmap;	//height of the window on the document
var cpx;			//X Center Point of the image
var cpy;			//Y Center Point of the image
var viewmap;		//container of image part visualized
var posCenterX; //x coordinate of the image position in the viewmap center
var posCenterY; //y coordinate of the image position in the viewmap center



/*******************************************************************************************************
*	writeLog
*	generete debug object and write the szMessage
*******************************************************************************************************/
function writeLog(szMessage){
	var d = document.getElementById( 'log' );
    if (d == undefined)
    {
        d = document.createElement( 'div' );
        d.id = 'log';
        document.body.appendChild( d );
    }
    var p = document.createElement( 'p' );
    p.appendChild(document.createTextNode( ((new Date( )).toLocaleString()) + ": " + szMessage ))
    if (d.firstChild)
        d.insertBefore( p, d.firstChild );
     else
        d.appendChild(p);
     d.style.scrollTop = 0;
}


/*******************************************************************************************************
*	initDHTMLAPI
*	find the browser type
*******************************************************************************************************/
function initDHTMLAPI() {
    if (document.images) {
        isCSS = (document.body && document.body.style) ? true : false;
        isW3C = (isCSS && document.getElementById) ? true : false;
        isIE4 = (isCSS && document.all) ? true : false;
        isNN4 = (document.layers) ? true : false;
        isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false;
        isOpera = (navigator.userAgent.indexOf("Opera") > -1) ? true:false;
        isSafari = (navigator.userAgent.indexOf("safari") > -1) ? true:false;
  
        }
}

/*******************************************************************************************************
*	cancelEvent
*	Cancel the event e
*******************************************************************************************************/
function cancelEvent(e)
{
    e = (e)?e:((event)?event:null);
    e.returnValue = false;
    if (e.preventDefault) e.preventDefault();
    return false;
}


/*******************************************************************************************************
*	getRawObject
*	return the object 
*******************************************************************************************************/
function getRawObject(obj) {
    var theObj;
    if (typeof obj == "string") {
        if (isW3C) {
            theObj = document.getElementById(obj);
        } else if (isIE4) {
            theObj = document.all(obj);
        } else if (isNN4) {
            theObj = seekLayer(document, obj);
        }
    } else {
        // pass through object reference
        theObj = obj;
    }
    return theObj;
}

/*******************************************************************************************************
*	getObjectWidth
*	return the obj width 
*******************************************************************************************************/
function getObjectWidth(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetWidth) {
        result = elem.offsetWidth;
    } else if (elem.clip && elem.clip.width) {
        result = elem.clip.width;
    } else if (elem.style && elem.style.pixelWidth) {
        result = elem.style.pixelWidth;
    }
    return parseInt(result);
}

/*******************************************************************************************************
*	getObjectWidth
*	return the obj height 
*******************************************************************************************************/
function getObjectHeight(obj)  {
    var elem = getRawObject(obj);
    var result = 0;
    if (elem.offsetHeight) {
        result = elem.offsetHeight;
    } else if (elem.clip && elem.clip.height) {
        result = elem.clip.height;
    } else if (elem.style && elem.style.pixelHeight) {
        result = elem.style.pixelHeight;
    }
    return parseInt(result);
}

/*******************************************************************************************************
*	find_zoom_fit(larg,alt,quadratox,quadratoy)
*	Find the zoom level to fit the image
*******************************************************************************************************/
function find_zoom_fit(larg,alt,quadratox,quadratoy){
	var origLevel;
	 for (origLevel = 0; alt > (quadratoy ) ||
        larg > (quadratox); origLevel++) {
      alt /= 2;
      larg /= 2;
   }
   return origLevel;
}

/*******************************************************************************************************
*	initMap:
*	Create the image container
*	Generate all the tile
*	Manage the event: mouse over/move/etc...
*******************************************************************************************************/
function initMap(){
	viewmap=getRawObject('viewmap');
	if (viewmap != undefined ) {
		/* Create the div viewmap */
		viewmap.setAttribute('style', 'z-index:10;display:block;position:relative;overflow: hidden;width:'+width_start_viewmap+';height:'+height_start_viewmap+';');
		viewmap.style.zIndex="10";
		viewmap.style.display="block";
		viewmap.style.position="relative";
		viewmap.style.overflow="hidden";
		viewmap.style.width=width_start_viewmap;
		viewmap.style.height=height_start_viewmap;
		viewmap.style.cursor="move";
		/* EnD Create Div viewmap */
		width_viewmap=getObjectWidth('viewmap');
		height_viewmap=getObjectHeight('viewmap');
		//Find the zoom levle to fit image
		var lvl_zoom_tmp=find_zoom_fit(dimIMGOrigx,dimIMGOrigy,width_viewmap,height_viewmap);
		// Center the image
		startx=parseInt(dimOrigx/2);
		starty=parseInt(dimOrigy/2);
		cordx=-parseInt(widthTile/2);
		cordy=-parseInt(heightTile/2);
		generate_imagedocument(lvl_zoom_tmp);
		show_value_zoom(lvl_zoom_tmp);
		//manage the image event
		if (IE) {viewmap.onresize=winonresize;} //Only for IE
		else{window.onresize=winonresize;}
		viewmap.onmousedown=omd;
		viewmap.oncontextmenu=ocm;
		viewmap.onmouseout = omout;
		//document.onmousemove=omm;
		refreshPreview();
	}
	getRawObject("preview_img").onclick=clickPreview;
}

/*******************************************************************************************************
*	generate_imagedocument:
*	Calculate the common information about the tile image
*	Calculate the actual image dimension (at this zoom level)
*	Center the image
*	Generate all the tile
*	Create all tile
*	refresh the preview
*******************************************************************************************************/
function generate_imagedocument(lvl_zoom){
	zoom_level=lvl_zoom;
	sourceImg=URL_image_start+"&wid="+widthTile+"&hei="+heightTile+"&page="+document_page+"&lev="+zoom_level;
	//Calculate the actual image dimension (at this zoom level)
	dimOrigx=dimIMGOrigx;
	dimOrigy=dimIMGOrigy;
	var valore_zoom=Math.pow(2,zoom_level);
	if (zoom_level!=0){
		dimOrigx=parseInt(dimIMGOrigx/valore_zoom);
		dimOrigy=parseInt(dimIMGOrigy/valore_zoom);
	}
	quadx=Math.round(width_viewmap/widthTile)+1;
	quady=Math.round(height_viewmap/heightTile)+1;
	passox=widthTile/dimOrigx;
	passoy=heightTile/dimOrigy;
	//Center the image
	cpx=startx/dimOrigx;
	cpy=starty/dimOrigy;	
	cpx=0.5-((width_viewmap/2))/dimOrigx;
	cpy=0.5-((height_viewmap/2))/dimOrigy;
	posCenterX=parseInt(cpx*dimOrigx+(width_viewmap)/2);
	posCenterY=parseInt(cpy*dimOrigy+(height_viewmap)/2);
	//Create all tile
	createAllImage(startx,starty,width_viewmap,height_viewmap);
	refreshPreview();
}


/*******************************************************************************************************
*	winonresize:
*	Manage the onresize event
* 	1. Clear the viewmap
*	2. Recenter image
*	3. find the original center point
*	4.calculate the new center point
*	6. load the tile
*******************************************************************************************************/
function winonresize(e){
	e = (e)?e:((event)?event:null);
	
	//find the new viewmap dimension
	var old_larg=width_viewmap;
	var old_alt=height_viewmap;
	width_viewmap=getObjectWidth('viewmap');
	height_viewmap=getObjectHeight('viewmap');
	if (!(width_viewmap==old_larg && height_viewmap==old_alt)){	//Only if the dimension are changed
		clear_screen(viewmap);
		//find the original center point
		var cpxtemp=posCenterX/dimOrigx; 
		var cpytemp=posCenterY/dimOrigy;
		//Calculate the step 
		passox=widthTile/dimOrigx;
		passoy=heightTile/dimOrigy;
		//Find the numeber of x,y tile 
		quadx=Math.round(width_viewmap/widthTile)+1;
		quady=Math.round(height_viewmap/heightTile)+1;
		//Check if the document border is inside the viewmap and calculate the new center point
		var NewCpx=posCenterX/dimOrigx;
		var NewCpy=posCenterY/dimOrigy;
		if (width_viewmap>dimOrigx) {
			NewCpx=0.5;
			posCenterX=dimOrigx*NewCpx;
		}
		else{
			posCenterX=dimOrigx*NewCpx;
			if ((posCenterX-parseInt(width_viewmap/2))<0) posCenterX=parseInt(width_viewmap/2);
			if ((posCenterX+parseInt(width_viewmap/2))>dimOrigx) posCenterX=dimOrigx-parseInt(width_viewmap/2);
			NewCpx=posCenterX/dimOrigx;
		}
		if (height_viewmap>dimOrigy){
			NewCpy=0.5;
			posCenterY=dimOrigy*NewCpy;
		}
		else{
			posCenterY=dimOrigy*NewCpy;
			if ((posCenterY-parseInt(height_viewmap/2))<0) posCenterY=parseInt(height_viewmap/2);
			if ((posCenterY+parseInt(height_viewmap/2))>dimOrigy) posCenterY=dimOrigy-parseInt(height_viewmap/2);
			NewCpy=posCenterY/dimOrigy;
		}
		cpx=NewCpx-(width_viewmap/2)/(dimOrigx);
		cpy=NewCpy-(height_viewmap/2)/(dimOrigy);
		startx=posCenterX;
		starty=posCenterY;
		cordx=-parseInt(widthTile/2);
		cordy=-parseInt(heightTile/2);
		clear_screen(viewmap);
		createAllImage(startx,starty,width_viewmap,height_viewmap);
		setPosition("thumbnails","viewmap","outtopright");
		get("thumbnails").style.height=get("viewmap").offsetHeight;
	}
	ShowHidePreview('show');
	setStartPositionPreview();
	ShowHidePreview('hide');
	refreshPreview();
}

/*******************************************************************************************************
*	Manage oncontextmenu event
*******************************************************************************************************/
function ocm(e)
{
	e = (e)?e:((event)?event:null);
    return cancelEvent(e);
}

/*******************************************************************************************************
*	Manage onmousedown event
*******************************************************************************************************/
function omd(e){
	 e = (e)?e:((event)?event:null);
	if (e.button==2)
    {
    	vbMouseDown=false;
        e.cancelBubble = true;
        e.returnValue = false;
        if (e.stopPropogation) e.stopPropogation();
        if (e.preventDefault) e.preventDefault();
        return false;
    }
    else
    {
    	lastX=sx=e.clientX;
        lastY=sy=e.clientY;
        vbMouseDown=true;
		document.onmousemove=omm;
		
		document.onmouseup=omu;
    	getRawObject('viewmap').style.cursor="move";
        return false;
    }

}

/*******************************************************************************************************
*	Manage onmouseup event
*******************************************************************************************************/
function omu(e){
	e = (e)?e:((event)?event:null);
	vbMouseDown=false

}

/*******************************************************************************************************
*	Manage onmousemove event
*******************************************************************************************************/
function omm(e){
	e = (e)?e:((event)?event:null);
	if (!vbMouseDown) return true;
	newx=e.clientX;
	newy=e.clientY;
	//Find how much mouse move
	diffX=newx-lastX;
	diffY=newy-lastY;
	lastX=newx;
	lastY=newy;
	
	if (diffX>widthTile/2) diffX=parseInt(widthTile/2)-1;
	if (diffY>heightTile/2) diffY=parseInt(heightTile/2)-1;
	if (diffX<-widthTile/2) diffX=1-parseInt(widthTile/2);
	if (diffY<-heightTile/2) diffY=1-parseInt(heightTile/2);

	//Stop move on the left if the document is finished
	if (posCenterX-diffX+width_viewmap/2>dimOrigx) {
		diffX=parseInt(posCenterX+width_viewmap/2-dimOrigx-1);
	}
	//Stop move up if the document is finished
	if (posCenterY-diffY+height_viewmap/2>dimOrigy) {
		diffY=parseInt(posCenterY+height_viewmap/2-dimOrigy-1);
	}
	
	//Stop move on the right if the document is finished
	if ( posCenterX-diffX-width_viewmap/2<0 ){
		diffX=parseInt(posCenterX-width_viewmap/2);
	}
	//Stop move down if the document is finished
	if ( posCenterY-diffY-height_viewmap/2<0 ){
		diffY=parseInt(posCenterY-height_viewmap/2);
	}
	//Check if the image dimension is less then the viewmap
	if (width_viewmap>dimOrigx) {
		diffX=0;
	}
	if (height_viewmap>dimOrigy){
		diffY=0;
	}
	
	//Update the tile position
	if (diffX!=0 || diffY!=0){
		updateTile(diffX,diffY);
		refreshPreview();
	}

    e.cancelBubble = true;
    e.returnValue = false;
    if (e.preventDefault) e.preventDefault();
    return false;
	
}


/*******************************************************************************************************
*	Manage onmouseout event
*******************************************************************************************************/
function omout(e){
		e = (e)?e:((event)?event:null);
	 //vbMouseDown = false;
	 var tg = (e.target) ? e.target : e.srcElement
	 if (tg.nodeType == 3) // defeat Safari bug
		tg = tg.parentNode;
	 return cancelEvent(e);
}




/*******************************************************************************************************
*	addRow:
*	Add tile row to viewmap
*	direction > 0 : bottom row
*	direction < 0 : top row
*******************************************************************************************************/
function addRow(direction){
	if (direction>0){ //add bottom row
		cpx_temp=cpx;
		cpy_temp=cpy;
		cpy=cpy+passoy*quady;
		var inizioy=parseInt(cordy+quady*heightTile);
		var diffTempx=cordx;
		for (col=0;col<quadx;col++){
				var idact="imgpiccolacol"+col+"_"+quady;
				var imgTemp=createImage(sourceImg+"&cp="+cpx+","+cpy,inizioy,diffTempx+heightTile*col,idact);
				viewmap.appendChild(imgTemp);
				imgTemp=null;
				cpx=cpx+passox;
		}
		cpx=cpx_temp;
		cpy=cpy_temp;
		quady++;
	}
	else if (direction<0) { //add top row
		cpx_temp=cpx;
		cpy_temp=cpy;
		cpy=cpy-passoy;
		var inizioy=cordy-heightTile;
		var diffTempx=cordx;
		for (col=0;col<quadx;col++){
				var idact="imgpiccolacol"+col+"_"+quady;
				var imgTemp=createImage(sourceImg+"&cp="+cpx+","+cpy,inizioy,diffTempx+heightTile*col,idact);
				viewmap.appendChild(imgTemp);
				imgTemp=null;
				cpx=cpx+passox;
		}

		cpy=cpy_temp-passoy;
		cordy=cordy-heightTile;
		cpx=cpx_temp;
		quady++;
	}
}


/*******************************************************************************************************
*	addColumn:
*	Add tile column to viewmap
*	direction > 0 : Right column
*	direction < 0 : Left column
*******************************************************************************************************/
function addColumn(direction){
	if (direction>0){ //Add left column
		cpx_temp=cpx;
		cpy_temp=cpy;
		cpx=cpx+passox*quadx;
		iniziox=cordx+quadx*widthTile;
		diffTempy=cordy;
		for (riga=0;riga<quady;riga++){
				idact="imgpiccola2"+quadx+"_"+riga;
				imgTemp=createImage(sourceImg+"&cp="+cpx+","+cpy,diffTempy+widthTile*riga,iniziox,idact);
				viewmap.appendChild(imgTemp);
				imgTemp=null;
				cpy=cpy+passoy;
		}
		cpx=cpx_temp;
		cpy=cpy_temp;
		quadx++;
	}
	else if (direction<0) { //Add right column
		cpx_temp=cpx;
		cpy_temp=cpy;
		cpx=cpx-passox;
		iniziox=cordx-widthTile;
		diffTempy=cordy;
		for (riga=0;riga<quady;riga++){
				idact="imgpiccolasx2"+quadx+"_"+riga;
				imgTemp=createImage(sourceImg+"&cp="+cpx+","+cpy,diffTempy+widthTile*riga,iniziox,idact);
				viewmap.appendChild(imgTemp);
				imgTemp=null;
				cpy=cpy+passoy;
		}
		cpx=cpx_temp-passox;
		cpy=cpy_temp;
		cordx=cordx-widthTile;
		quadx++;
	}
	
}

/*******************************************************************************************************
*	deleteRow:
*	Delee tile row to viewmap
*	direction > 0 : bottom row
*	direction < 0 : top row
*******************************************************************************************************/
function deleteRow(direction){
	var numeliminatisx=0;
	var numeliminatidx=0;
	var imgTemp;
	var scorri;
	//var num_elem=viewmap.childNodes.length;
	for (scorri=0;scorri<viewmap.childNodes.length;scorri++){
		if (viewmap.childNodes[scorri].nodeType==1){
			imgTemp=viewmap.childNodes[scorri];
			xact=parseInt(imgTemp.style.left);
			yact=parseInt(imgTemp.style.top);
			if (direction<0){
				if (yact+heightTile<0){	
					numeliminatisx++;
					if (imgTemp.src) {
						imgTemp.src="";
					}
					imgTemp.setAttribute('style','');
					viewmap.removeChild(imgTemp);
					scorri--;
				}
			}
			if (direction>0){
				if (yact>=height_viewmap){
					if (imgTemp.src) {
						imgTemp.src="";
					}
					imgTemp.setAttribute('style','');
					viewmap.removeChild(imgTemp);
					numeliminatidx++;
					scorri--;
				}
			}
			imgTemp=undefined;
		}
	}
	if (numeliminatisx>0) {
		quady--;
		cpy=cpy+passoy;
		cordy=cordy+heightTile;
	}
	if (numeliminatidx>0) {
		quady--;
	}
}

/*******************************************************************************************************
*	deleteColumn:
*	Delete tile column to viewmap
*	direction > 0 : Right column
*	direction < 0 : Left column
*******************************************************************************************************/
function deleteColumn(direction){
	var numeliminatisx=0;
	var numeliminatidx=0;
	var imgTemp;
	//var num_elem=viewmap.childNodes.length;
	for (scorri=0;scorri<viewmap.childNodes.length;scorri++){
		if (viewmap.childNodes[scorri].nodeType==1){
			imgTemp=viewmap.childNodes[scorri];
			xact=parseInt(imgTemp.style.left);
			yact=parseInt(imgTemp.style.top);
		
			if (direction<0){
				
				if (xact+widthTile<0){
					if (imgTemp.src) {
						imgTemp.src="";
					}
					imgTemp.setAttribute('style','');
					viewmap.removeChild(imgTemp);
					numeliminatisx++;
					scorri--;
				}
			}
			if (direction>0){
				if (xact>width_viewmap){
					if (imgTemp.src) {
						imgTemp.src="";
					}
					imgTemp.setAttribute('style','');
					viewmap.removeChild(imgTemp);
					numeliminatidx++;
					scorri--;
				}
			}
			imgTemp=undefined;
		}
		
	}
	if (numeliminatisx>0) {
		quadx--;
		cpx=cpx+passox;
		cordx=cordx+widthTile;
	}
	if (numeliminatidx>0) {
		quadx--;
	}	
}


/*******************************************************************************************************
*
*	updateTile
* 	Update the viewmap tile of about diffX and diffY
*******************************************************************************************************/
function updateTile(diffX,diffY) {
	
	if (diffX!=0 || diffY!=0){
		var imgTemp;
		var numquad=quadx*quady;
		//Aggiorno la poszione del punto
		posCenterX=posCenterX-diffX;
		posCenterY=posCenterY-diffY;
		cordx=cordx+diffX;
		cordy=cordy+diffY;
	
		for (scorri=0;scorri<viewmap.childNodes.length;scorri++){
		
			if (viewmap.childNodes[scorri].nodeType==1){
				//imgTemp=getRawObject("imgpiccola"+scorri);
				imgTemp=viewmap.childNodes[scorri];
				xact=parseInt(imgTemp.style.left);
				yact=parseInt(imgTemp.style.top);
				imgTemp.style.left=(xact+diffX)+"px";
				imgTemp.style.top=(yact+diffY)+"px";
				imgTemp=null;
			}
		}
		//Add right column
		if (cordx+(quadx)*widthTile<width_viewmap){
			addColumn(1);
		}
		//Add left column
		if (cordx>0){
			addColumn(-1);
		}
		//Add row bottom
		if (cordy+(quady)*heightTile<height_viewmap){
			addRow(1);
		}
		//Add row top
		if (cordy>0){
			addRow(-1);
		}
		
		//Delete tile out of viewmap
		if (widthTile+cordx<0){
			deleteColumn(-1);
		}
		if (cordx+(quadx-1)*widthTile>width_viewmap) {
			deleteColumn(1);
		}
		
		if (heightTile+cordy<0){
			deleteRow(-1);
			
		}
		if (cordy+(quady-1)*heightTile>height_viewmap) {
			deleteRow(1);
		}
		//END Delete tile out of viewmap
	}
}


/*******************************************************************************************************
*
*	createAllImage
* 	Create all the image tiles
*	
*	GLOBAL VARIABLES:
*		cpy,cpy: center point of the first tile
*		sourceImg: indirizzo http express Server, width catalog and item
*		cordx,cordy: position of thr first tile respect viewmap
*	PARAMETER;
*		NOT USED: cordTx,cordTy (position of thr first tile respect viewmap)
*		width_viewmap,height_viewmap: viewmap dimension
*******************************************************************************************************/
function createAllImage(cordTx,cordTy,width_viewmap,height_viewmap){

	startx=cordTx;
	starty=cordTy;
	conta=-1;
	diffTempX=cordx;
	diffTempY=cordy;
	cpyTemp=cpy;
	cpxTemp=cpx;
	for (j=0;j<quady;j++){
		//righe
		cpxTemp=cpx;
		for (i=0;i<quadx;i++){
			conta++;
			idact="imgpiccola"+i+"_"+j;
			imgTemp=createImage(sourceImg+"&cp="+cpxTemp+","+cpyTemp,diffTempY+heightTile*j,diffTempX+widthTile*i,idact);
			viewmap.appendChild(imgTemp);
			imgTemp=null;
			cpxTemp=cpxTemp+passox;
		}
		cpyTemp=cpyTemp+passoy;
	}
}


/*******************************************************************************************************
*
*	createImage
* 	Create one tile
*	PARAMETERS:
*		src: image src
*		top,left: position
*		id: id image
*	GLOBAL VARIABLES:
*		IE: indicate if browser is explorer
*******************************************************************************************************/
function createImage(src,top,left,id){
	if (IE){
		return createImageIE(src,top,left,id)
	}
	else{
		//alert("source" + src);
		return createImageDIV(src,top,left,id)
	}
}

/*******************************************************************************************************
*
*	createImage
* 	Create one tile width object image.
*	PARAMETERS:
*		src: image src
*		top,left: position
*		id: id image
*******************************************************************************************************/
function createImageIE(src,top,left,id){
	//var imgTemp=new Image();
	var imgTemp=document.createElement("img");
	imgTemp.src=src;
    imgTemp.style.position = 'absolute';
    imgTemp.style.top = top+'px';
    imgTemp.style.left = left+'px';
    imgTemp.alt="OurOntario.ca";
    imgTemp.style.display= "block";
    return imgTemp;
}


/*******************************************************************************************************
*
*	createImage
* 	Create DIV width background one tile.
*	PARAMETERS:
*		src: image src
*		top,left: position
*		id: id image
*******************************************************************************************************/
function createImageDIV(src,top,left,id){ 
	var imgTemp=document.createElement("div");

  	imgTemp.setAttribute('style', 'z-index:1;width:'+widthTile+'px;height:'+heightTile+'px;background-image:url('+src+');display:block;position:absolute; top:'+top+'px; left:'+left+'px;width='+widthTile+'px;height='+heightTile+'px;background=url('+src+')' );
    return imgTemp;
}


/*******************************************************************************************************
*
*	change_zoom
* 	Change the zoom of image document
*	PARAMETERS:
*		new_add_value: difference to apply do zoom_level to obtain the new zoom value
*	
*	GLOBAL VARIABLES:
*		zoom_level: actual zoom level
*******************************************************************************************************/
function change_zoom(new_add_value){
	if (zoom_level+new_add_value>-4){
		clear_screen(viewmap);
		viewUserPreview=true;
		zoom_level=zoom_level+new_add_value;
		show_value_zoom(zoom_level);
		sourceImg=URL_image_start+"&wid="+widthTile+"&hei="+heightTile+"&page="+document_page+"&lev="+zoom_level;
		var NewCpx=posCenterX/dimOrigx;
		var NewCpy=posCenterY/dimOrigy;
	
		dimOrigx=dimIMGOrigx;
		dimOrigy=dimIMGOrigy;
	
		if (zoom_level!=0){
			dimOrigx=dimIMGOrigx/Math.pow(2,zoom_level);
			dimOrigy=dimIMGOrigy/Math.pow(2,zoom_level);
		}
		cordx=-parseInt(widthTile/2);
		cordy=-parseInt(heightTile/2);
		if (width_viewmap>dimOrigx) {
			NewCpx=0.5;
			posCenterX=dimOrigx*NewCpx;
		}
		else{
			posCenterX=dimOrigx*NewCpx;
			if ((posCenterX-parseInt(width_viewmap/2))<0) posCenterX=parseInt(width_viewmap/2);
			if ((posCenterX+parseInt(width_viewmap/2))>dimOrigx) posCenterX=dimOrigx-parseInt(width_viewmap/2);
			NewCpx=posCenterX/dimOrigx;
		}
		if (height_viewmap>dimOrigy){
			NewCpy=0.5;
			posCenterY=dimOrigy*NewCpy;
		}
		else{
			posCenterY=dimOrigy*NewCpy;
			if ((posCenterY-parseInt(height_viewmap/2))<0) posCenterY=parseInt(height_viewmap/2);
			if ((posCenterY+parseInt(height_viewmap/2))>dimOrigy) posCenterY=dimOrigy-parseInt(height_viewmap/2);
			NewCpy=posCenterY/dimOrigy;
		}
		cpx=NewCpx-(width_viewmap/2)/(dimOrigx);
		cpy=NewCpy-(height_viewmap/2)/(dimOrigy);
		passox=widthTile/dimOrigx;
		passoy=heightTile/dimOrigy;
		quadx=Math.round(width_viewmap/widthTile)+1;
		quady=Math.round(height_viewmap/heightTile)+1;

		startx=parseInt(dimOrigx/2);
		starty=parseInt(dimOrigy/2);
		cordx=-parseInt(widthTile/2);
		cordy=-parseInt(heightTile/2);
		clear_screen(viewmap);
		createAllImage(startx,starty,width_viewmap,height_viewmap);
		refreshPreview();
	}
}


/*******************************************************************************************************
*
*	clear_screen
* 	Clear the object, deleting  childs
*	
********************************************************************************************************/
function clear_screen(objToClear){
	var conta=0;
	while (objToClear.childNodes.length>0){
		//var objimg=viewmap.firstChild;
		//viewmap.firstChild=null;
		var objImg=objToClear.firstChild;
		if (objImg.src) {
			objImg.src="";
			
		}
		conta++;
		objImg.setAttribute('style','');
		objToClear.removeChild(objToClear.firstChild)
		
		objImg=undefined;
	}
	//objToClear.innerHtml="";
	objToClear=undefined;
	//viewmap=null;
}


/*******************************************************************************************************
*
*	fitOneToOne
* 	Set image dimension to 100%
*	
********************************************************************************************************/
function fitOneToOne(){
	zoom_level=0;
	change_zoom(0);
}


/*******************************************************************************************************
*
*	fitWidth
* 	Set image dimension to fit with width
*	
********************************************************************************************************/
function fitWidth()
{	
	var newLevel;
	var sWidth=dimIMGOrigx;
	for (newLevel = 0; sWidth > (width_viewmap ); newLevel++) {
		sWidth /= 2;
	}
	cpx=0.5;
	posCenterX=dimOrigx/2;
	zoom_level=newLevel;
	change_zoom(0);
}

/*******************************************************************************************************
*
*	fitAll
* 	Set image dimension less than viewmap 
*	
********************************************************************************************************/
function fitAll()
{	
	clear_screen(viewmap);
	var newLevel=find_zoom_fit(dimIMGOrigx,dimIMGOrigy,width_viewmap,height_viewmap);
	cpx=0.5;
	cpy=0.5;
	posCenterX=dimOrigx/2;
	posCenterXY=dimOrigy/2;
	zoom_level=newLevel;
	change_zoom(0);
	refreshSquareRedPreview();
}


/*******************************************************************************************************
*
*	clickPreview
* 	Manage the event onclick on the image preview
*	
********************************************************************************************************/
function clickPreview(evt){
	evt = (evt)?evt:((event)?event:null);
	//found the position on the preview
	if (!IE) {
	  act_newx = evt.clientX;
	  for (var offMark = evt.target; offMark; offMark = offMark.offsetParent)
	     act_newx -= offMark.offsetLeft;
	} else if (isNN4)
	  act_newx = evt.x - document.imgView.x;
	else
	  act_newx = evt.offsetX;
	
	if (window.pageXOffset && !(isSafari) && !(isOpera)) {
		act_newx=act_newx+window.pageXOffset;
	}
 
	if (!IE) {
	  act_newy = evt.clientY;
	  for (var offMark = evt.target; offMark; offMark = offMark.offsetParent)
	     act_newy -= offMark.offsetTop;
	} else if (isNN4)
	  act_newy = evt.y - document.imgView.y;
	else
	  act_newy = evt.offsetY;
	
	if (window.pageYOffset && !(isSafari) && !(isOpera)) {
		act_newy=act_newy+window.pageYOffset;
	}
	
	var valore_zoom=Math.pow(2,zoom_level);
	
	 destinationX=parseInt((act_newx/getObjectWidth("preview_img"))*dimOrigx);
	 destinationY=parseInt((act_newy/getObjectHeight("preview_img"))*dimOrigy);
	moveTo(destinationX,destinationY);
}


/*******************************************************************************************************
*
*	moveTo
* 	Set the position of the image to the new destination:
*	
*	
********************************************************************************************************/
function moveTo(DestX,DestY){
	posCenterX=parseInt(posCenterX);
	posCenterY=parseInt(posCenterY);
	//Check position red rectangle inside preview
	if (width_viewmap>dimOrigx) {
		DestX=dimOrigx/2;
	}
	else{
		if ((DestX-parseInt(width_viewmap/2))<0) DestX=parseInt(width_viewmap/2);
		if ((DestX+parseInt(width_viewmap/2))>dimOrigx) DestX=dimOrigx-parseInt(width_viewmap/2);
	}

	if (height_viewmap>dimOrigy){
		DestY=dimOrigy/2;
	}
	else{
		if ((DestY-parseInt(height_viewmap/2))<0) DestY=parseInt(height_viewmap/2);
		if ((DestY+parseInt(height_viewmap/2))>dimOrigy) DestY=dimOrigy-parseInt(height_viewmap/2);
	}
	//END Check position red rectangle inside preview
	DestX=parseInt(DestX);
	DestY=parseInt(DestY);
	if ((Math.abs(posCenterX-DestX)<widthTile) && (Math.abs(posCenterY-DestY)<heightTile)){
		updateTile(posCenterX-DestX,posCenterY-DestY);
		refreshPreview();
	}
		else{
		posCenterX=parseInt(DestX);
		posCenterY=parseInt(DestY);
	
		
		//Check postion inside viewmap
		if (width_viewmap>dimOrigx) {
			posCenterX=dimOrigx/2;
		}
		else{
			if ((posCenterX-parseInt(width_viewmap/2))<0) posCenterX=parseInt(width_viewmap/2);
			if ((posCenterX+parseInt(width_viewmap/2))>dimOrigx) posCenterX=dimOrigx-parseInt(width_viewmap/2);
		}
	
		if (height_viewmap>dimOrigy){
			posCenterY=dimOrigy/2;
		}
		else{
			if ((posCenterY-parseInt(height_viewmap/2))<0) posCenterY=parseInt(height_viewmap/2);
			if ((posCenterY+parseInt(height_viewmap/2))>dimOrigy) posCenterY=dimOrigy-parseInt(height_viewmap/2);
		}
		//END Check postion inside viewmap
		posCenterX=parseInt(DestX);
		posCenterY=parseInt(DestY);
		cpx=(posCenterX-width_viewmap/2)/(dimOrigx);
		cpy=(posCenterY-height_viewmap/2)/(dimOrigy);
		

		passox=widthTile/dimOrigx;
		passoy=heightTile/dimOrigy;
		quadx=Math.round(width_viewmap/widthTile)+1;
		quady=Math.round(height_viewmap/heightTile)+1;
		
		
		startx=parseInt(posCenterX);
		starty=parseInt(posCenterY);
		cordx=-parseInt(widthTile/2);
		cordy=-parseInt(heightTile/2);
		clear_screen(viewmap);
		createAllImage(startx,starty,width_viewmap,height_viewmap);
		refreshPreview();
	}
}



/*******************************************************************************************************
*
*	moveQuadTo
* 	Move the image to destinationX,destinationY from posCenterX,posCenterY
*	Used when the move is less than tile dimension 
*	
********************************************************************************************************/
function moveQuadTo(destinationX,destinationY){
	var passetto=10;
	
	//Check position red rectangle inside preview
	if (width_viewmap>dimOrigx) {
		destinationX=dimOrigx/2;
	}
	else{
		if ((destinationX-parseInt(width_viewmap/2))<0) destinationX=parseInt(width_viewmap/2);
		if ((destinationX+parseInt(width_viewmap/2))>dimOrigx) destinationX=dimOrigx-parseInt(width_viewmap/2);
	}
	if (height_viewmap>dimOrigy){
		destinationY=dimOrigy/2;
	}
	else{
		if ((destinationY-parseInt(height_viewmap/2))<0) destinationY=parseInt(height_viewmap/2);
		if ((destinationY+parseInt(height_viewmap/2))>dimOrigy) destinationY=dimOrigy-parseInt(height_viewmap/2);
	}
	//END Check position red rectangle inside preview
	if ((posCenterX>destinationX-passetto) && (posCenterX<destinationX+passetto)) {
		passettox=posCenterX-destinationX;
	}
	else{
		if (destinationX>posCenterX){
			passettox=-passetto;
		}
		else{
			passettox=+passetto;
		}
	}
	if ((posCenterY>destinationY-passetto) && (posCenterY<destinationY+passetto)) {
		passettoy=posCenterY-destinationY;
	}
	else{
		if (destinationY>posCenterY){
			passettoy=-passetto;
		}
		else{
			passettoy=+passetto;
		}
	}
	if (passettox!=0 || passettoy!=0){
		updateTile(passettox,passettoy);
		refreshPreview();
		
	}
	
}

/*****************************************************************************
			Manage keyboard event 
			1. up,down,left,right
			2. Zoom In/Out
*******************************************************************************/
function manageKeypress(e)
{
	var b=true;
	e = (e)?e:((event)?event:null);
	if(e){
	var charCode=(e.keyCode)?e.keyCode:e.charCode;
	var nStep = 16;
	switch(charCode){
	  case 38://up
	  	destinationY=posCenterY-nStep;
	  	destinationX=posCenterX;
	   	moveQuadTo(destinationX,destinationY);
	   	break;
	  case 40://down
	    destinationY=posCenterY+nStep;
	    destinationX=posCenterX;
	   	moveQuadTo(destinationX,destinationY);
	    break;
	  case 37://left
	    destinationX=posCenterX-nStep;
	    destinationY=posCenterY;
	   	moveQuadTo(destinationX,destinationY);
	    break;
	  case 39://right
	  	destinationX=posCenterX+nStep;
	  	destinationY=posCenterY;
	   	moveQuadTo(destinationX,destinationY);
	    break;
	 case 63232://up
	  	destinationY=posCenterY-nStep;
	  	destinationX=posCenterX;
	   	moveQuadTo(destinationX,destinationY);
	   	break;
	  case 63233://down
	    destinationY=posCenterY+nStep;
	    destinationX=posCenterX;
	   	moveQuadTo(destinationX,destinationY);
	    break;
	  case 63234://left
	    destinationX=posCenterX-nStep;
	    destinationY=posCenterY;
	   	moveQuadTo(destinationX,destinationY);
	    break;
	  case 63235://right
	  	destinationX=posCenterX+nStep;
	  	destinationY=posCenterY;
	   	moveQuadTo(destinationX,destinationY);
	    break;
	  case 43://XoomIn
	    change_zoom(-1)
	    break;
	 case 45://zoomOut
	    change_zoom(+1)
	    break;
	 case 32: //spacebar
	 	nextPage();
	  default:
	    b=false;
	}
	
	if (b){
	    e.cancelBubble = true;
	    e.returnValue = false;
	    if (e.preventDefault) e.preventDefault();
	    return false;
	}
	return true;
	}
}
/*END manageKepress
****************************************************************************************************/

if (IE) {
	document.onkeydown = manageKeypress;
	//document.onkeyup = manageKeypress;
}else{
document.onkeypress= manageKeypress;
}
/********************************************************************/


/**********************************************************************************
Under construction switch Hnad/Zoom
***********************************************************************************/
function switchToZoom(){
		viewmap.onmousedown=null;
		viewmap.oncontextmenu=null;
		viewmap.onmouseout = null;
		
		viewmap.onmousup=null;
		viewmap.onmousemove=null;
		viewmap.onmouseup=null;
		viewmap.onclick=clickAndZoom;
		viewmap.style.cursor="auto";
}

function switchToHand(){
		viewmap.onmousedown=omd;
		viewmap.oncontextmenu=ocm;
		viewmap.onmouseout = omout;
		
		viewmap.onmousup=omu;
		viewmap.onmousemove=omm;
		viewmap.onmouseup=omu;
		viewmap.onclick=null;
		viewmap.style.cursor="move";
	
}
function clickAndZoom(evt){
	evt = (evt)?evt:((event)?event:null);

	if (!IE) {
	  act_newx = evt.clientX;
	  for (var offMark = evt.target; offMark; offMark = offMark.offsetParent)
	     act_newx -= offMark.offsetLeft;
	} else if (isNN4)
	  act_newx = evt.x - document.imgView.x;
	else
	  act_newx = evt.offsetX;
	
	/*if (window.pageXOffset && !(isSafari) && !(isOpera)) {
		act_newx=act_newx+window.pageXOffset;
	}*/
 
	if (false) {
	  act_newy = evt.clientY;
	  for (var offMark = evt.target; offMark; offMark = offMark.offsetParent)
	     act_newy -= offMark.offsetTop;
	} else if (isNN4)
	  act_newy = evt.y - document.imgView.y;
	else
	  act_newy = evt.offsetY;

}
