var uploaddialog = null;
var dialog = null;
var galerie = null;
var nextlevel = 1000;
var selectedCell = null;
var selectedfile = null;
var selectedFileElement = null;
var item = null;
var imgWidth = 0;
var imgHeight = 0;
var orgImgWidth = 0;
var orgImgHeight = 0;
var currentImageName = null;
var imageExtension = null;
var flip = 'o';
var thumbnailWidth = 0;
var thumbnailHeight = 0;
var scale = 0;
var selectedAutoField = null;
var selectedLayout = 1;
var lastAutoWidth = 0;
var lastAutoHeight = 0;
var slider = null;
var saved = 1;
var lastManualWidth = 0;
var lastManualHeight = 0;
var sizeFormat = "auto";
var maxSliderValue = 10;
var currentStep = 0;
var currentImage = null;
var layoutwidth = 50;
var layoutheight = 50;
var leftPosition = 0;
var topPosition = 0;
var lastMoveDraggerX = 0;
var lastMoveDraggerY = 0;
var dragwidth = 20;
var dragheight = 20;
var loadback = null;
var rotate = false;
var tblwidth = 350;
var tblheight = 350;
var newWidthMM = 0;
var newHeightMM = 0;
var newWidth = imgWidth;
var newHeight = imgHeight;
var zoom_image; 

var IEStep = 0;

function updateImageWorkaround(val) {

newWidthMM  = parseInt(lastAutoWidth);
newHeightMM = parseInt(lastAutoHeight);

var widthMM = $("max_hoehe").value;
var heightMM = $("max_hoehe").value;
var ratio = widthMM / heightMM;

var faktor = widthMM / newWidthMM;
var pixW = Math.round((faktor * 350)-350 / imgWidth);

maxSliderValue = pixW;

	if( val == 1 ) {
		IEStep += 10;
		updateImage(IEStep);
	}
	else {
		IEStep -= 10;
		updateImage(IEStep);
	}
}

function flipImage(dir) {
	
	zoom_image.flip( dir ) ; 
	return ; 
	
	if( currentImageName ) {
		switch( dir ) {
			case "h": flip = "h";
				  break;
			case "v": flip = "v";
				  break;
			case "r": flip = 'o';
				  break;
			default:  flip = 'o';
		}

		$('iFrame1').src = "flipimage.php?flip=" + flip + "&file=" + currentImageName + "&type=" + imageExtension;
	}
	else {
		alert("Es ist noch kein Bild hochgeladen");
	}
}

function saveSettings(callbackFunc, args) {
		if( !currentImage )
			currentImage = $("newImage");
		
		rotated 			= ( zoom_image.orientation == 'horizontal' ) ? "0" : "1"; 
		topPosition 	= zoom_image.x0; 
		leftPosition 	= zoom_image.y0; 
		
		
		data = { 	image: currentImageName +  imageExtension, /* "." +  extention enthaelt . schon */
						layout: selectedLayout, 
						/*
						lastAutoWidth: $("auto_breite").value, 
						lastAutoHeight: $("auto_hoehe").value,
						lastManualWidth: lastManualWidth,
						lastManualHeight: lastManualHeight,
						sizeFormat: sizeFormat,
						*/
						lastAutoWidth: lastAutoWidth, 
						lastAutoHeight: lastAutoHeight,
						sizeFormat: "manual",
						imgwidth: imgWidth,
						imgheight: imgHeight,
						width: parseInt(currentImage.style.width),
						height: parseInt(currentImage.style.height),
						tblwidth: parseInt($("table_vorschau").style.width),
						tblheight: parseInt($("table_vorschau").style.height),
						orgImgWidth: orgImgWidth,
						orgImgHeight: orgImgHeight,
						leftPosition: parseInt(currentImage.style.left),
						topPosition: parseInt(currentImage.style.top),
						flip: flip,
						rotated: rotated,
						selectedLayout: 1,
						imageExtension: imageExtension,
						currentImageName: currentImageName,
						currentStep: currentStep,
						maxSliderValue: maxSliderValue,
						lastMoveDraggerX: lastMoveDraggerX,
						lastMoveDraggerY: lastMoveDraggerY,
						dragwidth: parseInt($("thumbDrag").style.width),
						dragheight: parseInt($("thumbDrag").style.height)
					}; 
					
		var r = new Request({
		url: "save.php",
		method: 'post',
		data: data ,
		onComplete: function(responseHTML) {
		  if( callbackFunc ) {
			callbackFunc(JSON.decode(responseHTML), args);
		  }
		}
	}).post("save.php");
	//alert( JSON.encode(data)); 
}


function updateData(w, h) {
	saved = 1;
	if( w && h && currentImage ) {
		currentImage.style.width = w + "px";
		currentImage.style.height = h + "px";
	}
}

function myCallback(html, n) {
	var hidden1 = $('IMAGE');
	hidden1.value = currentImageName;

	var hidden2 = $('IMAGETYPE');
	hidden2.value = imageExtension;
	$('rotateImageForm').submit();

	/*
	var tmp0 = $("auto_breite").value;
	var tmp1 = $("auto_hoehe").value;
	*/
	/*
	$("auto_breite").value = tmp1;
	$("auto_hoehe").value = tmp0;
	*/
	$("newImage").style.left = "0px";
	$("newImage").style.top = "0px";
	
	updateMoveDragger();
	  
	var tmp1 = newWidthMM;
	var tmp2 = newHeightMM;
	newWidthMM = tmp2;
	newHeightMM = tmp1;
}

function scaleImageToLayout() {

}

function rotateImage() {
	
	zoom_image.rotate(); 
	
	return ;
	
	if (rotate) {
		rotate = false;
	}
	else {
		rotate = 1;
	}
	
	var tmp_width  = $("table_vorschau").style.width;
	var tmp_height = $("table_vorschau").style.height;
	
	$("table_vorschau").style.width  = tmp_height;
	$("table_vorschau").style.height = tmp_width;
	
	$("vorschau").style.width  = $("table_vorschau").style.width;
	$("vorschau").style.height = $("table_vorschau").style.height;
	
	layoutwidth = parseInt($("table_vorschau").style.width);
	layoutheight = parseInt($("table_vorschau").style.height);
	
	tmp_width  = lastAutoWidth;
	tmp_height = lastAutoHeight;
	
	lastAutoWidth  = tmp_height;
	lastAutoHeight = tmp_width;

	scaleImageToLayout()
	updateMoveDragger();
}

function updateImage(step) {
	
}

function updateMoveDragger() {
	
}

var miniOpts = {
	container: 'thumbnail',

	onStart: function(el) {
	},

    onDrag:function(el) {
/*****************************************************************************************************/
		
		var x = el.getPosition('thumbnail').x-1;
		var y = el.getPosition('thumbnail').y-1;
		var thumb = $('thumbnail');
		var image = $('newImage');

		var thumbnailLeft  = getPosition(thumb).left;
		var thumbnailTop   = getPosition(thumb).top;
		var imageLeft	   = getPosition(image).left;
		var imageTop	   = getPosition(image).top;

		zoom_image.move_thumb_drag( el , leftPosition, topPosition ); 
		return ; 
		

		w = parseInt(image.style.width);
		h = parseInt(image.style.height);

		sW = (w / thumbnailWidth );
		sH = (h / thumbnailHeight );

		// current Dragger position
		xDrag = getPosition($('thumbDrag')).left;
		yDrag = getPosition($('thumbDrag')).top;

		// Dragger Offset
		xOffset = (xDrag - thumbnailLeft);
		yOffset = (yDrag - thumbnailTop);
		
		lastMoveDraggerX = xOffset;
		lastMoveDraggerY = yOffset;

		// fix container-border
		xOffset += 2;
		yOffset += 2;

		// check, if dragger have reached borders
		// dragger is 20px in width and height, have 1px border at all
		addLeft = 0;
		addTop  = 0;

		if( xOffset == (thumbnailWidth) ) {
			xOffset -= 9;
			addLeft = 9 * sW;
		}

		if( yOffset == (thumbnailHeight) ) {
			yOffset -= 9;
			addTop = 9 * sH;
		}

		left = Math.ceil(-sW * xOffset) + addLeft;
		toleft = Math.ceil(sW * xOffset) + addLeft;
		topv  = Math.ceil(-sH * yOffset) + addTop;
		totop = Math.ceil(sH * yOffset) + addTop;

		// groesse der vorschau tabelle ermitteln, dann damit rechnen !!!
		var tblVorschau = $("table_vorschau");
		var tblWidth  = parseInt(tblVorschau.style.width);
		var tblHeight = parseInt(tblVorschau.style.height);

		maxleft = (w-tblWidth);
		maxtop  = (h-tblHeight);

		// check for right border
		if( maxleft >= toleft ) {
			image.style.left = left + 'px';
			leftPosition = left;
		}

		// check for bottom border
		if( maxtop >= totop ) {
			image.style.top = topv + 'px';
			topPosition = topv;
		}
		
		
		
/*
 		zoom_image.x0 =  leftPosition; 
		zoom_image.y0 =  topPosition; 
		zoom_image.showdebug(); 
*/		
	// zoom_image.set_image_xy( topPosition , leftPosition); 
	//	zoom_image.set_size(); 
	//	zoom_image.repaint(); 
/*****************************************************************************************************/
	}
};




function resetMoveDragger() {
	
}

function initMoveDragger() {

	var d = $('thumbDrag');

	d.style.display = "";
	d.style.position = "absolute";
	d.style.zIndex = 400;
	d.style.left = "0px";
	d.style.top = "0px";
	
	
}

function resetImage() {
	var iframe = $('iFrame1');
	iframe.src = "reset.php";
/*
	lastAutoWidth  = $("max_breite").value;
	lastAutoHeight = $("max_hoehe").value;
	
	
	saved = 1;
*/
}

function initThumbnail(w, h) {
	var thumb  = $('thumbnail');
	var ratio  = 1;
	var width  = w;
	var height = h;

	ratio = width / height;
	
	

	thumb.style.display = '';


	saved = 1;
}

function reinitThumbnail(src, w, h) {
	
	saved = 1;
}

function loadBack() {
	

}

/**********************************************************************************************************
 *
 * 	Galerie Funktionen
 *
 *********************************************************************************************************/


function closeUploadDialog() {
	if( uploaddialog ) {
	  for( i in uploaddialog ) {
		 document.body.removeChild(uploaddialog[i]);
	  }
	}
	uploaddialog = null;
}

function closeDialog() {
	if( dialog ) {
	  for( i in dialog )
		 document.body.removeChild(dialog[i]);
	}
	dialog = null;
	saved = 0;
}

function resetUploadDialog() {
	var message = $('message');
	message.style.display = "none";

	var uploadDialogContent = $('uploadDialogContent');
	uploadDialogContent.style.display = "";

	$('uploadForm').reset();
}

function uploadFile() {
	if( $('FILEUPLOAD1').value == "")
		return false;

	var frm = $('uploadForm');
	frm.target = "iFrame1";
	frm.submit();

	var uploadDialogContent = $('uploadDialogContent');
	uploadDialogContent.style.display = "none";

	var msg = '<span>Bitte warten, die Datei wird gerade auf den Server geladen...</span>';
	var message = $('message');
	message.innerHTML = msg;
	message.style.display = "block";
}

function createOverlay() {
	// create layer over layout to disable contents
	var dlayer = document.createElement('div');
	document.body.appendChild(dlayer);

	var w = window.innerWidth ? window.innerWidth : document.body.offsetWidth;
	var h = window.innerHeight ? window.innerHeight : document.body.offsetHeight;

	dlayer.style.width  = "100%"; //w + "px";
	dlayer.style.height = "100%"; //h + "px";
	dlayer.style.position = "absolute";
	dlayer.style.zIndex = nextlevel;
	dlayer.style.left = 0;
	dlayer.style.top = 0;
	dlayer.style.backgroundColor = "#000000";

	if( !Browser.Engine.trident )
	  	dlayer.setOpacity(0.4);
	else {
		dlayer.style.filter = "Alpha(opacity=40, finishopacity=0, style=0)";
	}

	nextlevel += 1000;

	return dlayer;
}

function showFileuploader() {
	// get layout container
	var el = $('contentWrapper');

	// get position of layout container
	var pos = getPosition(el);

	// get size from layout container
	var size = getSize(el);

	dlayer = createOverlay();

	// create simple drop shadow
	var slayer = document.createElement("div");
	slayer.style.backgroundColor = "#333";
	slayer.style.width = 300 + "px";
	slayer.style.height = 150 +  "px";
	slayer.style.left = ((size.width / 2) - 150) + "px";
	slayer.style.top  = ((size.height / 2) - 150) + "px";
	if( !Browser.Engine.trident )
	  	slayer.setOpacity(0.5);
	else {
		slayer.style.filter = "Alpha(opacity=50, finishopacity=0, style=0)";
	}
	slayer.style.position = "absolute";
	slayer.style.zIndex = nextlevel;
	nextlevel += 1000;

	document.body.appendChild(slayer);

	var ulayer = document.createElement("div");
	ulayer.style.backgroundColor = "#B8C9D7";
	ulayer.style.border = "1px solid #333";
	ulayer.style.width = "300px";
	ulayer.style.height = "150px";
	ulayer.style.position = "absolute";
	ulayer.style.left = (parseInt(slayer.style.left) - 4) + "px";
	ulayer.style.top = (parseInt(slayer.style.top) - 4) + "px";
	ulayer.style.zIndex = nextlevel;
	nextlevel += 1000;

	document.body.appendChild(ulayer);

	var html = '<p style="display: block;margin-bottom: 30px;margin-top: 10px;font-size: 1.3em;font-weight: bold;text-align: center;">Bild hochladen</p>';
	html += '<div id="message" style="text-align: center;display: none;"></div>';
	html += '<div id="uploadDialogContent">';
	html += '<form id="uploadForm" name="uploadForm" action="upload.php" method="POST" enctype="multipart/form-data" target="iFrame1" onsubmit="return false;">';
	html += '<div align="center" style="display: block;"><input type="FILE" name="FILEUPLOAD1" id="FILEUPLOAD1" /></div>';
	html += '<div style="width: 100%; text-align: right;position: absolute; right: 5px; bottom: 5px;">';
	html += '<input type="submit" value="upload" onclick="uploadFile();"/>';
	html += '&nbsp;&nbsp;&nbsp;';
	html += '<input type="button" value="abbrechen" onclick="closeUploadDialog()" />';
	html += '</div>';
	html += '</form>';
	html += '</div>';

	ulayer.innerHTML = html;

	//finally createdialogObject - needed for destruction of container
	uploaddialog = new Object();
	uploaddialog.dlayer = dlayer;
	uploaddialog.slayer = slayer;
	uploaddialog.ulayer = ulayer;
}

function showfiledialog() {
	var dlayer = createOverlay();
	var size = getSize();

	var slayer = document.createElement("div");
	slayer.style.backgroundColor = "#333";
	slayer.style.width = 700 + "px";
	slayer.style.height = 500 +  "px";
	slayer.style.left = ((size.width / 2) - 350) + "px";
	slayer.style.top  = (size.height / 5) + "px";
	if( !Browser.Engine.trident )
	  	slayer.setOpacity(0.5);
	else {
		slayer.style.filter = "Alpha(opacity=50, finishopacity=0, style=0)";
	}
	slayer.style.position = "absolute";
	slayer.style.zIndex = nextlevel;
	nextlevel += 1000;

	document.body.appendChild(slayer);

	var ulayer = document.createElement("div");
	ulayer.style.backgroundColor = "#B8C9D7";
	ulayer.style.border = "1px solid #333";
	ulayer.style.width = "700px";
	ulayer.style.height = "500px";
	ulayer.style.position = "absolute";
	ulayer.style.left = (parseInt(slayer.style.left) - 4) + "px";
	ulayer.style.top = (parseInt(slayer.style.top) - 4) + "px";
	ulayer.style.zIndex = nextlevel;
	nextlevel += 1000;

	document.body.appendChild(ulayer);
	if( !Browser.Engine.trident ) {
	  ulayer.setOpacity(0);
	  ulayer.fade(1);
	}

	var contentTbl   = document.createElement("div");
	contentTbl.style.height = "430px";
	contentTbl.border = "1";
	contentTbl.width = "100%";
	contentTbl.position = "relative";

	var tLeft  = document.createElement("div");
	galerie    = document.createElement("div");

	contentTbl.appendChild(tLeft);
	contentTbl.appendChild(galerie);

	var trash = document.createElement("img");
	trash.src = "media/images/trash.png";
	trash.width = 100;
	trash.height = 100;
	trash.style.position = "absolute";
	trash.style.top = "330px";
	trash.style.left = "25px";
	trash.className = "trash";
	trash.setAttribute("id", "trash");
	trash.id = "trash";

	var trashlist = document.createElement("ul");
	trashlist.className = "trashcan";
	trashlist.id = "trashcan";
	trashlist.setAttribute("id", "trashcan");
	trashlist.style.display = "";
	trashlist.style.width = "150px";
	trashlist.style.top = "0px";
	trashlist.style.bottom = "60px";
	trashlist.style.position = "absolute";
	trashlist.style.zIndex = 1000;
	trashlist.style.paddingTop = "100px";

	var trashinfo = document.createElement("p");
	trashinfo.style.padding = "5px";
	trashinfo.style.fontSize = "1.2em";
	trashinfo.innerHTML = "Ziehen Sie ein Thumbnail auf diese Fl&auml;che, um das Bild zu l&ouml;schen.";

	tLeft.appendChild(trashinfo);
	tLeft.appendChild(trashlist);
	tLeft.appendChild(trash);

	ulayer.appendChild(contentTbl);

	var buttonbar  = document.createElement("div");
	var buttonbarL = document.createElement("div");
	var buttonbarR = document.createElement("div");

	buttonbarR.innerHTML = '<input type="button" value="ausw&auml;hlen" id="selectBtn" disabled="disabled" onclick="selectImage();" />&nbsp;&nbsp;&nbsp;<input type="button" value="abbrechen" onclick="closeDialog();" />';
	buttonbarR.style.textAlign = "right";
	buttonbarR.style.position = "absolute";
	buttonbarR.style.right = "10px";
	buttonbarR.style.bottom = "10px";

	buttonbarL.innerHTML = '<input type="button" id="uploadButton" value="upload" onclick="showFileuploader();" />';
	buttonbarL.style.textAlign = "left";
	buttonbarL.style.position = "absolute";
	buttonbarL.style.left = "170px";
	buttonbarL.style.bottom = "10px";

	buttonbar.appendChild(buttonbarL);
	buttonbar.appendChild(buttonbarR);

	ulayer.appendChild(buttonbar);

	tLeft.setAttribute("valign", "bottom");
	tLeft.style.width = "150px";
	galerie.style.width = "530px";
	galerie.style.position = "absolute";
	galerie.style.left = "155px";
	galerie.style.top = "0px";
	galerie.style.bottom = "60px";
	galerie.style.zIndex = nextlevel;
	nextlevel += 1000;

	requestGalerie();

	dialog = new Object();
	dialog.dlayer = dlayer;
	dialog.slayer = slayer;
	dialog.ulayer = ulayer;
}

function appendGalerie(responseText) {
	var obj = JSON.decode(responseText);
	if( galerie ) {
		galerie.innerHTML = obj.html;

		var drop = $("trash");
		var dosort = true;
		var items = $("items");
		var images = items ? items.getElementsByTagName("img") : new Array();

		if( items && images.length > 0 ) {
		var s = new Sortables('#items, #trashcan', {
			clone: true,
			revert: false,
			opacity: 0.4,

			onStart: function(el) {
				el.style.zIndex = nextlevel;
				nextlevel += 1000;
			},

			onComplete: function(el) {
				el.style.visible = "false";

				if(el.parentNode.className == "trashcan") {

				if( confirm("Element entfernen ?") ) {
				    var img = el.getElementsByTagName("img")[0];

				    if( img )
				      senddata = { img: img.src  };
				    else
				      senddata = { img: "nix" };

				    senddata = null;
				    req = new Request({
				        url: "drop.php",
				        method: "post",
				        data: { 'img': img.src  },
				        async: false
				    }).send();
				    el.destroy();
				  }
				  else {
				    el.style.visible = "true";
				    $('items').appendChild(el);
				  }
				}
			}
		});
	      }
	}

	$exec(obj.js);

}

function requestGalerie() {
	req = new Request({
	url: "galerie.php",
	method: 'get',
	async: false,
	onComplete: function(response) {
		appendGalerie(response);
	  }
	}).send();
}

function demarkImage() {
  if( selectedCell ) {
	  selectedCell.style.background = "transparent";
  }
}

function markImage(obj) {
  demarkImage();

  obj.style.background = "#4682B4";

  selectedCell = obj;
  $('selectBtn').disabled = null;
}

function selectImage() {
	var cell = selectedCell;
	var cellimg = cell.getElementsByTagName("img")[0];

	req = new Request.HTML({
		data: { image: cellimg.src },

		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
		
		imgObject = JSON.decode(responseHTML);
		currentImageName = imgObject.name;
		imageExtension = imgObject.extension;

		var thumb  = $('thumbnail');
		if( !thumb ) {
			thumb = document.createElement("img");
			thumb.setAttribute("id", "thumbnail");
			thumb.id = "thumbnail";
			$('imgContainer').appendChild(thumb);
		}

		var vorschau = document.getElementById("vorschau");
		var image    = vorschau.getElementsByTagName("img")[0];
		if( image )
			vorschau.removeChild(image);
			thumb.src = imgObject.image;

			imgWidth  	  = imgObject.width;
			imgHeight 	  = imgObject.height;
			orgImgWidth   = imgObject.orgwidth;
			orgImgHeight  = imgObject.orgheight;
			
			lastAutoWidth    = imgObject.breite;
			lastAutoHeight   = imgObject.hoehe;
			lastManualWidth  = lastAutoWidth;
			lastManualHeight = lastAutoHeight;
			
			
			/*
			autobreitefeld = $("auto_breite");
			autobreitefeld.value = lastAutoWidth;
			autohoehefeld = $("auto_hoehe");
			autohoehefeld.value = lastAutoHeight;
			*/
			
			breitefeld = $("max_breite");
			breitefeld.value = lastAutoWidth;
			hoehefeld = $("max_hoehe");
			hoehefeld.value = lastAutoHeight;

			/*
			manualwidth = $("individuell_breite");
			manualwidth.value = 0;
			manualheight = $("individuell_hoehe");
			manualheight.value = 0;
			*/
			
			currentImage = document.createElement("img");
			var d = new Date();
			
			enableFormats();
			updateSizeFormats();
			initThumbnail(imgWidth, imgHeight);
			resetApplication();
			
			currentImage.src = imgObject.image + "?" + d.getTime();
			currentImage.id = "newImage";
			currentImage.setAttribute("id", "newImage");
			$("vorschau").appendChild(currentImage);
			
			currentImage.width = imgWidth;
			currentImage.height = imgHeight;
			currentImage.style.width = imgWidth + "px";
			currentImage.style.height = imgHeight + "px";
			currentImage.style.zIndex = "1";
			currentImage.style.position = "absolute";
			currentImage.style.left = "0px";
			currentImage.style.top = "0px";
			
			closeDialog();			
			
			leftPosition = 0;
			topPosition = 0;
			
			layoutwidth = parseInt($("table_vorschau").style.width);
			layoutheight = parseInt($("table_vorschau").style.height);
			
			
			doLayout();
			//initThumbnail(imgWidth, imgHeight);
			
			//$("panelwidth").innerHTML = lastAutoWidth;
			//$("panelheight").innerHTML = lastAutoHeight;
			newHeightMM = lastAutoHeight;
			newWidthMM = lastAutoWidth;
			
			var widthMM = $("max_hoehe").value;
			var heightMM = $("max_hoehe").value;
			var ratio = widthMM / heightMM;
		
			newWidthMM  = parseInt(lastAutoWidth);
			newHeightMM = parseInt(lastAutoHeight);
		
			var faktor = widthMM / newWidthMM;

			var pixW = Math.round((faktor * 350)-350 / imgWidth); // val is MM !!!
			var pixH = Math.round(pixW * ratio);
			
			slider.steps = pixW;
			maxSliderValue = pixW;
			slider.set(0);
			
			if( $("startDIV") )
				$("startDIV").style.display = "none";
			
			$("applicationDIV").style.display = "";
			
			switchImages();
		}
	}).post("copyimage.php");
}

function doLayout() {
	/*
	currentImage = currentImage ? currentImage : $("newImage");
	if( currentImage ) {		
		var layoutContainer = $("layoutContainer");
		//selectedLayout = ( selectedLayout > 0 ) ? selectedLayout : 1;
		selectLayout($("layout1Select"), 1);//selectedLayout);

		var mmSize = calcImageSize();

		mmWidth  = (mmSize.width);
		mmHeight = (mmSize.height);

		breitefeld = $("max_breite");
		hoehefeld = $("max_hoehe");
		breitefeld.value = mmWidth;
		hoehefeld.value  = mmHeight;

		breitefeld.disabled = "disabled";
		hoehefeld.disabled  = "disabled";

		
		//autobreite = $("auto_breite");
		//autohoehe  = $("auto_hoehe");

		//autobreite.value = lastAutoWidth ? lastAutoWidth : mmWidth;
		//autohoehe.value  = lastAutoHeight ? lastAutoHeight : mmHeight;

		//autobreite.disabled = false;
		//autohoehe.disabled  = false;
		//setLayoutSelection();
		
		//currentImage.style.left = leftPosition + "px";
		//currentImage.style.top = topPosition + "px";
		
		updateMoveDragger();
	}
	*/
}

function selectLayout(obj, t) {
	var aufteilung = $("aufteilung").getElementsByTagName("li");

	if( currentImageName ) {
	
		// reset active class
		/*
		for( var i = 0; i < aufteilung.length; i++) {
			if ( aufteilung[i].className.indexOf("typ") != -1 )
			aufteilung[i].className = "typ";
		}

		// get the current ul -> li and set as active state
		if( obj ) {
			var li = obj.parentNode;
			li.className = "typ active";
		}
		*/
		// verfiy layout type
		selectedLayout = parseInt(t);
				
		var tmp1 = parseInt($("table_vorschau").style.width);
		var tmp2 = parseInt($("table_vorschau").style.height);		
		
		req = new Request.HTML({
			data: {'type': selectedLayout.toString(), 
				   'image': currentImageName + "." + imageExtension, 
				   layout: rotate == 1 ? "rotate" : "manual", //sizeFormat,
				   width: tmp1,
				   height: tmp2
		    },
			onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				var response_str = JSON.decode(responseHTML);
				$("layoutContainer").innerHTML = response_str['html'];
				$("vorschau").style.top = "40px";

				$("vorschau").style.width  = $("table_vorschau").style.width;
				$("vorschau").style.height = $("table_vorschau").style.height;
				
				currentImage.style.left = leftPosition + "px";
				currentImage.style.top = topPosition + "px";
				
				tblwidth  = parseInt($("table_vorschau").style.width);
				tblheight = parseInt($("table_vorschau").style.height);
				
			}
		}).post("layout.php");
		
		/*
		switch( selectedLayout ) {
		  case 1: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 2: $("panelwidth").innerHTML = Math.round(newWidthMM / 3);
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 3: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = Math.round(newHeightMM / 3);
				  break;
		  case 4: $("panelwidth").innerHTML = Math.round(newWidthMM / 2);
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 5: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = Math.round(newHeightMM / 2);
				  break;
		  case 6: $("panelwidth").innerHTML = Math.round(newWidthMM  / 2);
				  $("panelheight").innerHTML = Math.round(newHeightMM / 2);
				  break;
		  case 7: $("panelwidth").innerHTML = Math.round(newWidthMM / 4);
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 8: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = Math.round(newHeightMM / 4);
				  break;
		}
		*/
	}
}

function selectRotateLayout(obj, t) {
	var aufteilung = $("aufteilung").getElementsByTagName("li");

	if( currentImageName ) {
	
		// reset active class
		for( var i = 0; i < aufteilung.length; i++) {
			if ( aufteilung[i].className.indexOf("typ") != -1 )
			aufteilung[i].className = "typ";
		}

		// get the current ul -> li and set as active state
		if( obj ) {
			var li = obj.parentNode;
			li.className = "typ active";
		}
		
		var img = $("newImage");
		var imgw = parseInt(img.style.width);
		var imgh = parseInt(img.style.height);
		tblwidth  = parseInt($("table_vorschau").style.width);
		tblheight = parseInt($("table_vorschau").style.height);
		
		var imgh_1 = imgh;
		var imgw_1 = imgw;
		
		if( imgw < tblwidth ) {
			imgw_1 = 350;
			imgh_1 = Math.round(350 / (imgw / imgh));
		}

		if( imgh < tblheight ) {
			imgh_1 = 350;
			imgw_1 = Math.round(350 * (imgw / imgh));
		}
		
		img.style.width = imgw_1 + "px";
		img.style.height = imgh_1 + "px";

		//initMoveDragger();
		
		req = new Request.HTML({
			data: {'type': selectedLayout.toString(), 
				   'image': currentImageName + "." + imageExtension, 
				   layout: "rotate",
				   width: parseInt($("table_vorschau").style.width),
				   height: parseInt($("table_vorschau").style.height)
		    },
			onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
				var response_str = JSON.decode(responseHTML);
				$("layoutContainer").innerHTML = response_str['html'];
				$("vorschau").style.width  = $("table_vorschau").style.width;
				$("vorschau").style.height = $("table_vorschau").style.height;
				$("vorschau").style.top = "40px";
				
				currentImage.style.left = leftPosition + "px";
				currentImage.style.top = topPosition + "px";
				
				tblwidth  = parseInt($("table_vorschau").style.width);
				tblheight = parseInt($("table_vorschau").style.height);
				
				updateMoveDragger();
			}
		}).post("layout.php");
		
		/*
		switch( selectedLayout ) {
		  case 1: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 2: $("panelwidth").innerHTML = Math.round(newWidthMM / 3);
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 3: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = Math.round(newHeightMM / 3);
				  break;
		  case 4: $("panelwidth").innerHTML = Math.round(newWidthMM / 2);
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 5: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = Math.round(newHeightMM / 2);
				  break;
		  case 6: $("panelwidth").innerHTML = Math.round(newWidthMM  / 2);
				  $("panelheight").innerHTML = Math.round(newHeightMM / 2);
				  break;
		  case 7: $("panelwidth").innerHTML = Math.round(newWidthMM / 4);
				  $("panelheight").innerHTML = newHeightMM;
				  break;
		  case 8: $("panelwidth").innerHTML = newWidthMM;
				  $("panelheight").innerHTML = Math.round(newHeightMM / 4);
				  break;
		}
		*/
	}
}

function setLayoutSelection() {
		var layoutName = "layout" + selectedLayout + "Select";
		var layout = $("aufteilung");
		var li = layout.getElementsByTagName("li");

		for(i = 0; i < li.length; i++ ) {
			var l = li[i];

			if( l && l.className == "typ active" ) {
					l.className = "typ";
			}

			var a = l.getElementsByTagName("a")[0];
			if( a && a.id == layoutName ) {
					l.className = "typ active";
			}
		}
}

function selectPreviewLayout(obj, t) {
	var aufteilung = $("aufteilung").getElementsByTagName("li");
	
	// reset active class
	for( var i = 0; i < aufteilung.length; i++) {
		if ( aufteilung[i].className.indexOf("typ") != -1 )
			aufteilung[i].className = "typ";
	}

	// get the current ul -> li and set as active state
	var li = obj.parentNode;
	li.className = "typ active";

	// verfiy layout type
	var ltype = parseInt(t);

	req = new Request.HTML({
		data: {type: ltype.toString()},
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			var response_str = JSON.decode(responseHTML);
			$("layoutContainer").innerHTML = response_str;
			var tbl_element = $("table_vorschau");
			tbl_element.makeDraggable();
		}
	}).post("layoutpreview.php");
}

function onRoomSelect(html, l) {
	document.location.replace(l);
}

function selectRoom(num) {
	switch( num ) {
		case '1': loc = "wohnzimmer.php"; 		break;
		case '2': loc = "esszimmer.php"; 		break;
		case '3': loc = "schlafzimmer.php"; 	break;
		case '4': loc = "flur.php"; 				break;
		default:  loc = "buttons.php";
	}

		
	//if( currentImageName ) {
		//saveSettings(onRoomSelect, loc);
		zoom_image.save(onRoomSelect, loc);
		//alert( 'saved') ;
	//} else {
	//	alert('kein Bild vorhanden.');
	//}
}

/*
 *
 *
 * 	Handle image size ( autosize / individual size )
 *
 *
*/
function setAutoSize(field) {
	var img = currentImage;

	var widthMM = $("max_breite").value;
	var heightMM = $("max_hoehe").value;
	
	var ratio = widthMM / heightMM;

	// set auto fields to mm values
	var reset = null;
	if( field.id == "auto_breite" ) {
		newWidthMM  = field.value;
		newHeightMM = newWidthMM / ratio;

		$('auto_hoehe').value = Math.round(newHeightMM);

		if( newWidthMM.toInt() > widthMM.toInt() ) {
			alert("Ein Fehler ist aufgetreten:\nDie neue Angabe der Breite darf nicht h�her als das Original (" + widthMM + "mm) sein.");
			reset = 1;
		}
		else {
			if( newWidthMM.toInt() == 0 || newWidthMM == "0" || newWidthMM.charAt(0) == "0" )
			{
				alert("Ein Fehler ist aufgetreten:\nDie Angabe der neuen Breite darf nicht '0' sein.");
				reset = 1;
			}
		}
	}
	else
	if( field.id == "auto_hoehe" ) {
		newHeightMM = field.value;
		newWidthMM	= newHeightMM * ratio;
		
		$('auto_breite').value = Math.round(newWidthMM);

		if( newHeightMM.toInt() > heightMM.toInt() ) {
			alert("Ein Fehler ist aufgetreten:\nDie neue Angabe der H�he darf nicht h�her als das Original (" + heightMM + "mm) sein.");
			reset = 1;
		}
		else {
			if( newHeightMM.toInt() == 0 || newHeightMM == "0" || newHeightMM.charAt(0) == "0" )
			{
				alert("Ein Fehler ist aufgetreten:\nDie Angabe der neuen H�he darf nicht '0' sein.");
				reset = 1;
			}
		}
	}

	if( reset ) {
		$("auto_breite").value = widthMM;
		$("auto_hoehe").value  = heightMM;

		newWidthMM  = widthMM;
		newHeightMM = heightMM;
	}
	
	var faktor = widthMM / newWidthMM;

	var orgSize = calcImageSize();
		
	var pixW = Math.round((faktor * 400)-400 / imgWidth); // val is MM !!!
	var pixH = Math.round(pixW / ratio);
		
	slider.steps = pixW;
	maxSliderValue = pixW;
	slider.set(0);
	
	updateMoveDragger();
	
	switch( selectedLayout ) {
	  case 1: $("panelwidth").innerHTML = newWidthMM;
			  $("panelheight").innerHTML = newHeightMM;
			  break;
	  case 2: $("panelwidth").innerHTML = Math.round(newWidthMM / 3);
			  $("panelheight").innerHTML = newHeightMM;
			  break;
	  case 3: $("panelwidth").innerHTML = newWidthMM;
			  $("panelheight").innerHTML = Math.round(newHeightMM / 3);
			  break;
	  case 4: $("panelwidth").innerHTML = Math.round(newWidthMM / 2);
			  $("panelheight").innerHTML = newHeightMM;
			  break;
	  case 5: $("panelwidth").innerHTML = newWidthMM;
			  $("panelheight").innerHTML = Math.round(newHeightMM / 2);
			  break;
	  case 6: $("panelwidth").innerHTML = Math.round(newWidthMM  / 2);
			  $("panelheight").innerHTML = Math.round(newHeightMM / 2);
			  break;
	  case 7: $("panelwidth").innerHTML = Math.round(newWidthMM / 4);
			  $("panelheight").innerHTML = newHeightMM;
			  break;
	  case 8: $("panelwidth").innerHTML = newWidthMM;
			  $("panelheight").innerHTML = Math.round(newHeightMM / 4);
			  break;
	}
}

function sizeResetImage() {
	$("newImage").style.width = imgWidth + "px";
	$("newImage").style.height = imgHeight + "px";
	doLayout();
	initMoveDragger();
	slider.set(0);
	updateMoveDragger();
}

function setSizeFormat(fmt) {
	sizeFormat = fmt;
	switch( fmt ) {
			case "auto":	disableField($("individuell_breite"));
							disableField($("individuell_hoehe"));
							enableField($("auto_breite"));
							enableField($("auto_hoehe"));
							//setAutoSize($("auto_breite"));
							sizeResetImage();
							break;
							
			case "manual":  disableField($("auto_breite"));
							disableField($("auto_hoehe"));
							enableField($("individuell_breite"));
							enableField($("individuell_hoehe"));
							//setManualSize($("auto_hoehe"));
							sizeResetImage();
							break;
			default:;
	}
}

var changeFormat = 0; 
function updatePreview( radio ) {
	changeFormat ++; 
	//alert( "format" + changeFormat );	 	
	//zoom_image.debug1= 2; 
	
	sizeFormat = radio.value.split("x");
	
	width 	= (sizeFormat[0]) * 10;
	height 	= (sizeFormat[1]) * 10;
	zoom_image.set_format( width , height ); 

	return ; 
	
}

function updatePreview_old(radio) {

}

function setManualSize(field) {

}
/**************************************************************************************

	MOVE IMAGE BY HAND

**************************************************************************************/

function moveTo(dir) {

}

/**************************************************************************************

	ORDER PROCESS

**************************************************************************************/

function onOrder() {
	var r = new Request({
		url: "orderrequest.php",
		method: 'post',
		/*data: { 
			image: currentImageName + "." + imageExtension,
			width: parseInt(currentImage.style.width), 
			height: parseInt(currentImage.style.height) ,
			printWidth: lastAutoWidth,
			printHeight: lastAutoHeight,
			zoom: currentStep, 
			offsetLeft: leftPosition, 
			offsetTop: topPosition,
			rotated: rotate
		}*/
		
			data: { 
			image: currentImageName + "." + imageExtension,
			width: zoom_image.w, 
			height: zoom_image.h ,
			printWidth: lastAutoWidth,
			printHeight: lastAutoHeight,
			zoom: zoom_image.zoom_level ,
			offsetLeft: zoom_image.x0, 
			offsetTop: zoom_image.y0,
			rotated: zoom_image.rotate_state * 90
		},
		onRequest: function() {
			var msg = '<span>Bitte warten, Daten werden gespeichert...</span>';
			var message = $('ordermessage');
			message.innerHTML = msg;
			message.style.display = "block";
		},
		onComplete: function(responseHTML) {
			//alert( 'to cart');
			var message = $('ordermessage');
			
			message.style.display = "none";
	
			document.location = "cart.php";
		}
	}).post("orderrequest.php");
}

function doOrder() {
	if( currentImage ) {
//		saveSettings(onOrder, null);
		zoom_image.save(onOrder, null);
	}else {
		alert('Kein Bild vorhanden.');
	}
}

function editImage(path, cid) {
	var r = new Request.JSON({
		url: "editimage.php",
		method: "post",
		data: { image: path, cart_id: cid },
		onComplete: function(responseHTML) {
			if( responseHTML.status == "EDITOK" ) {
				alert('Sie wechseln in den Bearbeitungs-Modus.\nDas Bild wird dazu aus dem Warenkorb entfernt.\n\nWenn Sie Ihr Bild bearbeitet haben, klicken Sie bitte nochmal auf "Jetzt bestellen".')
				document.location = "index.php?back=2&msg=edit";
			}
			else {
				alert("Das angegebene Bild konnte nicht gefunden werden.");
			}
		}
	}).post("editimage.php");
}

/***************************************************************************************

	GENERAL WINDOW EVENT 

***************************************************************************************/
if( window.addEvent ) {
window.addEvent("domready",function(){ 
	if( $("scaleSlider") ) {
		maxSliderValue = 0;
		currentStep = 0;
		
		slider = new Slider($("scaleSlider"), $("knob"), {
			steps: maxSliderValue,
			onChange: function(step){
				updateImage(step);
			}
		}).set(currentStep);
		
		if(Browser.Engine.trident) {
			$("knob").ondragstart = function() {
				return false;
			};
		}
	}
});
}


var miniOpts2 = {
	container: 'thumbnail',

	onStart: function(el) {
	},

    onDrag:function(el) {
/*****************************************************************************************************/
		
		var x = el.getPosition('thumbnail').x-1;
		var y = el.getPosition('thumbnail').y-1;
		var thumb = $('thumbnail');
		var image = $('newImage');

		var thumbnailLeft  = getPosition(thumb).left;
		var thumbnailTop   = getPosition(thumb).top;
		var imageLeft	   = getPosition(image).left;
		var imageTop	   = getPosition(image).top;

		zoom_image.move_thumb_drag( el , leftPosition, topPosition ); 
		return ; 
		
/*****************************************************************************************************/
	}
};

var zoom_image; 
var zoom_image_debug = false; 
var canvas_w_max = 350;  // max w 
var canvas_h_max = 350;  // max h
var thumb_w_max  = 122; 
var thumb_h_max  = 122; 
var currentImage; 
	
//var canvas_ratio        = 1.5 ; // 30cm/20cm; // w : h

function ZoomImage(data2){ // w_orig, h_orig, path, name , x0, y0 , zoom , w, h) {
	if (!currentImage) {
		currentImage = data.currentImageName;
		alert('no image');
		
	}
	
	
	// handle for real images and divs
	this.image 				= $('newImage');
	this.thumb 				= $('thumbnail');
	this.thumb_drag 		= $('thumbDrag');
	this.debug_msg 		= $('debug_msg');
	this.debug_log 		= $('debug_log');
	this.canvas 			= $("viewport");
	this.vorschau 			= $('vorschau');
	this.table_vorschau 	= $('table_vorschau');
	
}

ZoomImage.prototype.init = function (data2){
	changeFormat = 0; 
	this.stop=0;
	this.path 			= data2.image ;
	this.name 			= data2.name  ;
	this.w_orig 		= parseInt(data2.w_orig) ; 
	this.h_orig 		= parseInt(data2.h_orig) ; 
	this.w 				= parseInt(data2.w)		; // always changes !
	this.h 				= parseInt(data2.h)		;
	this.w_init			= parseInt(data2.w_init); 
	this.h_init			= parseInt(data2.h_init);
	
	// default
	//this.rotate_state	= 0; 
	this.flip_v_state = parseInt(data2.flip_v); 
	this.flip_h_state = parseInt(data2.flip_h); 

	this.flip( 'auto' ); // restore _state
	
	
	// from session
	this.zoom_level   = parseFloat(data2.zoom) ; 
	this.x0 				= parseInt(data2.x0) 	 ;
	this.y0 				= parseInt(data2.y0) 	 ;

	
	this.rotate_state	= parseInt( data2.rotated ); 
	
	
	
	this.image_zoom = canvas_w_max / this.w_orig; 
	this.thumb_zoom = thumb_w_max  / this.w_orig; 
	this.orientation = data2.orientation; // 'auto'; // or 'vertical' 
	this.canvas_ratio = 1.5; 
	
	this.canvas_h = canvas_h_max; 
	this.canvas_w = canvas_w_max; 
	this.thumb_w = thumb_w_max; 
	this.thumb_h = thumb_h_max; 
	this.thumb_drag_w = thumb_w_max; 
	this.thumb_drag_h = thumb_h_max; 
	this.thumb_drag_x0 = 0; 
	this.thumb_drag_y0 = 0; 
	this.repeat_state = 0; 
	this.repeat_delay = 100 ; // milliseconds for setTimeout
	this.move_speed = 1; // how many pixels to move with "positionieren"

	this.zoom_level_max = 4; 
	this.zoom_level_min = 1; 
	this.zoom_speed = 0.25;
	
		
	this.set_image_zoom(); /* orig to screen */
	
	
	//alert( JSON.encode( data2 )); 
	
    
    if (0) {
        if (this.rotate_state > 0 /* 1 oder 90 */) {
			this.set_orientation('vertical');
		}
		else {
			if (this.rotate_state == 0) {
				this.set_orientation('horizontal');
			}
			else {
				this.set_orientation(this.orientation);
			}
		}
    }
	if (this.orientation == "auto") {
   	this.set_orientation(this.orientation);
   }
	//this.set_image_xy(this.x0,this.y0); // use function to set thumb also
	//alert( this.orientation); 
	
	//this.check_limits(); 
	
	this.set_canvas(); 
	this.set_size(); 
	/* 
	this.move(0,1); 
	this.move(0,-1);
	*/
	//this.check_limits(); 
	
	
	this.repaint();
	//this.check_limits(); 
	



	this.thumb_drag.style.display = "";
	this.thumb_drag.style.position = "absolute";
	this.thumb_drag.style.zIndex = 400;
	this.thumb_drag.style.left = "0px";
	this.thumb_drag.style.top = "0px";
	
	// enable drag+drop
	dm = new Drag.Move(this.thumb_drag, miniOpts2);

	if (Browser.Engine.trident5) {
		$('thumbDrag').ondragstart = function(){
			return false;
		};
	}

	//alert( JSON.encode(this )); 

}

ZoomImage.prototype.save = function saveSettings(callbackFunc, args) {
	

		rotated 			= ( zoom_image.orientation == 'horizontal' ) ? 0 : 1; 
		topPosition 	= zoom_image.x0; 
		leftPosition 	= zoom_image.y0; 
		
		
		data = { 
						image: this.path , /* "." +  extention enthaelt . schon */
						layout: selectedLayout, 
						w_orig: this.w_orig,
						h_orig: this.h_orig,
						w_init: this.w_init,
						h_init: this.h_init,
						x0: this.x0,
						y0: this.y0,
						w: this.w,
						h: this.h,
						format_w: this.format_w,
						format_h: this.format_h,
						
						flip_h: this.flip_h_state ,
						flip_v: this.flip_v_state ,
						flip : flip,
						zoom: this.zoom_level ,
						rotated:  this.rotate_state,
						orientation: this.orientation, 
						selectedLayout: 1,
						imageExtension: imageExtension,
						currentImageName: currentImageName,
						currentStep: currentStep, 
						tblwidth: parseInt($("table_vorschau").style.width),
						tblheight: parseInt($("table_vorschau").style.height),
						
						/* OLD */ 
						lastAutoWidth: lastAutoWidth, 
						lastAutoHeight: lastAutoHeight,
						sizeFormat: "manual",
						imgwidth: imgWidth,
						imgheight: imgHeight,
						width: parseInt(currentImage.style.width),
						height: parseInt(currentImage.style.height),
						tblwidth: parseInt($("table_vorschau").style.width),
						tblheight: parseInt($("table_vorschau").style.height),
						orgImgWidth: orgImgWidth,
						orgImgHeight: orgImgHeight,
						leftPosition: parseInt(currentImage.style.left),
						topPosition: parseInt(currentImage.style.top),
						maxSliderValue: maxSliderValue,
						lastMoveDraggerX: lastMoveDraggerX,
						lastMoveDraggerY: lastMoveDraggerY,
						dragwidth: parseInt($("thumbDrag").style.width),
						dragheight: parseInt($("thumbDrag").style.height)
					}; 
					
		var r = new Request({
		url: "save.php",
		method: 'post',
		data: data ,
		onComplete: function(responseHTML) {
		  if( callbackFunc ) {
			callbackFunc(JSON.decode(responseHTML), args);
		  }
		}
	}).post("save.php");
	//alert( JSON.encode(data)); 
}

ZoomImage.prototype.set_orientation = function ( new_orientation ) {
	this.log('set_orientation set: ' + new_orientation ); 
	
	if (new_orientation == 'auto') {
   	if (this.w_orig > this.h_orig) {
   		this.orientation = 'horizontal';
		}
   	else {
   		this.orientation = 'vertical';
   	}
   } 
	if ( new_orientation =='horizontal' ) {
		this.orientation = 'horizontal'; 
	}
	if ( new_orientation =='vertical' ) {
		this.orientation = 'vertical'; 
	}
	//return this.orientation;
}

ZoomImage.prototype.set_size = function(){
//	this.log('set_size'); 
	
	this.set_image_zoom(); 
		this.w = parseInt(this.w_orig * this.image_zoom * this.zoom_level);
   	this.h = parseInt(this.h_orig * this.image_zoom * this.zoom_level);
   //this.check_limits(); 
	
	this.log( 'set size-> w:'+ this.w + " h: "+ this.h); 

	this.set_thumb_zoom(); 
	this.thumb_w = parseInt( this.w_orig * this.thumb_zoom ) ; 
	this.thumb_h = parseInt( this.h_orig * this.thumb_zoom ) ; 
	
	if (this.orientation == 'horizontal') {
   	this.thumb_drag_w = parseInt(this.w_orig / this.zoom_level * this.thumb_zoom); 
		this.thumb_drag_h = parseInt(this.w_orig / this.zoom_level * this.thumb_zoom / this.canvas_ratio);
	} else {
		this.thumb_drag_h = parseInt(this.h_orig / this.zoom_level * this.thumb_zoom);
   	this.thumb_drag_w = parseInt(this.h_orig / this.zoom_level * this.thumb_zoom / this.canvas_ratio ); 
	}

	//leftPosition   	= - this.x0;
	//topPosition		= - this.y0;
}

ZoomImage.prototype.set_canvas = function(force){
	this.log('set_canvas');
	
	if (this.orientation == 'horizontal') {
		this.canvas_w = canvas_w_max;
		this.canvas_h = Math.round(canvas_w_max / this.canvas_ratio);
	}
	else {
		this.canvas_w = Math.round(canvas_h_max / this.canvas_ratio);
		this.canvas_h = canvas_h_max;
	}
	
}

ZoomImage.prototype.set_image_xy = function( x0a, y0a ){
	this.x0 = parseInt(x0a); 
	this.y0 = parseInt(y0a); 
	
	//this.refresh_thumb_drag();	
	this.repaint(); 
}

ZoomImage.prototype.set_format = function( w, h){

	this.format_w = w; 
	this.format_h = h; 
	
	this.canvas_ratio = w / h; 

	if ( changeFormat > 2) {
		//this.reset(); 
		this.zoom_level = 1; // try to reset onto maximum selection
		this.x0 = 0; 
		this.y0 = 0; 
		//alert("reset" )
	//	alert( changeFormat ); 
	}
	
	//recalculate min zoom and max zoom
	this.check_limits();

	this.set_size();
	this.check_limits();
	this.set_canvas(); 
	//this.reset(); 
	this.repaint(); 
	
	
}

ZoomImage.prototype.refresh_thumb_drag = function(){
   
	this.thumb_drag_x0 = parseInt( this.x0  / this.w * this.thumb_w  ) +1
	this.thumb_drag_y0 = parseInt( this.y0  / this.h * this.thumb_h  ) +1

	//this.log('thumbdrag x: ' + this.thumb_drag_y0 + 'y: ' + this.thumb_drag_x0 );
}


ZoomImage.prototype.set_image_zoom = function(){
	//this.log('set_image_zoom'); 
	
	if ( this.orientation == 'horizontal') {
		this.image_zoom =  canvas_w_max / this.w_orig ;
	} else {
		this.image_zoom =  canvas_h_max / this.h_orig ;
	}

}

ZoomImage.prototype.set_thumb_zoom = function(){
	if ( this.w_orig > this.h_orig ) {
		this.thumb_zoom = thumb_w_max / this.w_orig; 
	} else {
		this.thumb_zoom = thumb_h_max / this.h_orig; 
	}

}

ZoomImage.prototype.show_debug_msg = function( msg_str ){
	if (zoom_image_debug == false) {
   	return false;
   }
	
	this.debug_msg.style.display="block";
	this.debug_msg.value = msg_str; 
}

ZoomImage.prototype.log = function ( str ){
	if (zoom_image_debug == false) {
   	return false;
   }

	this.debug_log.style.display="block";
	this.debug_log.value += " | "+ str; 
}

ZoomImage.prototype.repaint = function(  ){
	this.log('repaint');
	
	
	//this.set_size(); 
	//this.set_canvas(); 
	//this.check_limits(); // moves image back to viewport if it should be outside
		
	
	this.image.style.width 			= this.w + "px";
	this.image.style.height 		= this.h + "px";
	this.image.style.left 			= - this.x0 + "px"; // negative moving image up
	this.image.style.top 			= - this.y0 + "px";

	this.thumb.style.width 			= this.thumb_w + "px";
	this.thumb.style.height 		= this.thumb_h + "px";
	
	this.refresh_thumb_drag(); 
	
	if ( parseInt(this.thumb_drag_y0) < 1 ){
		this.thumb_drag_y0 = 1; 
		this.refresh_thumb_drag(); 
	}
	if ( parseInt(this.thumb_drag_x0) < 1 ){
		this.thumb_drag_x0 = 1; 
		this.refresh_thumb_drag(); 
	}
	
	
	
	
	this.thumb_drag.style.width 	= parseInt(this.thumb_drag_w ) + "px";
	this.thumb_drag.style.height 	= parseInt(this.thumb_drag_h  ) + "px";
	this.thumb_drag.style.left 	= parseInt(this.thumb_drag_x0 -1 ) + "px";
	this.thumb_drag.style.top 		= parseInt(this.thumb_drag_y0 -1 ) + "px";

	// if changed ??
	this.table_vorschau.style.width 		= this.canvas_w + "px";
	this.table_vorschau.style.height 	= this.canvas_h + "px";
	this.vorschau.style.width 				= this.canvas_w + "px";
	this.vorschau.style.height 			= this.canvas_h + "px";
	this.canvas.style.width  				= ( this.canvas_w -20) + "px";
	this.canvas.style.height 				= ( this.canvas_h -20) + "px";
	

	//
	this.show_debug_msg( JSON.encode( this ).replace(/\,/g ," ,") ); 
	

}


// only move for drag and drop
ZoomImage.prototype.repaint_fast = function(  ){

	//this.image.style.width 			= this.w + "px";
	//this.image.style.height 		= this.h + "px";
	this.image.style.left 			= - this.x0 + "px"; // negative moving image up
	this.image.style.top 			= - this.y0 + "px";
	
	//
	this.show_debug_msg( JSON.encode( this ).replace(/\,/g ," ,") ); 
	//this.check_limits();
}

ZoomImage.prototype.showdebug = function(){
	this.show_debug_msg(JSON.encode(this).replace(/\,/g, " ,"));
}

ZoomImage.prototype.check_limits = function(){
	//return; 
	if (this.stop > 1) {
   	this.log('loop');
		return
   }
	
	this.log('check_limits'); 
	changed = 0; 
	
	limit_x = (this.w) - this.canvas_w;
	limit_y = (this.h) - this.canvas_h;

	if ( this.y0 >  limit_y ) {
		this.y0 				 =    limit_y; 
		changed = 1; 
	}

	if ( this.x0 > limit_x ) {
		this.x0 				 =   limit_x; 
		changed = 1; 	
	}
	
	// to much left // zu weit nach links geschoben
	if ( this.x0 < 0 ) {
		this.x0 = 0; 
		changed = 1; 
	}
	
	// to much top // zu weit nach oben geschoben
	if ( this.y0 < 0 ) {
		this.y0 = 0; 
		changed = 1; 
	}
	changed = this.check_zoom_limit(); 
	
	
	this.debug_limit =  "(x: "+ limit_x +" y: " + limit_y; 
	//this.show_debug_msg(); 
	
	if ( changed == 1){
			
		this.log('check->repaint'); 
		//this.set_size(); 
		//this.set_canvas(); 
		this.stop = 1; 
		
		this.repaint(); 	
	} else {
		this.log('limit=good');
	}
}

ZoomImage.prototype.check_zoom_limit = function ( changed ) {
	this.log('check_zoom_limit'); 
	if (this.stop > 1) {
  // 	return false;
   }
	
	fmtW = mm2pixel( this.format_w );
	fmtH = mm2pixel( this.format_h );
	//scale =  this.w_orig / fmtH ;  // ratio when orig is scaled into format, needed to check if height is big enough at this ratio

	//alert( this.format_w)

	ratio_image = this.w_orig / this.h_orig; 
	ratio_fmt   = (this.orientation=='horizontal') 
					? this.format_w / this.format_h
					: this.format_h / this.format_w	; 
	
	//alert( "i: "+ ratio_image + " f: "+ ratio_fmt + " o: "+ this.orientation ); 
	
	this.zoom_level_min = 1; 

   if ( this.zoom_level_min == 1 && ratio_image >= ratio_fmt   && this.orientation== "horizontal"  ) {
		this.zoom_level_min = ratio_image / ratio_fmt ; 
		//alert( " 1934 h: " + this.zoom_level_min )
	}
   if ( this.zoom_level_min == 1 &&  ratio_image <= ratio_fmt   && this.orientation== "vertical"  ) {
		this.zoom_level_min = ratio_fmt / ratio_image ; 
		//alert( " 1938 w: " +this.zoom_level_min )
	}
	if ( this.zoom_level_min == 1 && ratio_image >= ratio_fmt   && this.orientation== "vertical"  ) {
		this.zoom_level_min = 1 ; // ratio_image / ratio_fmt ; 
		//alert( " 1942 h: " + this.zoom_level_min )
		this.set_canvas();
	}
   if ( this.zoom_level_min == 1 &&  ratio_image <= ratio_fmt   && this.orientation== "horizontal"  ) {
		this.zoom_level_min =  1; // ratio_fmt / ratio_image ; 
		//alert( "	1947 w:  " +this.zoom_level_min )
		this.set_canvas(); 
	}
	
	//alert( "size: w:" + this.w_orig +" fw:"+  fmtW +" h:" +this.h_orig +" fh:" + fmtH +" rf:" + ratio_fmt + " ri:"+ ratio_image ); 
	
	// calc zoom max ( depends on chosen format and uploaded picture pixel-ammount ) 	
	if ( this.orientation == "horizontal") {
		if ( ratio_image > ratio_fmt ) {
			this.zoom_level_max = this.w_orig / fmtW; 	
			this.log('hor , img > fmt')
		} else {
			//this.zoom_level_max = this.h_orig / fmtH; 	
			this.zoom_level_max = this.w_orig / fmtW; 	
			this.log('hor , img < fmt')
		}
	} else /* vertical */ {
		if ( ratio_image < ratio_fmt ) {
			this.zoom_level_max = this.w_orig / fmtH; 	
			this.log('ver , img < fmt')
		} else {
			this.zoom_level_max = this.h_orig / fmtW; 	
			this.log('ver , img > fmt')
		}
	}
	this.log( this.zoom_level_max) ; 
	//alert ( "i: "+ ratio_image + " f:"+ratio_fmt ); 
	
	
	// init
	// w = 350 , h = 350
	// wo = 3500 , ho = 3500
	// zoom = 10
	
	
	// calc zoom max
	//this.zoom_level_max = Math.max( this.canvas_w / this.w , this.canvas_h / this.h );  
		
	if ( this.zoom_level_max < this.zoom_level_min ) {
		//alert('unmoeglich: min:'+ this.zoom_level_min + " max: " + this.zoom_level_max ); 
		this.reset();
	}
		
	if ( this.zoom_level > this.zoom_level_max ) {
		//alert('over max'); 
		this.zoom_level = this.zoom_level_max; 
		changed = 1;
	}
	
	if ( this.zoom_level < this.zoom_level_min ) {
		//alert('under min'); 
		this.zoom_level = this.zoom_level_min; 
		changed = 1; 
	}
	
	/*
	this.stop++; 
	
	if ( this.w_init * this.zoom_level < this.canvas_w  || this.h_init * this.zoom_level < this.canvas_h ){
		this.stop ++; 
		
		this.log( "new: " + this.zoom_level) 
		//this.set_size(); // recalc this.w and this.h
		changed = 1; 
	}
	*/ 
	
	if ( changed ) {
		 this.stop ++; 
		 
		// this.set_size(); 
	}
	
	return changed; 
}

ZoomImage.prototype.repeat = function( state ){
	this.repeat_state = state; 
	//alert( this.repeat_state ); 
	//this.repaint();
}

ZoomImage.prototype.rotate = function(){
	this.log('rotate' + this.rotate_state); 

	// only allow to rotate if resolution is high enough 
	// for this orientation otherwise return false
	if (this.orientation == 'horizontal') {
		// try to rotate into vertical
		// if new orientation does not fit return false
		new_fmtW = mm2pixel( this.format_h  ); // flip w and h !!
		new_fmtH = mm2pixel( this.format_w  ); 
		
   } else {
		// try to rotate into horzontal
		// if new orientation does not fit return false
		new_fmtW = mm2pixel( this.format_w  ); // flip w and h !!
		new_fmtH = mm2pixel( this.format_h  ); 
	}
	
	if( new_fmtW > this.w_orig  ||  new_fmtH > this.h_orig) {
		str = 'Drehen ist nicht möglich, da die Auflösung dann zu gering ist!'; 
		str +='\n\n Format: '+ pixel2mm( new_fmtW / 10 ) + " x "+ pixel2mm(new_fmtH/10)  + " cm "; 
		str +=", Bild: " + pixel2mm( this.w_orig/10) + " x " + pixel2mm(this.h_orig/10) + " cm"; 
		
		alert( utf8_decode( str)  )	; 
		
		return false; 
	}

	
	this.rotate_state = 1 - this.rotate_state; 

	this.x0 = 0; 
	this.y0 = 0; 

	
	if (this.orientation == 'horizontal') {
   	this.orientation = 'vertical';
   } else {
		this.orientation = 'horizontal';
	}

	
	
	// first !! 
	this.set_canvas(); //  /* force: */ true ); 
	this.zoom_level = 1; 
	//alert( this.orientation); 
	this.check_limits();
	this.set_size(); 
; 
	this.repaint(); 

}

ZoomImage.prototype.reset = function() {
	this.stop ++; 
		  this.orientation = ( this.w > this.h ) ? 'horizontal' : 'vertical' ;
	
	this.flip_v_state = 0; 
	this.flip_h_state = 0; 
	this.flip('auto'); 
			
	this.x0 = 0; 
	this.y0 = 0; 
	
	this.zoom_level = 1; 
	this.check_limits(); 
	this.set_size(); 
	this.set_canvas( ); 
	this.repaint(); 
}

ZoomImage.prototype.flip = function( dd ){
	this.log('flip' + dd); 
	
	switch( dd ){
		case 'v': 
			flip = 'v'; 
			this.flip_v_state = 1 - this.flip_v_state; 
		break;
		
		case 'h': 
			flip = 'h'; 
			this.flip_h_state = 1 - this.flip_h_state; 
		break;
		
		case 'o':
			flip = 'o'; 
			this.flip_v_state = 0;
			this.flip_h_state = 0;
		break; 

		// only reload
		default: // orig
		case 'auto': 	
			flip = ''; 
		break; 
	}

	
	flip_vh = "v" + this.flip_v_state + "h" + this.flip_h_state; 			
	try {
		if ( flip_vh == zoom_image.flip_vh ) {
			  return false; 
		} } catch (e) {}

	zoom_image.flip_vh = flip_vh; 

	my_random = Math.floor(Math.random()*100000000); 
		
//		alert( JSON.encode( this)) ; 	
	currentImageName = this.path; 
			
	currentImageName = currentImageName.replace(/^images\//,"")	; // remove "images/" from path
	currentImageName = currentImageName.replace(/\.[a-zA-Z]*$/,"")	; // remove ".jpg/" from path
	
	
   	var r = new Request({
   		url: "flipimage.php",
   		method: 'get',
   		evalScripts: false,
   		data: "flip=o&flip_vh="+ flip_vh +"&file=" + currentImageName + "&type=" + imageExtension +"&random=" + my_random
   	});
   	r.addEvent('success', function(response, xml){
			//alert( 'success' + "flip=o&flip_vh="+ flip_vh +"&file=" + currentImageName + "&type=" + imageExtension +"&random=" + my_random); 
   		zoom_image.image.src = "images/" + currentImageName + imageExtension + "?" + my_random;
   		zoom_image.thumb.src = "images/" + currentImageName + imageExtension + "?" + my_random;
   		
   		//zoom_image.x0=0; 
			//zoom_image.y0=0; 
			zoom_image.set_size();
			zoom_image.set_canvas();
			
			zoom_image.repaint(); // refresh look
		});
		r.send();
		
	
	zoom_image.stop++;
	
}

ZoomImage.prototype.move = function( dx, dy ){
	//	this.log('move');


	this.set_image_xy( this.x0 + dx * this.move_speed  , this.y0 + dy * this.move_speed );
	this.stop=0; 
	//this.set_size(); 
	this.check_limits();
	
	this.repaint(); 
	
	if ( this.repeat_state == 1) {
		setTimeout( "zoom_image.move("+dx+","+dy+");", this.repeat_delay  ); 
	}
}

ZoomImage.prototype.move_thumb_drag = function( el , x2, y2  ){
	//	this.log('drag move');

	x2 = el.getPosition('thumbnail').x-1;
	y2 = el.getPosition('thumbnail').y-1;
	
	drag_x = parseInt(  this.thumb_drag.style.left ); 
	drag_y = parseInt(  this.thumb_drag.style.top  );
	
	//this.log(' DRAG x: '+drag_x +" : y"+ drag_y); 
	zoom_1 = ( this.canvas_w  ) / parseInt( this.thumb_drag.style.width ); 
	
	//this.log( 'z: ' + zoom_1 )
	this.x0 =  parseInt( ( drag_x  ) * zoom_1 ); 
	this.y0 =  parseInt( ( drag_y  ) * zoom_1 ); 
	
	//	this.show_debug_msg( JSON.encode( this ).replace(/\,/g ," ,") ); 
	//this.set_size();
	this.check_limits();
	this.repaint_fast(); 
	
}


ZoomImage.prototype.zoom = function ( dz ){
//	this.log('zoom'); 
	
	this.old_zoom = this.zoom_level; 
	
	this.zoom_level += dz * this.zoom_speed ; 
	
	this.stop=0; 
	this.check_limits();
	this.set_size(); 
	this.check_limits(); // 2x is ok ! needed for boundaries checking
	
	
	// only repaint when actually moved
	if (this.old_zoom != this.zoom_level) {
   	this.repaint(); // refresh look
	}
	
}


function zoom_image_init( data , upload_state ) {
   //zoom_image = new ZoomImage(1600, 1200, "tmp", "tmp", 0, 0, 1.0, 350, 350); // init with dummy -values
	
	data2 = data ; 
	if ( typeof( data2.x0 ) == 'undefined' ){
		data2 				= {} ; // init json-obj.
		data2.x0 			= 0;
		data2.y0 			= 0; 
		data2.image 		= data.image; 
		data2.name  		= data.name; 
		data2.extension 	= data.extension; 
		data2.w 				= data.width; 		
		data2.h				= data.height;
		data2.w_orig		= data.orgwidth;
		data2.h_orig		= data.orgheight;
		
	}
	
	if (upload_state != 0) {
   	if (data.w_orig >= data.h_orig) {
	  	data2.rotated = 0;
	  } else {
	  	data2.rotated = 1; // hochformat preset
	  }
   }

	
	//alert( JSON.encode( data2 )); 
	
	zoom_image = new ZoomImage(data2);
	zoom_image.init( data2 );
}

function zoom_image_move( dx, dy ) {
	zoom_image.move( dy, dy);
}



