uploadDlgHTML = "";
dreh = 0;
function getE(str) {
	var o = document.getElementById(str);
	return  o ? o : null;
}

function strpos( haystack, needle, offset){
    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

function getPosition(obj) {
  var pos = { left:0, top:0 };

  do {
    pos.left += obj.offsetLeft;
    pos.top += obj.offsetTop;
  } while (obj = obj.offsetParent);

  return pos;
}

function getSize() {
	var size = new Object();
	size.width  = window.innerWidth  ? window.innerWidth  : document.body.offsetWidth;
	size.height = window.innerHeight ? window.innerHeight : document.body.offsetHeight;

	return size;
}

function disableField(field) {
	field.disabled = "disabled";
	field.disabled = "disabled";
	field.className = "textDisabled";
}

function enableField(field) {
	field.disabled = "";
	field.disabled = "";
	field.className = "text";
}

function enableApplication() {
	/*
	var fType1 = document.getElementsByName("formatType")[0];
	var fType2 = document.getElementsByName("formatType")[1];
	fType1.disabled = false;
	fType2.disabled = false;
	fType1.checked = true;
	sizeFormat = "auto";
	
	enableField($("auto_breite"));
	enableField($("auto_hoehe"));
	disableField($("individuell_breite"));
	disableField($("individuell_hoehe"));
	*/
	maxZoomSize = 10;
	if( slider )
		slider.set(0);
		
	initMoveDragger();
}

function resetApplication() {
	enableApplication();
}

function hideSlider() {
}

function showSlider() {
}

function goBack() {
	document.location = "index.php?back=1";
}

function calcImageSize() {
  var size = new Object();
	size.width  = Math.round( (orgImgWidth  / 96) * 25.4 ); // calc in cm
	size.height = Math.round( (orgImgHeight / 96) * 25.4 ); // calc in cm

	return size;
}

function calcNewImageSize(w, h) {
  var size = new Object();
	size.width  = Math.round( (w  / 96) * 25.4 ); // calc in cm
	size.height = Math.round( (h / 96) * 25.4 ); // calc in cm

	return size;
}

function mm2pixel(mm) {
	return Math.round((mm * 96) / 25.4);
}

function pixel2mm(pixel) {
	return Math.round((pixel / 96) * 25.4);
}


//////////////// FORMATS in checkboxes

function setFormatText(fmt) {
	if ( fmt ) {
		txt_array = fmt.split("x");
		
		// calc new image size
		var widthMM = $("max_hoehe").value;
		var heightMM = $("max_hoehe").value;
		var ratio = widthMM / heightMM;
		
		newWidthMM  = parseInt(txt_array[0]) * 10;
		newHeightMM = parseInt(txt_array[1]) * 10;
		
		var faktor = widthMM / newWidthMM;

		var pixW = Math.round((faktor * 350)-350 / imgWidth); // val is MM !!!
		var pixH = Math.round(pixW * ratio);
		
		if (slider) {
			slider.steps = pixW;
			maxSliderValue = pixW;
			slider.set(0);
		}
		
		updateMoveDragger();

		calcImageSize();
		
		lastAutoWidth = newWidthMM;
		lastAutoHeight = newHeightMM;
		
		var txt = txt_array[0] + " x " + txt_array[1] + " cm";
		
leftPosition = 0;
topPosition = 0;
		
		return txt;
	}
	return null;
}

function disableExtra() {
	var e = document.getElementsByName("formatChooserExtra");
	for(i = 0; i < e.length; i++) {
		e[i].checked = false;
	}
	$("formatSwitcher").checked = false;
	
	var selectedFormat = getFormatValue("formatChooserDefault");
	
	$("formatText").innerHTML = setFormatText(selectedFormat);
}

function disableDefault() {
	var e = document.getElementsByName("formatChooserDefault");
	for(i = 0; i < e.length; i++) {
		e[i].checked = false;
	}
	$("formatSwitcher").checked = true;
	
	var selectedFormat = getFormatValue("formatChooserExtra");
	
	$("formatText").innerHTML = setFormatText(selectedFormat);
}

function getFormatValue(fields) {
	var e = document.getElementsByName(fields);
	val = "";
	
	for(i = 0; i < e.length; i++) {
		if( e[i].checked ) {
			val = e[i].value;
		}
	}
	
	return val;
}

function disableFormats() {
	var e = document.getElementsByName("formatChooserDefault");
	for(i = 0; i < e.length; i++) {
		e[i].checked = false;
		e[i].disabled = "disabled";
	}
	
	var e = document.getElementsByName("formatChooserExtra");
	for(i = 0; i < e.length; i++) {
		e[i].checked = false;
		e[i].disabled = "disabled";
	}
	
	$("formatSwitcher").checked = false;
	$("formatSwitcher").disabled = "disabled";
}

function enableFormats() {
	var e = document.getElementsByName("formatChooserDefault");
	for(i = 0; i < e.length; i++) {
		e[i].checked = false;
		e[i].disabled = null;
	}
	
	var e = document.getElementsByName("formatChooserExtra");
	for(i = 0; i < e.length; i++) {
		e[i].checked = false;
		e[i].disabled = null;
	}
	
	$("formatSwitcher").checked = false;
	$("formatSwitcher").disabled = null;
	
	updateSizeFormats()

}

function showFormats() {
	disableDefault();
	
	if (currentImage) {
	
		var navi = $("navi");
		var pos = navi.getPosition();
		
		var x = pos.x;
		var y = pos.y;
		
		// show layerwindow ?
		var layer = document.getElementById("formatWindow");
		
		if (layer.style.display == "none") {
			layer.style.position = "absolute";
			layer.style.zIndex = 9999;
			layer.style.left = "168px"; //(x + 30) + "px";
			layer.style.top = (y + 30) + "px";
			layer.style.display = "";
		}
		
		// handle clicks and close window
		layer.onclick = function(){
			layer.style.display = "none";
			var e = document.getElementsByName("formatChooserExtra");
			checkthis = null;
			for (i = 0; i < e.length; i++) {
				if (e[i].checked) {
					checkthis = true;
					disableDefault();
					break;
				}
			}
			
			if (checkthis) {
		 		$("formatSwitcher").checked = true;
		 	}
		}
	}
	else {
		alert('Kein Bild geladen.'); 
	}
}

var hasExtraFormat = false; 
var availableFormats =""; 
var availableFormats_max = ""; 

function updateSizeFormats() {
	availableFormats =""; 
	
	//w = Math.round(parseInt(lastAutoWidth ) / 10);
	//h = Math.round(parseInt(lastAutoHeight) / 10);
	
	w = orgImgWidth;
	h = orgImgHeight;
	
	zoom_str = ""; 	
	var e = document.getElementsByName("formatChooserDefault");
	for(i = 0; i < e.length; i++) {
		v = e[i].value.split("x");
		
		fmtW = mm2pixel(v[0]*10);
		fmtH = mm2pixel(v[1]*10);
		
		//zoom = Math.max( fmtH / h , fmtW / w); 
		//zoom_str +=" , " + zoom; 
		
		// disable format, when it is to small resolution to fit into the format
		// test if image is bigger than format "vert" + test "horiz"	
		
	w_orig = w; 
	h_orig = h; 
	
	orientation = ( w_orig > h_orig ) ? "horizontal" : "vertical" ; // optimistic guess that it will be enough when image is rotated correctly, rotate will be disabled later 
	
	ratio_image = w_orig / h_orig; 
	ratio_fmt   = ( orientation == "horizontal" )
					? fmtW / fmtH
					: fmtH / fmtW	; 
	//alert( "i: "+ ratio_image + " f: "+ ratio_fmt )
	
	zoom_level_min = 1; 
   if ( zoom_level_min == 1 && ratio_image > ratio_fmt   && orientation=="horizontal" ) {
		zoom_level_min = ratio_image / ratio_fmt ; 
	}
   if ( zoom_level_min == 1 &&  ratio_image < ratio_fmt && orientation=="vertical"  ) {
		zoom_level_min = ratio_fmt / ratio_image ; 
	}
			// calc zoom max ( depends on chosen format and uploaded picture pixel-ammount ) 	
	if ( orientation == "horizontal") {
		if ( ratio_image > ratio_fmt ) {
			zoom_level_max = w_orig / fmtW; 	
		} else {
			zoom_level_max = h_orig / fmtH; 	
		}
	} else /* vertical */ {
		if ( ratio_image < ratio_fmt ) {
			zoom_level_max = w_orig / fmtH; 	
		} else {
			zoom_level_max = h_orig / fmtW; 	
		}
	}


		if( ( /* horizontal */ ( w > fmtW && h > fmtH ) || /* vertical */ ( h > fmtW && w > fmtH ) ) && zoom_level_max > zoom_level_min ) {
			e[i].disabled = "";
			e[i].parentNode.parentNode.style.color="";	
			availableFormats +=", "  +v[0] +"x"+ v[1] +"cm" ; // +fmtW + ":"+ fmtH +" "+ (fmtW*fmtH/1000000) +"mp ";
		}
		else {
			e[i].disabled = "disabled";
			e[i].parentNode.parentNode.style.color="silver";	
		
		}	
		
	}
	
	hasExtraFormat = false; 
	
	var e = document.getElementsByName("formatChooserExtra");
	for(i = 0; i < e.length; i++) {
		v = e[i].value.split("x");
		
		
		fmtW = mm2pixel(v[0]*10);
		fmtH = mm2pixel(v[1]*10);
		
		
		// disable format, when it is to small resolution to fit into the format
		// test if image is bigger than format "vert" + test "horiz"	
	
		w_orig = w; 
	h_orig = h; 
	
	orientation = ( w_orig > h_orig ) ? "horizontal" : "vertical" ; // optimistic guess that it will be enough when image is rotated correctly, rotate will be disabled later 
	
	ratio_image = w_orig / h_orig; 
	ratio_fmt   = ( orientation == "horizontal" )
					? fmtW / fmtH
					: fmtH / fmtW	; 
	//alert( "i: "+ ratio_image + " f: "+ ratio_fmt )
	
	zoom_level_min = 1; 
   if ( zoom_level_min == 1 && ratio_image > ratio_fmt  && orientation=="horizontal" ) {
		zoom_level_min = ratio_image / ratio_fmt ; 
	}
   if ( zoom_level_min == 1 &&  ratio_image < ratio_fmt  && orientation=="vertical" ) {
		zoom_level_min = ratio_fmt / ratio_image ; 
	}
			// calc zoom max ( depends on chosen format and uploaded picture pixel-ammount ) 	
	if ( orientation == "horizontal") {
		if ( ratio_image > ratio_fmt ) {
			zoom_level_max = w_orig / fmtW; 	
		} else {
			zoom_level_max = h_orig / fmtH; 	
		}
	} else /* vertical */ {
		if ( ratio_image < ratio_fmt ) {
			zoom_level_max = w_orig / fmtH; 	
		} else {
			zoom_level_max = h_orig / fmtW; 	
		}
	}


		if( ( /* horizontal */ ( w > fmtW && h > fmtH ) || /* vertical */ ( h > fmtW && w > fmtH ) ) && zoom_level_max > zoom_level_min ) {
			e[i].disabled = "";
			e[i].parentNode.parentNode.style.color="";	
			hasExtraFormat = true; 
			availableFormats +=", " + v[0] +"x"+ v[1] +"cm";
		}
		else {
			e[i].disabled = "disabled";
			e[i].parentNode.parentNode.style.color="silver";	
		}
	}

	availableFormats_max ="\n\n Maximales Format bei dieser Aufl&ouml;sung des Bildes ist: "+ Math.round( pixel2mm( w )/10 ,2)  + "cm x " + Math.round( pixel2mm( h ) /10 , 2)  +"cm " ; 
	
	leftPosition = 0;
	topPosition = 0;

	//alert( zoom_str); 
	
	if ( hasExtraFormat == false ){
		// hide "anderes Format"
		document.getElementById('extraFormatsButton').style.display="none";
	} else {
		document.getElementById('extraFormatsButton').style.display="";
	}
	
	
}
function paymentShowDetailForm() {
	var e = document.getElementsByName("zahlung");
	payelement = null;
	for(i = 0; i < e.length; i++) {
		if( e[i].checked ) {
			payelement = e[i];
			break;
		}
	}
	
	tpl = null;
	
	if( payelement ) {
		switch( payelement.value ) {
			case "bank": 	tpl = "bankeinzug.tpl"; break;
			case "card": 	tpl = "creditcard.tpl"; break;
			case "paypal": tpl = "paypal.tpl"; break;
		}
		
		if( tpl ) {
			new Request({
				method: "post",
				url: "templates/"+tpl,
				onComplete: function(responseHTML) {
					$("paymentDetails").innerHTML = responseHTML;
				}
			}).post("templates/"+tpl);
		}
	}
}

function loadPaymentMethods() {
	new Request({
				method: "post",
				url: "templates/payment.tpl",
				onComplete: function(responseHTML) {
					$("paymentDetails").innerHTML = responseHTML;
				}
	}).post("templates/payment.tpl");
}

function initPaypal() {
	window.open("paypal.php", "ppal", "left=50, top=50, width=800,height=800,menubar=no, scrollbars=1, toolbar=no");
}

function switchImages() {
	$("aufteilung").style.backgroundImage = "url(media/images/bildgroesse.gif)";
	$("groesse").style.backgroundImage = "url(media/images/bild_aufbau.gif)";
}

function loadSizeBack() {
	/*
	var fmt = (lastAutoWidth / 10)+"x"+(lastAutoHeight/10);
	
	var extra = $("navi").getElementsByTagName("input");
	for(i = 0; i < extra.length; i++) {
		if( extra[i].value == fmt ) {
			extra[i].checked = "checked";
		}
	}
	*/
}

function removeImage(id, price) {
	if( confirm("Diesen Artikel wirklich entfernen ?")) {
		var tb = $("myCart").getElementsByTagName("tbody")[0];
		
		var tr1 = document.getElementById("cart1Row"+id);
		var tr2 = document.getElementById("cart2Row"+id);
		var tr3 = document.getElementById("cart3Row"+id);

		if (tb) {
			tb.removeChild(tr1);
			tb.removeChild(tr2);
			tb.removeChild(tr3);
		}
		else {
			$("myCart").removeChild(tr1);
			$("myCart").removeChild(tr2);
			$("myCart").removeChild(tr3);
		}
			
		var gp = $("gesamtPrice");
		var vp = $("versandPrice");
		var wk = $("warenkorbView");
		
		var r = new Request.JSON({
			url: "cartdrop.php",
			method: 'post',
			data: { image: id },
			onComplete: function(responseHTML) {
				if( responseHTML ) {
					gp.innerHTML = responseHTML.price + " &euro;";
					vp.innerHTML = responseHTML.versand + " &euro;";
					wk.innerHTML = responseHTML.articles;
				}
			}
		}).post("cartdrop.php");
	}
}

function showUpload() {
	var div = $("uploadLayer");
	div.style.position = "absolute";
	div.style.left = "30px";
	div.style.top = "80px";
	div.style.zIndex = "12000";
	
	div.style.display = "";
}

function hideUpload() {
	var div = $("uploadLayer");
	div.style.display = "none";
	
	// sicherstellen, dass der dialog schon mal benutzt wurde,
	// sonst uploadDlgHTML LEER und man hat kein Formular mehr *lol* !!!!
	if (uploadDlgHTML != "") {
		$("uF").innerHTML = uploadDlgHTML;
	}
}
function hideDreh() {
	var div = $("drehLayer");
	div.style.display = "none";
	
	// sicherstellen, dass der dialog schon mal benutzt wurde,
	// sonst uploadDlgHTML LEER und man hat kein Formular mehr *lol* !!!!
	if (uploadDlgHTML != "") {
		$("uF").innerHTML = uploadDlgHTML;
	}
}

function drehfile(sid) {
	dreh = 1;
	var div = $("drehLayer");
	div.style.position = "absolute";
	div.style.left = "30px";
	div.style.top = "80px";
	div.style.zIndex = "12000";
	
	div.style.display = "";

	$("dF").innerHTML = '<p style="width: 250px;font-size: 12px;text-align: center;">Bitte warten Sie, bis Ihr Bild gedreht ist.<br /><img src="/media/images/ajax-loading.gif" /></p>';

	$('iFrame2').src = "dreh.php";
}


function doUpload() {
	if ($("FileData").value != "" ) {
		$("uF").submit();
		uploadDlgHTML = $("uF").innerHTML;
		$("uF").innerHTML = '<p style="width: 250px;font-size: 12px;text-align: center;">Bitte warten Sie, bis Ihr Bild hochgeladen ist.<br /><img src="/media/images/ajax-loading.gif" /></p>';
	}
	else {
		alert("Ein Fehler ist aufgetreten:\n\nEs wurde keine Datei ausgewaehlt.");
	}
}

function msgClose() {
	var msgBox = $("messageBox");
	msgBox.style.display = "none";
}

function showMessage(title, content) {
	var msg = "<h3>"+title+"</h3><br />";
	msg += "<div>"+content+"</div>";
	msg += '<input type="button" value="OK" onclick="msgClose();" class="button" />';
	
	var msgBox = $("messageBox");
	msgBox.innerHTML = msg;
	msgBox.style.display = "";
	
	var winSize = window.getSize();
	var left = (winSize.width / 2) - parseInt((msgBox.getSize().x) / 2);
	msgBox.setStyles({
		position: "absolute",
		left: left,
		top: 200,
		zIndex: 10000,
		display: ""
	});
}

function setNumArticles(field, artikel_id, i) {
	var value = parseInt(field.value);
	if ( value > 0 ) {
	
		var aid = artikel_id;
		
		var gp = $("gesamtPrice");
		var vp = $("versandPrice");
		var ek = $("artpreissumme_" + i);
		
		if( value >= 1 && $("zusatz_"+i).checked ) {
			zusatz = $("zusatz_"+i).value;
			zusatz = parseFloat(value) * parseFloat(zusatz);
			$("zusatzview_"+i).innerHTML = zusatz.toFixed(2);
		}
		
		var r = new Request.JSON({
			url: "setcart.php",
			method: 'post',
			data: {
				func: 'set_articleNum',
				cart_id: aid,
				value: value
			},
			onComplete: function(responseHTML){
				if (responseHTML) {
					gp.innerHTML = responseHTML.price + " &euro;";
					vp.innerHTML = responseHTML.versand + " &euro;";
					ek.innerHTML = responseHTML.ekgesamt;
				}
			}
		}).post("setcart.php");
	}
	else {
		field.value = 1;
		showMessage("Ein Fehler ist aufgetreten", "Sie m&uuml;ssen mindestens 1 Keilrahmen bestellen,<br />oder Ihre Bestellung entfernen.");
	}
}

function setKeilrahmen(field, artikel_id) {
	var value = field.checked;
	var aid = artikel_id;
	
	var gp = $("gesamtPrice");
	var vp = $("versandPrice");
	var zv_id = field.id;
	zv_id = zv_id.split("_");
	zv_id = zv_id[1];
	
	value = value ? 1 : 0;
	
	if( value == 1 ) {
		zusatz = $(field).value;
		stk = $("stueckzahl_"+zv_id);
		zusatz = parseFloat(stk.value) * parseFloat(zusatz);
		$("zusatzview_"+zv_id).innerHTML = zusatz.toFixed(2);
	}
	else
		$("zusatzview_"+zv_id).innerHTML = "0.00"
	
	var r = new Request.JSON({
		url: "setcart.php",
		method: 'post',
		data: {func: 'set_keilrahmen', cart_id: aid, value: value },
		onComplete: function(responseHTML) {
			if( responseHTML ) {
				gp.innerHTML = responseHTML.price + " &euro;";
				vp.innerHTML = responseHTML.versand + " &euro;";
				/*
				if( value == 1 )
					$("zusatzview_"+zv_id).innerHTML = field.value;
				else
					$("zusatzview_"+zv_id).innerHTML = "0.00"
				*/
			}
		}
	}).post("setcart.php");
}
