/**
 * @author abratfisch
 */
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function updateLayout() {
	$("table_vorschau").style.width  = imgWidth + "px";
	$("table_vorschau").style.height = imgHeight + "px";
}

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 onComplete(data, reset) {
		upload_state = data; 
		var r = new Request.JSON({
			url: "sgetimage.php",
			method: "post",
			data: { sid: data},
			onComplete: function(responseHTML) {
				var data = responseHTML;
				
				//alert( JSON.encode( data ) ); 
				
				imgObject = data;
				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.w; //width;
				imgHeight 	  = imgObject.h; // height;
				orgImgWidth   = imgObject.w_orig; // orgwidth;
				orgImgHeight  = imgObject.h_orig; // orgheight;

				lastAutoWidth    = imgObject.w; // breite;
				lastAutoHeight   = imgObject.h; // hoehe;
				lastManualWidth  = lastAutoWidth;
				lastManualHeight = lastAutoHeight;
				
				breitefeld = $("max_breite");
				breitefeld.value = lastAutoWidth;
				hoehefeld = $("max_hoehe");
				hoehefeld.value = lastAutoHeight;
	
				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";
				
				leftPosition = 0;
				topPosition = 0;
				currentStep = 0;
				
				switchImages();
				if( $("startDIV") )
					$("startDIV").style.display = "none";
				
				$("applicationDIV").style.display = "";

				if( data ) {
					zoom_image_init(data , upload_state);
				}	
			
				// HERE default format !!!
				
				format_type = "formatChooserDefault"; 
				format_type_found = "formatChooserDefault"; 
				format_nr = 0; 
					
					
				if (typeof(data.format_w) != "undefined" && upload_state == 1) {
					format_value = parseInt( data.format_w ) / 10  + "x" + parseInt( data.format_h ) / 10; 
//					alert( format_value ); 
					debug_str = ""; 
					
					//var hide_showformats= 1; 
					
					showFormats(); 
					//document.getElementById("formatWindow").style.display ="none" ;
					//var hide_formats = 0; 
					
					format_type 		= "formatChooserDefault"; 
					format_type_found = "formatChooserDefault"; 
					
					fields = document.getElementsByName( format_type ); 
					for ( i = 0; i< fields.length ; i++ ){
						debug_str += " : " + i; 
						
						if ( fields[i].value == format_value ) {
							format_nr = i; 
							format_type_found = format_type; 
						}
					}
					
					format_type = "formatChooserExtra"; 
					fields = document.getElementsByName( format_type ); 
					for ( i = 0; i< fields.length ; i++ ){
						debug_str += " : " + i; 
						
						if ( fields[i].value == format_value ) {
							format_nr = i; 
							format_type_found = format_type; 
						}
					}
					document.getElementsByName( format_type_found )[format_nr].click(); 
					
				} else {
					
				} 
				
				
				
				//alert( format_value + " .. "  + format_type_found  + format_nr );
				//	document.getElementById("formatWindow").style.display = "none"; 
				 document.getElementById("formatWindow").style.display ="none" ;
				
				//alert(1);
				var radio = document.getElementsByName( format_type_found )[format_nr];
				radio.checked = "checked";
				
				var changeFormat = 0; // init first load 
				
				if (format_type_found == 'formatChooserDefault') {
					disableExtra();
				}
				
				if( data ) {
					loadBack();
				}	
				
				//alert(2);
				updatePreview(document.getElementsByName( format_type_found )[format_nr]);
				
				if ( upload_state != 1) {
					//alert( "2: " +availableFormats ); 
					if (availableFormats != "") {
						if (dreh == 1) {
							//alert(utf8_decode("Ihr Bild wurde gedreht. " )); // trim first ,
							dreh == 0;
							
							var msg = "<h3>Ihr Bild wurde erfolgreich gedreht.</h3><p>Bitte w&auml;hlen Sie erneut Ihr Format.</p>";
							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: ""
							});
						}
						else
						{
							if (!reset) {
								var msg = "<h3>Ihr Bild wurde erfolgreich hochgeladen.</h3><br />";
								msg += "<div>" + availableFormats_max.replace(/^\, /, "") + "</div>";
								msg += '<input type="button" value="OK" onclick="msgClose();" class="button" />';
							}
							else {
								var msg = "<h3>Ihr Bild wurde erfolgreich zur&uuml;ckgesetzt.</h3><br />";
								msg += "<div>" + availableFormats_max.replace(/^\, /, "") + "</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: ""
							});
							
							//alert(utf8_decode("111 Ihr Bild wurde erfolgreich hochgeladen. " + availableFormats_max.replace(/^\, /, ""))); // trim first ,
						
						}
						//alert(utf8_decode("Ihr Bild wurde erfolgreich hochgeladen. Folgende Formate sind bei dieser Auflösung möglich: \n" + availableFormats.replace(/^\, /, ""))); // trim first ,
					}
					else {
						alert(utf8_decode("Die Auflösung des Bildes ist zu gering. \nBitte laden sie ein grösseres Bild hoch.\n\nMindestgrösse für 30 x 20 cm bei 96dpi sind 1134 x 756 Pixel."));
					}
				}
			
			}
		}).send(); //post("sgetimage.php")
	}

	function utf8_decode ( str_data ) {
    // Converts a UTF-8 encoded string to ISO-8859-1  
    // 
    // version: 810.1317
    // discuss at: http://phpjs.org/functions/utf8_decode

    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var tmp_arr = [], i = ac = c1 = c2 = c3 = 0;

    str_data += '';

    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}
