// carddesign-2011-2.js 
// Copyright (C) 2007-2011 Selbstdenker AG 
// <jmb@selbstdenker.ag>

var SPCM = new Object();
SPCM.loadingImage = new Image();
SPCM.loadingImage.src = "/spi/img/loading.gif";

SPCM.dummyImage = new Image();
SPCM.dummyImage.src = "/spi/img/1pxl.gif";

SPCM.evalJSON = function( str ){
	if ( !str ) return null;
	try {
		return str.evalJSON(true);
	} catch(err){
		// alert(err);
	}
	return null;
}

SPCM.random = function(){
	return Math.floor(Math.random()*100000000);
}
SPCM.ajaxUrl = function( linkId ){
	var url = $(linkId).href;
	if ( url.indexOf("rnd=") > 0 ){
		return url;
	}
	if ( url.indexOf("?") < 0 ){
		url = url + "?rnd=" + SPCM.random();
	} else {
		url = url + "&rnd=" + SPCM.random();
	}
	return url;
}
		


function stripPx(value) {
	if (value == "") return 0;
	return parseFloat(value.substring(0, value.length - 2));
}

function copyDimensions( src, dst ){
	dst.setStyle({
		width:src.style.width,
		height:src.style.height,
		left:src.style.left,
		top:src.style.top
	});
}

function extractDim( src ){
	var result = {};
	result.l = stripPx(src.style.left); 
	result.t = stripPx(src.style.top); 
	result.w = stripPx(src.style.width); 
	result.h = stripPx(src.style.height);
	return result;
}

function setDimStyle( dim, el ){
	el.setStyle({ top:dim.t+'px',left:dim.l+'px', width:dim.w+'px',height:dim.h+'px' });
}

function isMouseOverElement( ev , elementName ){		
	if ( null == ev ) return false;
	return Position.within( $(elementName),  Event.pointerX(ev), Event.pointerY(ev) );
}

function isBrowserIE(){
	return ( /MSIE/.test(navigator.userAgent) && !window.opera );
}

function isBrowserIEOrOpera(){
	return ( /MSIE/.test(navigator.userAgent) || window.opera );
}

function isBrowserIE6(){
	return ( Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined"));
}

var senderlineArray = new Array();

var Senderline = Class.create({
	initialize: function( aWarpId, aDisplayId, anEmptyId, anEditId, aFormId, anInputId ) {   
		this.lastSubmittedText = "";
		this.wrapId = aWarpId;
		this.displayId = aDisplayId;
		this.emptyId = anEmptyId;
		this.editId = anEditId;
		this.formId = aFormId;
		this.updateVisibility();
		this.inputId = anInputId;
		Event.observe($(this.wrapId), 'mouseover', function(e){ this.handleOver(); return false; }.bind(this) );
		Event.observe($(this.inputId), 'mouseout', function(e){ this.submit(); return false; }.bind(this) );
		Event.observe($(this.inputId), 'blur', function(e){ this.submit(); return false; }.bind(this) );
		senderlineArray.push(this);
	},
	updateVisibility : function (){
		if ( $(this.displayId).innerHTML.length == 0 ){
			$(this.emptyId).show();
		 	$(this.displayId).hide();
		} else {
			$(this.emptyId).hide();
		 	$(this.displayId).show();
		}
 		$(this.editId).hide();
	},
	update : function() {
		var theDiv = $(this.displayId);
		var input = $(this.inputId);
		var parsedText = input.value.replace(/\n /g, "<BR>&nbsp;").replace(/\n/g, "<BR>").replace(/  /g, "&nbsp;&nbsp;");
		theDiv.innerHTML = parsedText;
		this.updateVisibility();
	},
	submit: function() {
		this.update();
		var input = $(this.inputId);
		if ( this.lastSubmittedText == input.value ) return;
		this.lastSubmittedText = input.value;
		document.forms[this.formId].submit();
	},
	handleOver : function(){
		$(this.displayId).hide();
		$(this.emptyId).hide();
		$(this.editId).show();
		if ( ( !selectedContentbox ) || !(selectedContentbox.isInEditMode) ){
			// document.forms[this.formId].senderLineInput.focus();		
			$(this.inputId).focus();		
		}
	},
	visible : function(){
		return $(this.editId).visible();
	}
});
	

// content boxes

// static definitions
var pixelPerInch = 60.0;

var templateboxArray = new Array();

var Templatebox = Class.create({
	calcAndSetToolsOffset : function(){
		var off1 = $("lowerDiv").cumulativeOffset();
		var off2 = $("mainarea").cumulativeOffset();
		this.toolsOffsetLeft = off1.left - off2.left;
		this.toolsOffsetTop  = off1.top - off2.top;
	},
	initialize: function( displayDiv, dropDiv, maxDropCount, dropCutDiv  ){
		this.displayDiv = Element.extend(displayDiv);
		this.dropDiv = Element.extend(dropDiv);
		this.id = dropDiv.id;

		this.left = stripPx(this.dropDiv.style.left); 
		this.width = this.dropDiv.getWidth(); 
		this.right =  this.left + this.width;
		this.top = stripPx(this.dropDiv.style.top); 
		this.height = this.dropDiv.getHeight();
		this.bottom =  this.top + this.height;

		this.cutL = this.left;
		this.cutW = this.width;
		this.cutT = this.top;
		this.cutH = this.height;
		
		if ( dropCutDiv ){ 
			this.dropCutDiv = Element.extend(dropCutDiv);
			var dim = extractDim(dropCutDiv);
			var h = dim.h;
			var w = dim.w;
			var l = dim.l;
			var t = dim.t;
			this.cutL = l;
			this.cutW = w;
			this.cutT = t;
			this.cutH = h;
			h -= 2;
			w -= 2;
			l -= 1;
			t -= 1;

			this.dropCutDiv.setStyle( { width:w+'px', height:h+'px', left:l+'px', top:t+'px' });
		} else {
			this.dropCutDiv = null;
		}

		// Doppelter Schnittrand (zur Sicherheit)
		var cutOffX = (this.cutL-this.left);
		var cutOffY = (this.cutT-this.top);

		/*
		this.textL = this.cutL + 2*cutOffX;
		this.textW = this.cutW - 3*cutOffX;
		this.textR = this.textL + this.textW;
		this.textT = this.cutT + cutOffY;
		this.textH = this.cutH - 2*cutOffY;
		this.textB = this.textT + this.textH; 
		*/

		this.textL = this.cutL + 3*cutOffX;
		this.textW = this.cutW - 5*cutOffX;
		this.textR = this.textL + this.textW;
		this.textT = this.cutT + 2*cutOffY;
		this.textH = this.cutH - 4*cutOffY;
		this.textB = this.textT + this.textH; 

		this.toolsOffsetLeft = 0;
		this.toolsOffsetTop  = 0;
		this.calcAndSetToolsOffset();

		// alert( "DIV: " + this.dropDiv.getWidth() + "," + this.dropDiv.getHeight() + "; " + width + "," + height );
		this.ratio = this.width / this.height;
		this.maxContentCount = maxDropCount;
		this.contentArray = new Array();
		templateboxArray.push(this);
	},
	isStamp : function(){
		return ( this.id == "stamp");
	},
	hasMaxContentCount : function(){
		if (!this.maxContentCount) return false;
		return (this.contentArray.length >= this.maxContentCount );
	},
		
	makeDropable : function(){
		var dropImageId = (this.dropCutDiv) ? this.dropCutDiv.id : this.dropDiv.id;
		var acceptArray = new Array();
		acceptArray.push("draggable_image");
		if ( !this.isStamp() ) acceptArray.push("draggable_text");
		Droppables.add(dropImageId,{accept: acceptArray,
			hoverclass: 'dragHere',
			onDrop: function(draggableElement,  droppableElement, event ) {
				this.dropHandler( dropImageId, draggableElement, droppableElement, event);
			}.bind(this)
		});
	},
	dropHandler : function( boxId, drag, drop, event){
		if ( drop.id.indexOf("_cut") > 0 ){
			var newId = drop.id.replace("_cut", "");
			drop = $(newId);
		}
		if ( !this.isStamp()  && this.hasMaxContentCount() ){
			isRevertEffectOn = true;	
			dropWasDenied = true;
			return false;
		}
		if ( drag.id == "newTextboxDragImage" ){
			isRevertEffectOn = false;	
			this.insertNewTextbox(); 
			return false;
		}

		offset = drag.cumulativeOffset();
		dropOffset = Position.cumulativeOffset(drop);
		offset[0] = offset[0] - dropOffset[0];				
		offset[1] = offset[1] - dropOffset[1];				

		if ( this.isStamp() || (!this.hasMaxContentCount()) ){
			isRevertEffectOn = false;
			this.submitDrop(offset[0], offset[1],drag.offsetWidth,drag.offsetHeight,drag);
		} else {
			isRevertEffectOn = true;
			dropWasDenied = true;
		}
		return false;	
	},
	submitDrop:function( offX, offY, w, h, drag ){
		if ( selectedContentbox && (selectedContentbox.isInEditMode) ){
			return false;
		}
		
		var params = new Hash();
		if ( drag ){
			params.set( "draggedImage", drag.id );
		} else {
			params.set( "newHtmlBox", 1 );
		}
		params.set( "droppedBox", this.id );
		params.set( "offsetX", offX );
		params.set( "offsetY", offY );
		if (w&&h){
			params.set( "width",  w );
			params.set( "height", h );
		}
		var paramJson = params.toObject();	
/* 
		var url = $("dropImageAjax").href;
		if (drag){ 
			url += '&draggedImage=' + drag.id;
		} else {
			url += '&newHtmlBox=1';
		}
		url += '&droppedBox=' + this.id + '&offsetX=' + offX + '&offsetY=' + offY;
		if (w&&h) url+= '&width=' + w + '&height=' +h;
*/		
		var url = SPCM.ajaxUrl( "dropImageAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : paramJson,
			onSuccess: function(resp){
				var ans = resp.responseText;
				// alert(ans);
				var json = SPCM.evalJSON( ans );
				if ( json ){
					Contentbox.makeNew( json.id, json.boxId, json );
				}
		 	}.bind(this),
			onFailure: function(){ 
			}
		});		
	},
	insertNewTextbox : function( ){
		if (this.hasMaxContentCount() ){
			alert( dropWasDeniedMessage );
			return false;	
		}

		var l = this.textL;
		var t = this.textT;
		var w = this.textW;
		var h = this.textH;
		// alert("insertNewTextbox w:" + w +"; h:" + h );
	 	
	 	if ( ( w == 216 ) && ( h == 316 ) ){ // Rueckseite A5
			l += 3; t += 3;
			w -= 3; h -= 6;	
		} else if ( ( w == 204 ) && ( h == 303 ) ){ // Rueckseite A6
			l += 6; t += 3;
			w -= 6; h -= 6;	
		} else {
			l += 3; t += 3;
			w -= 6; h -= 6;
		} 
		this.submitDrop(l,t,w,h,null);
		return false;
	}
	
});

Templatebox.findWithId = function( anId ){ 
	return templateboxArray.find( function(cb){ return (anId == cb.id) });
}

Templatebox.getEditable = function(){
	return templateboxArray.find( function(cb){ return !cb.isStamp(); });
}

Templatebox.addTextbox = function(){
	var tb = Templatebox.getEditable();
	if (!tb) return;
	tb.insertNewTextbox(); 
}

var FixContentbox = Class.create({
	initialize: function( withId, templateBox, config ){
	    this.config = config || { };
		// alert("constructor Contentbox: " + withId );
		if ( withId == null ) return;
		this.id = withId;
		this.tb = templateBox;
		this.tb.contentArray.push(this);
		
		this.width = this.config.width;
		this.height = this.config.height;
		this.left = 0;
		this.top = 0;

		this.imageSrc = this.config.imageSrc;
		this.lowResSrc = this.config.lowResSrc;
	
		this.image = null;
		this.imageDiv = null; // Element.extend(imageDiv);
		this.imageGrab = null;
		this.imageGrabDiv = null; // Element.extend(imageGrabDiv);
		this.imageDel = null; // Element.extend(imageGrabDiv);
		
		this.imgPreloader = new Image();
		this.isLoaded = false;
		this.createDOM();
	},
	
	dispose : function(){	
		this.tb.contentArray = this.tb.contentArray.without(this);
		// alert("dispose: " + this.id + "; " + this.image + ";" + this.imageDiv + ";" + this.imageGrab + ";" + this.imageGrabDiv );
		if (this.imageDel) this.imageDel.remove();
		if (this.imageGrab) this.imageGrab.remove();
		if (this.imageGrabDiv) this.imageGrabDiv.remove();
		if (this.image) this.image.remove();
		if (this.imageDiv) this.imageDiv.remove();
		if (this.tb.contentArray.length == 0){
			this.tb.displayDiv.addClassName('containsNoImage');
		} 
	},
	
	remove:function(){
		this.tb.contentArray = this.tb.contentArray.without(this);
		if (this.imageDel){
			this.imageDel.remove();
			this.imageDel=null;
		}
	 	Effect.Fade(this.imageDiv, {duration:0.5, afterFinish: function() { this.dispose() }.bind(this) });

		var url = SPCM.ajaxUrl( "removeImageAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { "removedImage" : this.id, "box" : this.tb.id },
			onSuccess: function(resp){
				var ans = resp.responseText;
				// alert(ans);
		 	}.bind(this),
			onFailure: function(){ 
			}
		});	
	},

	createDOM:function(){
		var hadImage = false;
		if ( this.tb.contentArray.length > 1 ){
			var delFCB = this.tb.contentArray[0];
			delFCB.remove();
			hadImage=true;
		}
		this.tb.displayDiv.removeClassName('containsNoImage');

		var divId = 'imageX'+this.id+'Div';
		var imgId = 'image'+this.id;
		var aDiv = $(divId);
		var aImg = null;

		var marginTop = this.tb.height - this.height;

		if (aDiv){
			aImg = $(imgId);
		} else {
			aDiv = new Element( 'div',{id:divId});
			aDiv.setStyle({
				// zIndex:this.zIndex,
				position:'absolute', 
				top:'0px',left:'0px',
				width:this.tb.width+'px',height:this.tb.height+'px'
			});
		 	aImg =  new Element('img',{ 
				id:imgId,alt:"",
				width:this.width,height:this.height,
				src:this.lowResSrc,
				style:"margin-top:" + marginTop + "px"
			});
			aDiv.appendChild( aImg );
			this.tb.displayDiv.appendChild( aDiv );
			if (hadImage){
				aDiv.hide();
				new Effect.Appear( aDiv , { duration: 0.5 } );
			}
		}

		aImg.width=this.width;
		aImg.height=this.height;
		
		this.imageDiv = aDiv;
		this.image = aImg;
		// alert("NEW: th" + this.tb.height + " " + this.height + "->" + marginTop );
		aDiv = new Element('div',{ id:'imageX'+this.id+'GrabDiv','class':'imgcontainer' });
		aDiv.setStyle({
			position:'absolute',zIndex:1000,
			top:'0px',left:'0px',
			width:this.width+'px',height:this.height+'px'
		});
		aImg =  new Element('img',{ 
			id:"image"+this.id+"Grab",alt:"",
			// width:this.tb.width+"px",height:this.tb.height+"px",
			src:"/spi/img/1pxl.gif"
		});
		// needed for IE 
		aImg.width = this.tb.width;
		aImg.height = this.tb.height;

		// if ( marginTop > 0 ) aImg.setStyle( { "margin-top" : marginTop +"px" } );
		aDiv.appendChild(aImg);
		var delImg =  new Element('img',{ 
			id:"imageX"+this.id+"Del","class":"delimg",alt:FixContentbox.REMOVE_TEXT,title:FixContentbox.REMOVE_TEXT,
			src:"/spi/img/delimg.gif",
			style:"top:" + (this.tb.height-10) + "px;"
		});
		aDiv.appendChild(delImg);
		this.tb.dropDiv.appendChild(aDiv);

		this.imageGrab = aImg;
		this.imageGrabDiv = aDiv;
		this.imageDel = delImg;
		
		delImg.hide(); 

		Event.observe(this.imgPreloader, 'load', function() {
			this.image.src = this.imgPreloader.src;
			this.image.width=this.width;
			this.image.height=this.height;
			this.isLoaded = true;
			// new Effect.Highlight(this.image, { duration: 0.4 });
		}.bind(this) );
		Event.observe(this.imgPreloader, 'error', function() {
			this.isLoaded = true;
		}.bind(this) );
		this.imgPreloader.src = this.imageSrc;		
			
		Event.observe( this.imageGrabDiv, 'mouseover', function(ev){ 
			var el=this.imageDel;
			if (el) el.show(); 
		}.bind(this) );
		Event.observe( this.imageGrabDiv, 'mouseout', function(ev){ 
			var el=this.imageDel;
			if (el) el.hide(); 
		}.bind(this));
		Event.observe( this.imageDel, 'click', function(ev){ this.remove() }.bind(this));
				
		return this;
	}
});

FixContentbox.REMOVE_TEXT = "entfernen";

var contentboxArray = new Array();
// var maxContentboxCountOnPage = false;
var selectedContentbox = null;

var handleCornerArray = new Array();
var handleEdgeArray = new Array();
var handleHash = new Hash();

var toolDiv = null;
var toolFrontDiv = null;
var toolMaxsizeDiv = null;
var toolBackDiv = null;
var toolEditDiv = null;

var imageInfoDiv = null;

var dropWasDenied = false;
var dropWasDeniedMessage = "";
var isRevertEffectOn = true;

var removeContentUrl = "";
var dropContentUrl = "";

// static definitions
var PPI_WARN_RED = 100;	
var PPI_WARN_YELLOW = 180;	

var PPI_WARN_GREEN_TITLE = "Bildaufl&ouml;sung gut";
var PPI_WARN_YELLOW_TITLE = "Bildaufl&ouml;sung ausreichend";
var PPI_WARN_RED_TITLE = "Bildaufl&ouml;sung zu gering f&uuml;r Druck";
var TEXT_EDITOR_COMPATIBILITY_WARN = "Der Texteditor kann mit diesem Browser leider nicht genutzt werden. Bitte verwenden sie einen anderen Browser.";

var Contentbox = Class.create();


Object.extend(Contentbox, {
	ListenerMouseMove:null,
	ListenerMouseUp:null,
	MAXIMIZE_MAX_FACTOR:2.1, 
	minimumWidthHeight:15,	
	magneticBorderRange:5,
	MIN_OVERLAP:5,
	MIN_TEXT_WIDTH:25,	
	MIN_TEXT_HEIGHT:15,	
	fixedRatio:true,
	cropToolBorderWidth:0,
	offsetSmallSquares:0,
	cursorMoveByAmount:1,
	BASE_FONT_SIZE_DEFAULT: 12,
	BASE_FONT_SIZE_ARRAY : [ 5,6,7,8,9,10,11,12,14,16,18,20,24,28,32,36,42,50,56,60,72,80,92,100,120,140,160,180,200,220 ]
});

Contentbox.prototype = {
	initialize: function( withId, templateBox, config ){
	    this.config = config || { };
	
		// alert("constructor Contentbox: " + withId );
		if ( withId == null ) return;

		this.id = withId;
		this.resizeType = "";

		this.tb = templateBox;
		this.tb.contentArray.push(this);
		
		this.dim = { 
			w:this.config.width,
			h:this.config.height,
			l:this.config.left,
			t:this.config.top
		};
		this.zIndex = this.config.zIndex;
		if ( (!this.config.imageSrc) || (this.config.imageSrc=='') ){
			this.imageSrc = null;
			this.lowResSrc = null;
			this.origWidth = this.dim.w;
			this.origHeight = this.dim.h; 
		} else {
			this.imageSrc = this.config.imageSrc;
			if ( ( !config.lowResSrc) || ( this.config.lowResSrc=='' ) ){
				this.lowResSrc = this.imageSrc;
			} else {
				this.lowResSrc = this.config.lowResSrc;
			}
			this.maximise = ( this.config.maximise ) ? true : false;
			this.origWidth = parseInt(this.config.origWidth);
			this.origHeight = parseInt(this.config.origHeight);
		}
		this.ratio = this.origWidth / this.origHeight;

		if (this.ratio < 1 ) {
			this.minWidth = Contentbox.minimumWidthHeight;
			this.minHeight = Math.round(this.minWidth / this.ratio);
		} else {
			this.minHeight = Contentbox.minimumWidthHeight;
			this.minWidth = Math.round(this.minHeight * this.ratio);
		}
			

		// this.boxWidth = this.tb.width;
		// this.boxHeight = this.tb.height;

		this.posX = 0;
		this.posY = 0;
		
		this.eventX=0;
		this.eventY=0;

		this.moveCounter = -1;
		this.resizeCounter = -1;
	
		this.image = null;
		this.imageDiv = null; // Element.extend(imageDiv);
		// this.imageDiv = $('image' + this.id + 'Div');
		this.imageGrab = null;
		this.imageGrabDiv = null; // Element.extend(imageGrabDiv);
		
		this.isSaved = true;
		this.isInEditMode = false;
		this.lastContent = null;
		this.lastBaseFontSize = Contentbox.BASE_FONT_SIZE_DEFAULT;
		
		this.imgPreloader = new Image();
		this.loadDiv = null;
		this.isLoaded = false;
		this.isPreviewLoaded = false;
		this.isAnimating = false;
		contentboxArray.push( this );
	},
	
	dispose : function(){
		if ( this == selectedContentbox ){
			selectedContentbox.updateToolboxVisibility( false );
			unselectAllImages();			
			selectedContentbox = null;
		}
		contentboxArray = contentboxArray.without( this );
		this.tb.contentArray = this.tb.contentArray.without(this);
		// alert("dispose: " + this.id + "; " + this.image + ";" + this.imageDiv + ";" + this.imageGrab + ";" + this.imageGrabDiv );
		this.resetPreviewImageAjax();
		if (this.image) this.image.remove();
		if (this.imageDiv) this.imageDiv.remove();
		if (this.imageGrab) this.imageGrab.remove();
		if (this.imageGrabDiv) this.imageGrabDiv.remove();
		if (this.previewImageDiv){
			Effect.Fade(this.previewImageDiv, {duration:0.5, afterFinish: function() { this.previewImageDiv.remove() }.bind(this) });
		}
		if (contentboxArray.length == 0){
			this.tb.displayDiv.addClassName('containsNoImage');
		}
	},
	
	setPreviewImageSrc : function( url ){
		// console.log( "setPreviewImageSrc" + url + ", " + this.imgPreloaderSrc + ", " + this.previewImageSrc );
		if ( this.imgPreloaderSrc == url ){
			this.isPreviewLoaded = true;
			this.isPreviewOk = true;
			if ( this.previewImageSrc == url ){
				this.isPreviewLoaded = true;
				this.isPreviewOk = true;
				// this.previewImage.addClassName("success");
				return;
			}
		} else {
			this.imgPreloaderSrc = url;
			this.imgPreloader.src = url;
		}
	},

	createDOM : function( isNew ){
		// alert( "createDOM: " + this.id + ", " + isNew );
		var aDiv = $('image' + this.id + 'Div');
		var aImg = null; 
		if (aDiv){
			aImg = $("image" + this.id );
		} else {
			aDiv = new Element( 'div',{ id:'image' + this.id + 'Div' });
			aDiv.setStyle({ zIndex:this.zIndex,position:'absolute' });
			setDimStyle( this.dim, aDiv );
			if ( this.isImage() ){		
				aImg =  new Element('img',{ 
					id:"image" + this.id,
					alt:"",width:this.dim.w,height:this.dim.h,
					src:this.lowResSrc
				});
				//aImg.width=config.width;
				//aImg.height=config.height;
				aDiv.appendChild( aImg );
			} else {
				aDiv.setStyle( {"fontSize":Contentbox.BASE_FONT_SIZE_DEFAULT +"px" } );
			}
			this.tb.displayDiv.appendChild( aDiv );
		} 
		this.imageDiv = aDiv;

		this.imageGrabDiv = new Element('div',{ id:'image'+this.id +'GrabDiv' });
		this.imageGrabDiv.setStyle( { position:'absolute' });
		setDimStyle( this.dim,this.imageGrabDiv );
		this.imageGrab =  new Element('img',{ zIndex: 10, src:"/spi/img/1pxl.gif",id:"image"+this.id+"Grab",alt:"",width:this.dim.w,height:this.dim.h });
		this.imageGrabDiv.appendChild( this.imageGrab );
		this.tb.dropDiv.appendChild( this.imageGrabDiv );

		if ( this.isImage() ){		
			this.previewImageDiv = null;
			this.image = aImg;
						
			Event.observe(this.imgPreloader, 'load', function() {
				this.image.src = this.imgPreloader.src;
				//this.image.width=this.width;
				//this.image.height=this.height;
				this.isLoaded = true;
				// new Effect.Highlight(this.image, { duration: 0.4 });
			}.bind(this) );
			Event.observe(this.imgPreloader, 'error', function() {
				this.isLoaded = true;
			}.bind(this) );

			this.imgPreloader.src = this.imageSrc;			
			
			// new PeriodicalExecuter(function(pe) { Contentbox.preloadImageTask(pe,[self]); }, 0.5);

		} else {
			// preview 
			this.previewImageDiv = new Element('div',{ id:'image'+this.id +'PreviewDiv' });
			this.previewImageDiv.setStyle({ zIndex:this.zIndex,position:'absolute', "display":"none" });
			// this.previewImageDiv.setStyle({ background : "green" });
			setDimStyle( this.dim,this.imageGrabDiv );
			this.previewImage = new Element( 'img',{ src : SPCM.dummyImage.src } );
			this.previewImage.setStyle({ zIndex: 10 ,position:'absolute', width : '100%', height : '100%', left : 0, top : 0 });
			this.previewImageDiv.appendChild( this.previewImage );
			// this.tb.displayDiv.appendChild( this.previewImage );
			this.tb.displayDiv.appendChild( this.previewImageDiv );
			copyDimensions( this.imageDiv,this.previewImageDiv );

			// this.imageDiv.setStyle({ background : "yellow" });
			this.loadDiv = new Element('div').setStyle( {
				position:"absolute", zIndex:200, top:"50%", left:"50%", height:"32px", width:"32px", margin:"-16px 0px 0px -16px"
			});
			this.loadDiv.appendChild(
				new Element('img',{ src:SPCM.loadingImage.src, width:32, height:32 } )
			);
			this.imageGrabDiv.appendChild( this.loadDiv );


			this.imageDiv.addClassName('textContentBox');
			this.image = null;
			this.lastContent = this.imageDiv.innerHTML;
			this.lastBaseFontSize = this.baseFontSizeFromDiv();
			this.isLoaded = true;
			this.isPreviewLoaded = false;

			Event.observe(this.imgPreloader, 'load', function() {
				this.previewImageSrc = this.imgPreloaderSrc;
				this.previewImage.src = this.imgPreloader.src;
				//this.image.width=this.width;
				//this.image.height=this.height;
				// this.isLoaded = true;
				// this.previewImage.addClassName("success");
				this.isPreviewLoaded = true;
				this.isPreviewOk = true;
				this.checkPreviewImageLoad();
				// new Effect.Highlight(this.image, { duration: 0.4 });
			}.bind(this) );
			Event.observe(this.imgPreloader, 'error', function() {
				this.isPreviewLoaded = true;
				this.isPreviewOk = false;
				this.previewImageSrc = null;
				this.checkPreviewImageLoad();
			}.bind(this) );
			if (!isNew){
				if ( this.config.previewImageSrc ){
					this.setPreviewImageSrc( this.config.previewImageSrc );
				}	else if ( !this.isImage() ){
					this.initPreviewImageAjax();
				}
			}
		}

		Event.observe( this.imageGrabDiv, 'mousedown',  function(e){ this.select(); }.bind(this) );
		Event.observe( this.imageGrabDiv, 'dblclick',  function(e){ 
			this.select(); 
			if (selectedContentbox){
				if ( selectedContentbox.isImage() ){
					selectedContentbox.resizeMax();
				} else {
					selectedContentbox.startEditText();
				}
				Event.stop(e);
			}
		}.bind(this));
		this.tb.displayDiv.removeClassName('containsNoImage');

	},
	
	checkPreviewImageAjax : function(){
		var url = SPCM.ajaxUrl( "previewImageAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { "contentbox" : this.id },
			onSuccess: function(resp){
				var ans = resp.responseText;
				var json = SPCM.evalJSON( ans );
				var previewPath = null;
				if ( json ){
					if ( json.status == "WORKING" ){
						return;
					}
					previewPath = json.previewImageSrc;
					if ( !previewPath || previewPath.charAt(0) != "/" ){
						previewPath = null;
					}
				}
				if ( !previewPath || !this.previewImagePE ){
					// this.previewImage.removeClassName("success");
					this.isPreviewLoaded = true;
					this.isPreviewOk = false;
					this.checkPreviewImageLoad();
				} else {
					// this.previewImage.removeClassName("success");
					this.isPreviewLoaded = false;
					this.isPreviewOk = false;
					this.setPreviewImageSrc( previewPath );
				}
				this.isPreviewLoaded = true;
				this.resetPreviewImageAjax();
		 	}.bind(this),
			onFailure: function(){ 
				this.isPreviewLoaded = true;
				this.isPreviewOk = true;
				this.resetPreviewImageAjax();
				this.checkPreviewImageLoad();
			}
		});	
	},

	resetPreviewImageAjax : function(){
		if ( this.previewImagePE ){
			this.previewImagePE.stop();
		}
		this.previewImagePE = null;
	},
	
	initPreviewImageAjax : function(){
		// alert("initPreviewImageAjax: " + this.isLoaded +  ", " + this.isPreviewLoaded + "," + this.isPreviewOk );
		this.resetPreviewImageAjax();
		if ( this.isImage() ){
			return;
		}
		this.previewImagePE = new PeriodicalExecuter(function(pe){ this.checkPreviewImageAjax(pe); }.bind(this), 0.5 );
		this.checkPreviewImageAjax(this.previewImagePE);
	},

	checkPreviewImageLoad:function(){
		// alert("checkPreviewImageLoad: " + this.isLoaded +  ", " + this.isPreviewLoaded + "," + this.isPreviewOk );
		if ( this.isInEditMode ){
				this.loadDiv.hide();
				this.previewImageDiv.hide();
				this.imageDiv.hide();
				return true;
		}
		copyDimensions( this.imageDiv,this.previewImageDiv );

		if ( this.isLoaded ){
			if ( this.isPreviewLoaded ){
				this.loadDiv.hide();
				if ( this.isPreviewOk ){
					this.previewImageDiv.show();
					this.imageDiv.hide();
				} else {
					this.previewImageDiv.hide();
					this.imageDiv.show();
				}
			} else {
				this.previewImageDiv.hide();
				this.imageDiv.show();
				this.loadDiv.show();
			}
		} else {
				this.previewImageDiv.hide();
				this.imageDiv.hide();
				this.loadDiv.show();
		}
	},

	isImage : function(){
		return ( null != this.imageSrc );
	},
	
	setZIndex : function( val ) {
		this.zIndex = val;
		if ( this.isImage() ){
			this.imageDiv.style.zIndex = val;
		} else {
			this.imageDiv.style.zIndex = ( (val*1) +500 );
			this.previewImageDiv.style.zIndex = ( (val*1) +500 );
		}
		this.imageGrabDiv.style.zIndex = ( (val*1) + 1000);
	},
	
	resizeMax : function() {
		var imageRatio = this.imageGrabDiv.getWidth() / this.imageGrabDiv.getHeight();
		var dim = extractDim(this.imageGrabDiv);
		var h = dim.h;
		var w = dim.w;
		var l = dim.l;
		var t = dim.t;

		if ( !this.isImage() ){
			this.resetPreviewImageAjax();
			if ( this.previewImage ){
				this.resetPreviewImageAjax();
				this.isPreviewLoaded = false;
				this.isPreviewOk = false;
				this.checkPreviewImageLoad();
				//this.previewImageDiv.hide();
				this.loadDiv.hide();			
				//this.imageDiv.show();
			}
		
			l = this.tb.textL;
			t = this.tb.textT;
			w = this.tb.textW;
			h = this.tb.textH;
		} else {
			var boxRatio = this.tb.ratio;
			// alert( "resize: " + imageRatio +":" + boxRatio + ": " + this.tb.width + "," + this.tb.height + ': ' + this.imageGrabDiv.getWidth() +  "," + this.imageGrabDiv.getHeight() );

			// einpassen
			var wfac = this.tb.width/w;
			var hfac = this.tb.height/h;
			if ( ( (h*wfac)/this.tb.height ) < 0.66 ){
				w *= wfac;
				h *= wfac;
			} else if ( ( (w*hfac)/this.tb.width ) < 0.66 ){
				w *= hfac;
				h *= hfac;
			} else if (boxRatio > imageRatio) {
				w = this.tb.width;
				h = this.tb.width / imageRatio;
				var maxH = Contentbox.MAXIMIZE_MAX_FACTOR * this.tb.height;
				if ( h > maxH ){
					hfac = maxH/h;
					w *= hfac;
					h *= hfac;
				}
			} else {
				h = this.tb.height;
				w = this.tb.height * imageRatio;
				var maxW = Contentbox.MAXIMIZE_MAX_FACTOR * this.tb.width;
				if ( w > maxW ){
					wfac = maxW/w;
					w *= wfac;
					h *= wfac;
				}
			}
			w = Math.ceil(w);
			h = Math.ceil(h);
			l = ( this.tb.width - w ) / 2;
			t = ( this.tb.height - h ) / 2;
		}
		this.imageGrabDiv.setStyle( { width:w+'px', height:h+'px', left:l+'px', top:t+'px' });
		this.updateSizes(true);
		this.isSaved = false;
		this.submitMove();
	},
	
	bringToFront : function() {
		var foundContentbox = this;

		var maxZIndex = 500;

		if ( contentboxArray.length > 0 ){
			maxZIndex = this.zIndex;
			var currContentbox;
			for (var i = 0; i < contentboxArray.length; i++ ){
				currContentbox = contentboxArray[i];
				if ( this.id == currContentbox.id ){
					contentboxArray.splice(i,1);
					foundContentbox = currContentbox;
					contentboxArray.push(foundContentbox);
					break;
				}
			}
			if ( contentboxArray.length > 1 ){
				maxZIndex = contentboxArray[contentboxArray.length-2].zIndex;
				maxZIndex++;
			}
			foundContentbox.setZIndex(maxZIndex);
			foundContentbox.select();
			this.isSaved = false;
			foundContentbox.submitMove();
		}
	},
	
	bringToBack : function() {
		var foundContentbox = this;
		var minZIndex = 500;
		if ( contentboxArray.length > 0 ){
			minZIndex = this.zIndex;
			var currContentbox;
			for (var i = 0; i < contentboxArray.length; i++ ){
				currContentbox = contentboxArray[i];

				if ( this.id == currContentbox.id ){
					contentboxArray.splice(i,1);
					foundContentbox = currContentbox;
					contentboxArray.unshift(foundContentbox);
					break;
				}
			}
			if ( contentboxArray.length > 1 ){
				minZIndex = contentboxArray[1].zIndex;
				minZIndex = minZIndex-1;
			}
			foundContentbox.setZIndex(minZIndex);
			foundContentbox.select();
			this.isSaved = false;
			foundContentbox.submitMove();
		}
	},
	updateToolboxVisibility : function ( isVisible ){
		if ( isVisible && this.tb ){
			this.tb.calcAndSetToolsOffset();
			this.updateSizes();
		}
		[toolFrontDiv,toolBackDiv,toolEditDiv,imageInfoDiv].each( function(el){
			el.style.visibility = "hidden";
		});

		
		if ( !isVisible ){
			toolDiv.style.visibility = "hidden";
			toolMaxsizeDiv.style.visibility = "hidden";
			return;
		}
		
		if ( contentboxArray.length > 0 ){
			if ( contentboxArray.last().id !=  this.id ) toolFrontDiv.style.visibility = "visible";
			if ( contentboxArray.first().id !=  this.id ) toolBackDiv.style.visibility = "visible";
		}
		
		if ( this.isImage() ){
			// toolDiv.addClassName('imgToolboxDivWithoutEdit');
			toolDiv.setStyle( { width:'80px' } );
			toolEditDiv.hide();
			imageInfoDiv.style.visibility = "visible";
			this.imageDiv.setStyle( { border: "1px transparent"} );
		} else {
			// toolDiv.addClassName('imgToolboxDivWithEdit');
			toolDiv.setStyle( { width:'100px' } );
			toolEditDiv.show();
			toolEditDiv.style.visibility = "visible";
			this.imageGrabDiv.setStyle( { border: "1px dashed #900" } );
		}
		toolDiv.style.visibility = "visible";
		toolMaxsizeDiv.style.visibility = "visible";
	
	},
	
	select : function() {
		if ( selectedContentbox && ( this.id == selectedContentbox.id ) && ( this.isInEditMode ) ) return false; 
		if ( selectedContentbox && selectedContentbox.isInEditMode ){
			saveAndExitEditText();
		}
		if ( ( null == selectedContentbox ) || ( this.id != selectedContentbox.id ) ){ 
			// alert("selectDiv 2: " + this.id );	
			unselectAllImages();	
			selectedContentbox = this;
			this.updateSizes();
			handleCornerArray.each( function(h){ h.show() });
			if ( !this.isImage() ){
				handleEdgeArray.each( function(h){ h.show() });
			}
		} 
		this.updateToolboxVisibility( true );
	},
	
	selectAndInitMove : function( ev ){
		this.select();
		// alert("Contentbox_doInitMove: " + this.id + "; " + selectedContentbox.id  );			
		// if ( this.id != selectedContentbox.id ) return;
		this.dim = extractDim(this.imageGrabDiv);
		this.eventX = ev.clientX;
		this.eventY = ev.clientY;		

		this.moveCounter = 0;
		Contentbox.initMoveListeners(this,false);
		ev.stop();
		return false;
	},

	doInitResize : function ( clientX, clientY ){
		if ( this.isAnimating ) return false;
		this.eventX = clientX;
		this.eventY = clientY;
		this.resetPreviewImageAjax();
		if ( this.previewImage ){
			this.isPreviewLoaded = false;
			this.isPreviewOk = false;
			this.loadDiv.hide();			
			this.checkPreviewImageLoad();
			//this.previewImageDiv.hide();
			//this.isPreviewLoaded = false;
			//this.imageDiv.show();
		}
				
		this.dim = extractDim(this.imageGrabDiv);
		this.resizeCounter = 0;
		Contentbox.initMoveListeners(this,true);
		return false;
	},

	handleMove : function(e) {	
		if ( !selectedContentbox ) return;
		if ( this.id != selectedContentbox.id ) return;
		if ( this.isInEditMode ) return;
		
		var newL = this.dim.l;
		var newW = this.dim.w;
		var newR = newL + newW;

		var newT = this.dim.t;
		var newH = this.dim.h;
		var newB = newT + newH;
								
		var deltaX = e.clientX - this.eventX;
		var deltaY = e.clientY - this.eventY;
		
		newL += deltaX;
		newT += deltaY;
			
		if ( !this.isImage() ){
			newL = limitToLT( this.tb.textL, newL );
			newT = limitToLT( this.tb.textT, newT );
			newR = newW + newL;
			newB = newH + newT;
			newR = limitToRB( this.tb.textR, newR );
			newB = limitToRB( this.tb.textB, newB );
		} else {
			newL = snapToEdge( this.tb.left, newL );
			newT = snapToEdge( this.tb.top, newT );
			newR = newW + newL;
			newB = newH + newT;
			newR = snapToEdge( this.tb.right, newR );
			newB = snapToEdge( this.tb.bottom, newB );
		}
				
		newL = newR - newW;
		newT = newB - newH;
		this.moveCounter++;
		
		this.checkAndSetPosAndSize( newL, newW, newT, newH );
		this.updateSizes();
		this.isSaved = false;
		e.stop();
	},

	handleResize : function(e) {	
		if ( !selectedContentbox ) return;
		if ( this.id != selectedContentbox.id ) return;
		if ( this.isInEditMode ) return;
		
		var newL = this.dim.l;
		var newW = this.dim.w;
		var newR = newL + newW;

		var newT = this.dim.t;
		var newH = this.dim.h;
		var newB = newT + newH;		
				
		var deltaX = e.clientX - this.eventX;
		var deltaY = e.clientY - this.eventY;
	
		if ( !this.isImage() ){
			if ( this.resizeType.indexOf('l') >= 0 ) {
				newL += deltaX;
				newL = limitToLT( this.tb.textL, newL );
				newW = newR - newL;
				if ( newW < Contentbox.MIN_TEXT_WIDTH ){
					newL += ( newW - Contentbox.MIN_TEXT_WIDTH );
					newW = Contentbox.MIN_TEXT_WIDTH;
				}
			}					
			if ( this.resizeType.indexOf('r') >= 0 ) {
				newR += deltaX;
				newR = limitToRB( this.tb.textR, newR );
				newW = newR - newL;
				if ( newW < Contentbox.MIN_TEXT_WIDTH ){
					newW = Contentbox.MIN_TEXT_WIDTH;
				}
			}
			if ( this.resizeType.indexOf('t') >= 0 ){
				newT += deltaY;
				newT = limitToLT( this.tb.textT, newT );
				newH = newB - newT; 
				if ( newH < Contentbox.MIN_TEXT_HEIGHT ){
					newT += ( newH - Contentbox.MIN_TEXT_HEIGHT );
					newH = Contentbox.MIN_TEXT_HEIGHT;
				}
			}
			if ( this.resizeType.indexOf('b') >= 0 ){
				newB += deltaY;
				newB = limitToRB( this.tb.textB, newB );
				newH = newB - newT;
				if ( newH < Contentbox.MIN_TEXT_HEIGHT ){
					newH = Contentbox.MIN_TEXT_HEIGHT;
				}
			}	
		} else {
			if ( this.resizeType=='tr' ){
				newT += deltaY;					
				// magnetisches Einrasten
				newR  = newL + ( newB - newT ) * this.ratio;
				var xOff = (this.tb.width-newR);
				newT = snapToBorder(xOff, newT, this.ratio );
				// minimale Groesse
				if ( (newB - newT) < this.minHeight ) newT = newB-this.minHeight;
				newT = Math.round(newT);
				newH = newB - newT;
				newW  = Math.round(newH * this.ratio); 
			}
			if (this.resizeType=='br') {
				newB += deltaY;
				// magnetisches Einrasten
				newR  = newL + ( newB - newT ) * this.ratio;
				var xOff = (this.tb.width-newR);
				var yOff = (this.tb.height-newB);
				yOff = snapToBorder(xOff, yOff, this.ratio );
				newH = this.tb.height - yOff -newT;
				if ( newH < this.minHeight ) newH = this.minHeight;
				newH = Math.round(newH);
				newW  = Math.round(newH * this.ratio); 
			}
			
			if (this.resizeType=='bl') {
				newB += deltaY;
				// magnetisches Einrasten
				newL  = newR - ( ( newB-newT ) * this.ratio );
				var yOff = (this.tb.height-newB);
				yOff = snapToBorder( newL, yOff, this.ratio );
				newH =	this.tb.height - yOff - newT;							
				if ( newH < this.minHeight ) newH = this.minHeight;
				newH = Math.round(newH);
				newW  = Math.round(newH * this.ratio); 
				newL  = newR - newW; 
			}
			
			if (this.resizeType=='tl') {
				newT += deltaY;					
				// magnetisches Einrasten
				newL  = newR - ( newB-newT ) * this.ratio;
				newT = snapToBorder( newL , newT, this.ratio );			
				// minimale Groesse
				if ( (newB - newT) < this.minHeight ) newT = newB-this.minHeight;
				newT = Math.round(newT);
				newH = newB - newT;
				newW  = Math.round(newH * this.ratio); 
				newL = newR - newW;
			}
		
		}
		this.resizeCounter++;
			
		this.checkAndSetPosAndSize( newL, newW, newT, newH );
		this.updateSizes();
		this.isSaved = false;
		e.stop();

	},

	moveImageWithCursor : function( ek ) {
		// alert("moveImageWithCursor: " + ek + "," +  this.isInEditMode );
		if ( this.isInEditMode ) return;
		
		var ma = Contentbox.cursorMoveByAmount; 
		var leftMove = 0;
		var topMove = 0;

		if (ek==Event.KEY_LEFT) leftMove = -ma;
		if (ek==Event.KEY_RIGHT) leftMove =  ma;
		if (ek==Event.KEY_UP) topMove  = -ma;
		if (ek==Event.KEY_DOWN) topMove  =  ma;
				
		if ( (topMove != 0) || (leftMove !=0) ){
			var dim = extractDim(this.imageGrabDiv);
			var l = dim.l;
			var t = dim.t;
			l += leftMove;
			t += topMove;
			
			this.checkAndSetPosAndSize( l, dim.w, t, dim.h );
			this.updateSizes();
			this.isSaved = false;
			this.submitMove( );
		}
		return false;
	},
	
	checkAndSetPosAndSize : function( l,w,t,h ){
		var b = t+h;
		var r = l+w;
		var ol = Contentbox.MIN_OVERLAP;
	 	if ( this.tb.top > (b-ol) ){
			b = this.tb.top+ol;
			t = b-h;
		}
		if ( this.tb.bottom < (t+ol) ) t = this.tb.bottom-ol;
		if ( this.tb.left > (r-ol) ){
			r = this.tb.left+ol;
			l = r-w;
		}
		if ( this.tb.right < (l+ol) ) l = this.tb.right-ol;
		setDimStyle( {l:l,t:t,h:h,w:w},this.imageGrabDiv );
	},
	
	updateSizes : function ( animate ) {
		var border = 1;
		var padding = 0;
		
		var dim = extractDim(this.imageGrabDiv);
		var l = dim.l;
		var t = dim.t;
		var w = dim.w;
		var h = dim.h;

		if ( animate ){
			
			if ( this.isImage() ) imageInfoDiv.hide();
			toolDiv.hide();				
			this.imageGrabDiv.hide();
			this.isAnimating=true;
			
			new Effect.Morph( this.imageDiv, {
				style: { width:w+"px", height:h+"px",left:l+"px",top:t+"px" }, // ,border:"dashed 1px #900" }, 
				afterUpdate:function(){ 
					copyDimensions( this.imageDiv, this.imageGrabDiv );
					if ( this.previewImageDiv ){
						copyDimensions( this.imageDiv, this.previewImageDiv );
					}
					this.updateSizes(false,true);
				}.bind(this),
				afterFinish:function(){
					this.isAnimating=false;
					this.updateSizes(false);
					toolDiv.show();
					if ( this.isImage() ){
						imageInfoDiv.show();
					} else {
						this.initPreviewImageAjax();
						this.checkPreviewImageLoad();
					}
					this.imageGrabDiv.show();
					
				}.bind(this),
				duration:1
			});
			return;
		}
		
		if ( this.isImage() ){
			setDimStyle( dim,this.imageDiv );
			this.image.width = w;
			this.image.height = h;
		} else {
			this.imageDiv.setStyle( {left:(l-border)+"px",top:(t-border)+"px",width:(w-2*padding)+'px',height:(h-2*padding)+'px'});
		}

		l = l + this.tb.toolsOffsetLeft;
		t = t + this.tb.toolsOffsetTop;
		
		if ( !this.isAnimating ){
			setDimStyle( dim,this.imageGrab );
			if ( this.previewImageDiv ){
				setDimStyle( dim,this.previewImageDiv );
			}
			toolDiv.setStyle( {left:l+"px",top:(t+h)+"px"});
		}
		
		handleHash.get("tl").setStyle({ left:(l-7)+"px",top:(t-7)+"px"});
		handleHash.get("tr").setStyle({ left:(l+w)+"px",top:(t-7)+"px"});
		handleHash.get("bl").setStyle({ left:(l-7)+"px",top:(t+h)+"px"});
		handleHash.get("br").setStyle({ left:(l+w)+"px",top:(t+h)+"px"});
		
		if ( this.isImage()){
			// var il = Math.max( (l+w-22),( l + toolDiv.getWidth() ) );
			if ( !this.isAnimating ){
				var il = Math.max( (l+w-22),( l + 82 ) );
			
				var scaleFactor = w / this.origWidth;
				var ppi = pixelPerInch / scaleFactor;

				var resIdx = 0;
				var infoText = "";
				if ( ppi < PPI_WARN_RED ){
					resIdx=0;
					infoText = PPI_WARN_RED_TITLE;
				} else if ( ppi < PPI_WARN_YELLOW ){
					resIdx=1;
					infoText = PPI_WARN_YELLOW_TITLE;
				} else {
					resIdx = 2;
					infoText = PPI_WARN_GREEN_TITLE;
				}
				imageInfoDiv.setStyle( { left:il+'px', top:(t+h)+'px', backgroundPosition:'0 -'+(resIdx*20)+'px' } );
				$("imageInfoImage").setAttribute('title', infoText);
			}
		} else {
			handleHash.get("l").setStyle({ left:(l-7)+"px",top:Math.round(t+h/2-3.5)+"px"});
			handleHash.get("r").setStyle({ left:(l+w)+"px",top:Math.round(t+h/2-3.5)+"px"});
			handleHash.get("b").setStyle({ left:Math.round(l+w/2-3.5)+"px",top:(t+h)+"px"});
			handleHash.get("t").setStyle({ left:Math.round(l+w/2-3.5)+"px",top:(t-7)+"px"});
		}
	},
	
	finishMove:function(e){
		Contentbox.stopMoveListeners();
		var hasChanged = ( this.resizeCounter > 0 ) || ( this.moveCounter > 0 );
		this.resizeCounter = -1;
		this.moveCounter = -1;
		if ( hasChanged ){
			this.dim = extractDim(selectedContentbox.imageGrabDiv);
			selectedContentbox.submitMove();
			Event.stop(e);
		}
	},
	
	submitMove : function() {
		if ( this.isInEditMode ) return;
		this.imageGrabDiv.setStyle( { cursor:null } );
		if ( this.isSaved ) return;
		this.isSaved=true;
		
		var dim = extractDim(this.imageGrabDiv);
	
		var url = SPCM.ajaxUrl( "moveImageAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { 
				"xpos" : dim.l, "ypos" : dim.t,  "width" : dim.w, "height" : dim.h,
				"contentbox" : this.id,  "zind" : this.zIndex
			},
			onSuccess: function(resp){
				var ans = resp.responseText;
				if ( !this.isAnimating ){
					this.initPreviewImageAjax();
					this.checkPreviewImageLoad();
				}
				// alert(ans);
		 	}.bind(this),
			onFailure: function(){ 
			}
		});	

	},
	
	editorFrame : function(){
		var result = $$('iframe.webeditor_contenteditable')[0];
		if (!result) result = $$('iframe.webeditor_contenteditable_disabled')[0];
		if (!result) result = $('editorContentFrame');
		if (!result){
			if ( !this.textEditorComatibilityWarned ){
				alert( TEXT_EDITOR_COMPATIBILITY_WARN );
				this.textEditorComatibilityWarned = true;
			}
		}
		return result;
	},
	
	editorBody : function(){
		var b = this.editorFrame().contentWindow.document.body;
		return b;
	},
	
	baseFontSizeFromEditor : function(){
		var result = stripPx( Element.getStyle( this.editorBody() ,"font-size") );
		return result ? result : Contentbox.BASE_FONT_SIZE_DEFAULT;
	},

	baseFontSizeFromDiv : function(){
		var result = stripPx( Element.getStyle( this.imageDiv ,"font-size") );
		return result ? result : Contentbox.BASE_FONT_SIZE_DEFAULT;
	},
	
	setEditorBaseFontSize : function( size ){
		Element.setStyle( this.editorBody(), { "fontSize":size } );
	},
	
	changeBaseFontSize : function( up ){
		var size = this.baseFontSizeFromEditor();
		var arr = Contentbox.BASE_FONT_SIZE_ARRAY;
		if ( up ){
			size = arr.detect( function(e){ return (e > size); } );
			if ( !size ) size =  arr.max();
		} else {
			size = arr.reverse(false).detect( function(e){ return (e < size); } );
			if ( !size ) size =  arr.min();
		}
		var content = WebEditorGetContent();
		
		// alert( "BEFORE: " + content );
	 	content = content.replace(/(<\w+\s+[^>]*)style=["']([^>]*)(font-size:[^>;]+;)([^>]*)["']([^>]*>)/gi, "$1style=\"$2$4\"$5"); 
	 	content = content.replace(/(<font[^>]*)size=["']?([1-7])["']?([^>]*>)/gi, "$1$3"); 
	 	content = content.replace(/(<font[^>]*)class=["']?fontSize\d["']?([^>]*>)/gi, "$1$2"); 
	 	// content = content.replace(/<font\s*>(.*)<\/font>/gi, "$1"); 
	 	content = content.replace(/\n/gmi, " "); 
	 	content = content.replace(/<font\s*>(.*)<\/font>/gi, "$1"); 
	 	
		// alert( "AFTER: " + content );

		WebEditorSetContent( content );
		this.setEditorBaseFontSize(size);
	},
	
	startEditText : function(){
		if (this.isImage()) return;
		if (this.isInEditMode ) return;
		// hide controls
		
		$("textPlacementInfo").hide();
		$("savebtn").hide();
		$("buttonbar").show();
		
		handleHash.values().invoke('hide');
		
		this.updateToolboxVisibility( false );
	
		var dim = extractDim(this.imageGrabDiv);
		var w = dim.w;
		var h = dim.h;
		var l = dim.l;
		var t = dim.t;

		var fl = l+1;
		var ft = t+1;
		var fh = h-4;
		var fw = w-1;
		
		var frame = this.editorFrame();
			
		Element.extend(frame.parentNode).setStyle( { width : fw+'px', height:fh+'px', left:fl+'px', top:ft+'px', border:'none' } );
		frame.width = fw;
		frame.height = fh;

		var th = ($("webeditorToolbox").getHeight()+2);
		$("webeditorToolboxWrapper").setStyle( { height:'50px', overflow:'hidden', border:'1px solid black' } );
		$("webeditorToolbox").setStyle( { top:'0px' } );
		
		var content = this.imageDiv.innerHTML;
		if (content == "" ) content = " ";
		this.lastContent = content;
		var fontSize = this.baseFontSizeFromDiv();
		if (!fontSize){ 
			fontSize = Contentbox.BASE_FONT_SIZE_DEFAULT;
			this.setEditorBaseFontSize(fontSize);
		}
		this.lastBaseFontSize = fontSize;

		// frame.focus();
		this.imageDiv.update("");
		// this.imageDiv.setStyle( { border: "1px solid #900" } );
		this.imageGrabDiv.setStyle( { border: "1px solid #900" } );

		this.isInEditMode = true;
		this.checkPreviewImageLoad();
		WebEditorSetContent( content );
		Element.setStyle( this.editorBody(), { "fontSize":fontSize+"px" } );
		WebEditorFocus();
		frame.focus();

	},
	
	exitEditText : function( content, fontSize ){
		var frame = this.editorFrame();
		Element.extend(frame.parentNode).setStyle( { top : "-1000px" } );
		$("webeditorToolboxWrapper").setStyle( { height:'0px',  overflow:'hidden', border:'none' } );
		$("webeditorToolbox").setStyle( { top:'-1000px' } );

		$("buttonbar").hide();
		$("savebtn").show();
		$("textPlacementInfo").show();

		this.imageGrabDiv.setStyle( { border: "1px dashed #900" } );
		this.isSaved=true;
		this.isInEditMode=false;
		
		this.imageDiv.innerHTML = content;
		this.imageDiv.setStyle( { "fontSize": fontSize +"px" } );
		// alert("exitEditText: " + this.imageDiv.inspect() );
		// alert("exitEditText: " + this.imageDiv.getStyle("fontSize") );
		if ( this.isLoaded ){
			handleHash.values().invoke('show');
			toolDiv.style.visibility = "visible";
			this.updateToolboxVisibility( true );
		}
	},
	
	/*
	showLoadDiv : function( fontSize ){
		if (this.isImage()) return;
		var dim = extractDim(this.imageGrabDiv);
		var l = dim.w/2 -16;
		var t = dim.h/2 -16;
		var loadDiv = "<div style='position:absolute; zIndex:1000; top:" + t +"px; left:" + l + "px; height:32px;width:32px;'>";
    loadDiv += "<img src='" + SPCM.loadingImage.src + "' width=32 height=32>"
    loadDiv += "</div>"
    this.isLoaded = false;
   	this.exitEditText(loadDiv, fontSize);
  },
  */
  	
	saveEditText : function( content, fontSize, doExit ){
		if (this.isImage()) return;
		if (!content) content= WebEditorGetContent();
		if (!fontSize) fontSize=this.baseFontSizeFromEditor();
    // this.imageDiv.update( content );
    this.isLoaded = false;
    this.isPreviewLoaded = false;
		this.checkPreviewImageLoad();
		// this.showLoadDiv( fontSize );
		
		var url = SPCM.ajaxUrl( "submitEditorAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { "contentbox" : this.id,  "content" : content, "fontSize" : fontSize },
			onSuccess: function(resp){
				var ans = resp.responseText;
				// alert(ans);
				var previewPath = null;
				var json = SPCM.evalJSON( ans );
				var html = "ERROR";
				if ( json && json.status == "OK" ){
					if( json.content ){
						html = json.content;
					} else {
						html = "";
					}
					previewPath = json.previewImageSrc;
					if ( !previewPath || previewPath.charAt(0) != "/" ){
						previewPath = null;
					}
					if ( json.fontSize ){
							this.lastBaseFontSize = fontSize;
					}
				}
				this.setHtml( html );
				this.isLoaded = true;
				// console.log("saveEditText success");
				this.isPreviewOk = false;
				if ( json && json.previewStatus == "WORKING" ){
					this.isPreviewLoaded = false;
					this.initPreviewImageAjax();
				} else if ( !previewPath ){
					this.isPreviewLoaded = true;
				} else {
					// alert( this.imgPreloader + "   " + previewPath );
					this.isPreviewLoaded = false;
					this.setPreviewImageSrc( previewPath );
				}
				
				if ( doExit ){ 
					this.exitEditText( html, this.lastBaseFontSize );
				}	
				this.checkPreviewImageLoad();
		 	}.bind(this),
			onFailure: function(){ 
			}
		});	
		return;
	},
	
	saveAndExitEditText : function(){
		this.saveEditText( null, null, true );
		/* 
		var savedVals = this.saveEditText();

		if (this.isImage()) return;
		var savedVals = this.saveEditText();
		var content = savedVals[0]; 
		var fontSize = savedVals[1];
		this.lastContent=content;
		this.lastBaseFontSize = fontSize;
    	// this.imageDiv.update( content );
		
		var dim = extractDim(this.imageGrabDiv);
		var l = dim.w/2 -16;
		var t = dim.h/2 -16;
		
    	var loadDiv = "<div style='position:absolute; zIndex:1000; top:" + t +"px; left:" + l + "px; height:32px;width:32px;'>";
    	loadDiv += "<img src='" + SPCM.loadingImage.src + "' width=32 height=32>"
    	loadDiv += "</div>"
    	this.isLoaded = false;
   		this.exitEditText(loadDiv, fontSize);
   	 */
	},
	
	setHtml : function( html ){
		if (this.isImage()) return;
		this.imageDiv.innerHTML = html;
		// this.isLoaded = true;
		if ( this == selectedContentbox ){
			handleHash.values().invoke('show');
			toolDiv.style.visibility = "visible";
			this.updateToolboxVisibility( true );
		}
	},
	
	cancelEditText : function(){
		if (this.isImage()) return;
		this.saveEditText(this.lastContent,this.lastBaseFontSize, true );
		// this.exitEditText(this.lastContent,this.lastBaseFontSize);
	},
	
 	lastContentIsEmpty:function(){
		return ( ( this.lastContent==null) || this.lastContent.blank() );
 	},

	remove : function(){
		this.updateToolboxVisibility( false );
		unselectAllImages();
		if ( this.isImage() || !this.lastContentIsEmpty() ){
			var fadeObj = ( this.image ) ? this.image : this.imageDiv;
			Effect.Fade(fadeObj, {duration:0.5, afterFinish: function() { this.dispose(); }.bind(this) });
		} else {
			this.dispose();
		}

		var url = SPCM.ajaxUrl( "removeImageAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { "removedImage" : this.id, "box" : this.tb.id },
			onSuccess: function(resp){
				var ans = resp.responseText;
				// alert(ans);
		 	}.bind(this),
			onFailure: function(){ 
			}
		});	
	}

}


// BEGIN Contentbox Class methods
Object.extend(Contentbox, {

checkImageLoad:function(cb){
	if ( !cb.isImage() ) return;
	if ( cb.isLoaded ){
		if ( cb.loadDiv ){ 
			cb.loadDiv.remove();
			cb.loadDiv = null;
		}
		return true;
	} else if ( !cb.loadDiv && !cb.isAnimating ){
		cb.loadDiv = new Element('div',{ id: "load" + this.id +"Div"} ).setStyle( {
			// border:"1px solid red",
			position:"absolute", zIndex:1000, top:"50%", left:"50%", height:"32px", width:"32px", margin:"-16px 0px 0px -16px"
		});
		cb.loadDiv.appendChild(
			new Element('img',{ id:"load" + cb.id+"Img",  src:SPCM.loadingImage.src, width:32, height:32 } )
		);
		cb.imageDiv.appendChild( cb.loadDiv );
	}
	return false;
},

preloadImageTask:function( pe, cbArray ){
	var finished = true;
	cbArray.each( function(cb){
		finished = finished && Contentbox.checkImageLoad(cb);
	});
	if ( finished ) pe.stop();
},

makeNew:function( id, tbId, config ){
	var tb = Templatebox.findWithId(tbId);
	if (!tb) return null;
	var cb;
	if ( tb.isStamp() ){
		cb = new FixContentbox( id,tb,config ); 
		return;
		// return cb.createDOM();
	} else {
		cb = new Contentbox( id,tb,config ); 
		cb.createDOM( true );
		cb.setZIndex( config.zIndex );
	}

	new PeriodicalExecuter(function(pe) { Contentbox.preloadImageTask(pe,[cb] ); }, 0.5);
	unselectAllImages();

	if ( !tb.isStamp() ){
		cb.select();
		if (cb.maximise) cb.resizeMax();
		if (!cb.isImage() ){
			cb.startEditText();
		}
	}	

	// cb.imageGrabDiv.onmousedown=cb.selectAndInitMove;

	cb.imageGrabDiv.observe('mousedown', cb.selectAndInitMove.bindAsEventListener(cb) );
},

init:function( droppedImageId ){
	// alert("initArray: " + contentboxArray.length + "; droppedImageId" + droppedImageId );
	
	var droppedContentbox = null;
	// var cb;
	var lastZIndex = -1;

	var toSubmitArray = new Array();
	
	contentboxArray.each( function(cb){
		cb.createDOM( false );
		// alert("cb.zIndex: " + cb.zIndex );
		var currZIndex = cb.zIndex;
		if (!currZIndex){
			if ( lastZIndex < 0 ) lastZIndex = 499;
 			currZIndex = lastZIndex+1;
		}
		if ( currZIndex <= lastZIndex ){ 
			currZIndex = ( lastZIndex*1 ) + 1;
			cb.setZIndex( currZIndex );
			toSubmitArray.push(cb);
		} else {
			cb.setZIndex( currZIndex );
		}
		// alert("AFTER cb.zIndex: " + cb.zIndex );
		lastZIndex = currZIndex;
		if ( ( droppedImageId != "" ) && ( droppedImageId == cb.id ) ){
			droppedContentbox = cb;
		}
	});
	new PeriodicalExecuter(function(pe) { Contentbox.preloadImageTask(pe, contentboxArray.clone() ); }, 0.5);
	["tl","tr","bl","br","l","r","b","t"].each( function(id){
		var h = $("handle_" + id);
		if ( id.length == 1 ){
			handleEdgeArray.push(h);
		} else {
			handleCornerArray.push(h);
		} 
		handleHash.set(id,h);
		Event.observe(h, 'mousedown', Contentbox.initResize.bindAsEventListener(h) );
	});

	toolDiv = $("imageToolboxDiv");
	toolFrontDiv = $("imageToolboxFrontDiv");
	toolMaxsizeDiv = $("imageToolboxMaxSizeDiv");
	toolBackDiv = $("imageToolboxBackDiv");
	toolEditDiv = $("imageToolboxEditDiv");
	imageInfoDiv = $("imageInfoDiv");
	
	unselectAllImages();
	// window.onbeforeunload = saveEditorOnExit;

	if ( droppedContentbox ){
		droppedContentbox.select();
		if (droppedContentbox.maximise){
			droppedContentbox.resizeMax();
		}
	}
	contentboxArray.each( function(cb){
		cb.imageGrabDiv.observe('mousedown', cb.selectAndInitMove.bindAsEventListener(cb) );
	});
},

stopMoveListeners:function(){
	if ( this.ListenerMouseMove){
		Event.stopObserving(document.body, 'mousemove', this.ListenerMouseMove );	
	}
	if ( this.ListenerMouseUp){
		Event.stopObserving(document.body, 'mouseup', this.ListenerMouseUp );	
	}
},
initMoveListeners:function( cb, isResize ){
	this.stopMoveListeners();
	if (isResize){
		this.ListenerMouseMove = 	cb.handleResize.bindAsEventListener(cb);
	} else {
		this.ListenerMouseMove = 	cb.handleMove.bindAsEventListener(cb);
	}
	Event.observe(document.body, 'mousemove', this.ListenerMouseMove );
	this.ListenerMouseUp = cb.finishMove.bindAsEventListener(cb);
	Event.observe(document.body, 'mouseup', this.ListenerMouseUp );
},
initResize:function(e){
	var cb = selectedContentbox;
	if ( !cb ) return false;
	cb.resizeType = this.id.replace('handle_','');
	cb.doInitResize( e.clientX, e.clientY );
	e.stop();	
	return false;
},

WARN_CANCEL_EDIT:"Wollen Sie wirklich alle &Auml;nderungen im Text r&uuml;ckg&auml;ngig machen?",

cancelEditText : function(){
	var cb = selectedContentbox;
	if (!cb) return;
	if (cb.isImage()) return;
	var content=WebEditorGetContent();
	if ( content != cb.lastContent ){ 
		var doDel = confirm(this.WARN_CANCEL_EDIT);
		if (!doDel) return;
	}
	cb.cancelEditText(content);
}

});
// END Contentbox class methods

function snapToBorder( xOffset, yOffset, ratio ) {
	var result = yOffset; 

	if ( Math.abs(xOffset) <= Contentbox.magneticBorderRange ){
		result -= ( 0.5 + xOffset / ratio );
		if ( (result > 0) && ( result <= Contentbox.magneticBorderRange ) ){
			result = 0;
		} 
	} else if (  Math.abs(result) <= Contentbox.magneticBorderRange ){
		result = 0;
		var newXOffset = xOffset - (yOffset-result) * ratio;
		// wenn drinnen, dann schauen ob Rand entstanden ist
		if ( ( newXOffset > 0 ) && ( newXOffset <= Contentbox.magneticBorderRange ) ){
			result = result - ( 0.5 + newXOffset / ratio );
		} 
	}
	return result;
}

function limitToLT( borderVal, newVal ) {
	var offset = newVal - borderVal;
	if ( offset < 0 ) return borderVal;
	return newVal;
}

function limitToRB( borderVal, newVal ) {
	var offset = borderVal - newVal;
	if ( offset < 0 ) return borderVal;
	return newVal;
}

function snapToEdge( borderVal, newVal ) {
	var offset = Math.abs( newVal - borderVal);
	if ( offset <= Contentbox.magneticBorderRange ) return borderVal;
	return newVal;
}


function unselectAllImages () {
	toolDiv.style.visibility = "hidden";
	handleHash.values().invoke('hide');
	contentboxArray.each( function(cb){ 
		if ( !cb.isImage() ){
			cb.imageGrabDiv.setStyle( { border: "1px dashed #ccc" } );	
		}
	} );
}

function bringToFront () {
	if (!selectedContentbox) return;
	selectedContentbox.bringToFront();
}

function bringToBack () {
	if (!selectedContentbox) return;
	selectedContentbox.bringToBack();
}

function resizeMax () {
	if (!selectedContentbox) return;
	selectedContentbox.resizeMax();
}		

function startEditText(){
	if (!selectedContentbox) return;
	if (selectedContentbox.isImage()) return;
	selectedContentbox.startEditText();
}

function saveAndExitEditText(){
	if (!selectedContentbox) return;
	if (selectedContentbox.isImage()) return;
	selectedContentbox.saveAndExitEditText();
}

function cancelEvent(e){
	var el = e.element();
	var name = el.tagName;
	if (!name) return true;
	//alert(source.tagName);				
	if( (name=='INPUT') || (name=='TEXTAREA') ) return true;
	e.stop();
	return false;
}

SPCM.KeyEventArray = [ Event.KEY_DELETE, Event.KEY_LEFT,Event.KEY_UP,Event.KEY_RIGHT, Event.KEY_DOWN ];

function moveImageWithCursor(ev) {
	var selCb = selectedContentbox;
	if ( !selCb ) return true;
	if ( selCb.isInEditMode ) return true;
	var isSL = false;
	senderlineArray.each( function(sl){
		if ( sl.visible() ){
			isSL=true;
			return;
		}
	});
	if ( isSL ) return true;
	var ek= ev.which || ev.keyCode;
	if ( SPCM.KeyEventArray.indexOf(ek) < 0 ) return false;
	var el = ev.element();
	var tagName = el.tagName;
	if (!tagName || tagName.blank() ) return true;
	['INPUT','TEXTAREA','SELECT'].each( function(s){ if(s == tagName) return true; });

	if ( [ Event.KEY_DELETE ].indexOf(ek) >=0 ){
		selCb.remove();
		return false;
	}	
	// alert( isMouseOverElement( ev, selectedContentbox ) );
	ev.stop();
	return selCb.moveImageWithCursor( ek );	
}

      	
function afterFinishRevertHandler(){
	if ( dropWasDenied ){
		alert( dropWasDeniedMessage );
		dropWasDenied = false;
	}
}
 
function makeDragableImage( imageId ){
	Event.observe( imageId,'dblclick',  function(e){ 
		var tb = Templatebox.getEditable();
		if ( !tb ) return false;
		if (tb.hasMaxContentCount() ){
		// if (maxContentboxCountOnPage){ 
			alert( dropWasDeniedMessage );
			// Event.stop(e);
			return false;
		}
		var el = Event.element(e);
		
		var idx = contentboxArray.length;
		var l = 10 + ((idx*50) % ( tb.width - 50 ) );
		var t = 10 + ((idx*50) % ( tb.height - 50 ) );
		
		tb.submitDrop( l, t, null, null, $(imageId) );
		Event.stop(e);
		return false;
	});
	return new Draggable( imageId ,{
		ghosting:true, // true results in an error in IE 7
		revert: true, // function(){ return isRevertEffectOn; }, 
		reverteffect : function(element, top_offset, left_offset) {
			var dur = isRevertEffectOn ? Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02 : 0;
			var effect = new Effect.Move(element, { 
				x: -left_offset, y: -top_offset, duration: dur, 
				queue: {scope:'_draggable', position:'end'}, 
				afterFinish:function(){ 
					if ( isBrowserIEOrOpera() ) $(imageId).setStyle( { position:"static" } )
					afterFinishRevertHandler(); 
				}
			});
		}
	});
}

function imageRemoveHandler(){
	if ( selectedContentbox ) selectedContentbox.remove();
}

function selectHighestTextbox(){
	for (var i=contentboxArray.length-1; i>=0; i-- ){
		cb = contentboxArray[i];
		if ( !cb.isImage() ){
			cb.select();
			return;
		}
	}
}

function getTextboxById( id ){
	for (var i=contentboxArray.length-1; i>=0; i-- ){
		cb = contentboxArray[i];
		if ( !cb.isImage() && cb.id == id ){
			return cb
		}
	}
	return null;
}


/*** Cliparts ***/

var ClipartCategory = Class.create();

ClipartCategory.allClipartArray = new Array();
ClipartCategory.clipartCategoryArray = new Array();
ClipartCategory.tdDisplayedArray = new Array();
ClipartCategory.selectedClipartCategory = null;

ClipartCategory.clipartDisplayRow1 = null;
ClipartCategory.clipartDisplayRow2 = null;
ClipartCategory.slider = null;

ClipartCategory.batchSize = 4;
ClipartCategory.selectContentCategoryURL = "",


ClipartCategory.prototype = {
	initialize: function( extId ) {   
		//alert("constructor ClipartCategory: " + extId + ", " + text );
		this.extId = extId;
		// this.text = text;
		this.clipartArray = new Array();
		ClipartCategory.clipartCategoryArray.push( this );
		if ( !ClipartCategory.selectedClipartCategory ) ClipartCategory.selectedClipartCategory = extId;
		var isSelected = ( extId == ClipartCategory.selectedClipartCategory );
		// ClipartCategory.appendOption( extId, text, isSelected );
		//alert("constructor ClipartCategory: " + extId + ", " + text );
	},

	addClipart : function( withId, withImageUrl ){
		newClipart = new Clipart( withId,withImageUrl );
		this.clipartArray.push( newClipart );
		ClipartCategory.allClipartArray.push( newClipart );
	},
	addCliparts : function( idArray ){
		idArray.each( function( def ){ 
			if ( def && ( def.length == 3 ) ){ 
				var id = def[0];
				var url = "/spi/processedcliparts/" + id;
/* 
				if ( def[1] ){ 
					url += "_tiny_idx.";
				} else {
					url += "_tiny.";
				}
 */
				if ( def[1] ){ 
					url += "_mini_idx.";
				} else {
					url += "_mini.";
				}
				url +=  def[2];
				this.addClipart(id,url);
			}
		}.bind(this) );
	}
}

ClipartCategory.scrollHorizontal = function(value, element, slider) {
	element.scrollLeft = Math.round(value/slider.maximum*(element.scrollWidth-element.offsetWidth));
}
	
/** Event handler for mouse wheel event. */
ClipartCategory.wheelHandler = function(event){
	if (!ClipartCategory.slider) return true;
	var delta = 0;
	if (event.wheelDelta) { /* IE/Opera. */
		delta = event.wheelDelta/120;
		if (window.opera) delta = -delta;
	} else if (event.detail) { 
		delta = -event.detail/3;
	}

	var count = selectedClipartArray().length;
	if ( count > 0 );
	delta /= count;
	if (delta) ClipartCategory.slider.setValueBy(-delta);

	if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

ClipartCategory.initSlider = function( contentId, trackWrapId, trackId, handleId, handleLeftId, handleRightId ){
	var slider = ClipartCategory.slider;
	if ( slider ){
		ClipartCategory.slider = null;
		slider.dispose();
	}
	var ce = $(contentId);
	var sw = ce.scrollWidth;
	var ow = ce.offsetWidth;
	// alert("init:" + contentElem.scrollWidth + ", " + contentElem.offsetWidth );
	if ( true && sw > ow ) {
		// $(trackWrapId).show();
		$("clipartTrackHandle").show();
		var newW = (ow*ow/sw).toFixed();
		var rightW = $("clipartTrackHandleRight").getWidth();
		if ( newW < rightW * 2 ) newW = rightW*2;
		// alert( newW );
		$("clipartTrackHandle").setStyle( { width:newW+"px" } );
		var leftW = newW - rightW;
		$("clipartTrackHandleLeft").setStyle( {width:leftW+"px" } );
		$("clipartTrackHandleRight").setStyle( {left:leftW+"px" } );
		var slider = new Control.Slider( handleId , trackId, {
			onSlide:  function(v) { ClipartCategory.scrollHorizontal(v, ce, slider);  },
			onChange: function(v) { ClipartCategory.scrollHorizontal(v, ce, slider); }
		});
		slider.setEnabled();
		slider.setValue(0);
		ClipartCategory.slider = slider;
	} else {
		// $(trackWrapId).hide();
		$("clipartTrackHandle").hide();
	}
	var tipp = $("tippTextboxInsert");
	if ( tipp ){
		updateTipps( tipp.id );
	}
}

ClipartCategory.refreshSlider = function(){
	ClipartCategory.initSlider( 'clipartContent', 'clipartTrackWrap', 'clipartTrack', 'clipartTrackHandle' );
}

/*
ClipartCategory.appendOption = function( withId, withText, isSelected ){ 
	var optionElement = new Element("OPTION", { value:withId, selected:isSelected } );
	optionElement.update(withText);
	$("clipartCategorySelect").appendChild(optionElement);
}
*/

function selectedClipartArray(){
	var selCat = ClipartCategory.selectedClipartCategory;
	if ( selCat ){
		return selCat.clipartArray;
	}	
	return ClipartCategory.allClipartArray;
}

ClipartCategory.procCount = 0;
ClipartCategory.lastCount = 0;
ClipartCategory.scn = 0;


ClipartCategory.checkSlider = function( scn, len ){
	if ( scn != ClipartCategory.scn ) return false;
	
	var cnt = ClipartCategory.procCount;
	var lastCnt = ClipartCategory.lastCount;
	 ClipartCategory.lastCount = cnt;
	
	var row = ClipartCategory.clipartDisplayRow1;
	if ( row && row.hasChildNodes() ){
			// console.log("checkSlider:" + cnt + "," + len );
	    if ( cnt != lastCnt ){
	    	/*
	    	row.select("img").each( function(img){
				makeDragableImage( img.id );
				if ( isBrowserIEOrOpera() ) img.setStyle( { position:"static" });
	    	});
	    	*/
	    	ClipartCategory.refreshSlider();
    	}
    	if ( cnt < len  ){
			setTimeout( function(){ ClipartCategory.checkSlider( scn, len ); }, 1000 );
    	}
	}
}

function insertCliparts( scn, showArray ){
	if ( scn != ClipartCategory.scn ) return false;
	// alert("insertCliparts");
	// ClipartCategory.imageProcessCount = 0;
	ClipartCategory.refreshSlider();
	if (!showArray) return;

	/*
		for ( i=0;i<showArray.length; ++i ){
			var clipart = showArray[i];
			clipart.makeTD( ClipartCategory.clipartDisplayRow, showArray.length );
		}
	*/
	var len = showArray.length;
	if ( len > ClipartCategory.batchSize ) len = ClipartCategory.batchSize;
	for ( i=0;i<len; ++i ){
		var clipart = showArray[i];
		var row = ( (i % 2) == 0 ) ? ClipartCategory.clipartDisplayRow1 : ClipartCategory.clipartDisplayRow2;
		clipart.makeTD( scn, row, showArray.length );
	}
	if ( showArray.length > ClipartCategory.batchSize )	{
		// setTimeout( function(){
		for ( i=len;i<showArray.length; ++i ){
			var clipart = showArray[i];
			var row = ( (i % 2) == 0 ) ? ClipartCategory.clipartDisplayRow1 : ClipartCategory.clipartDisplayRow2;
			clipart.makeTD( scn, row, showArray.length );
		}
		// }, 10 );
		setTimeout( function(){ ClipartCategory.checkSlider( scn, showArray.length ); }, 1000 );
	}

}

function showSelectedCliparts ( ){

	var scn = ClipartCategory.scn+1;
	ClipartCategory.scn = scn;
	ClipartCategory.procCount = 0;
	ClipartCategory.lastCount = 0;

	// console.log("showSelectedCliparts scn: " + scn + ": " + ClipartCategory.selectedClipartCategory.text );

	var showArray = selectedClipartArray();

	var row = ClipartCategory.clipartDisplayRow1;
	if ( row && row.hasChildNodes() ){
	    while ( row.childNodes.length >= 1 ){
	    	var child = row.firstChild;
	    	if ( child.scn != scn ){
	        	row.removeChild( child );	        	
	        }
    	} 
	}
	row = ClipartCategory.clipartDisplayRow2;
	if ( row && row.hasChildNodes() ){
	    while ( row.childNodes.length >= 1 ){
	    	var child = row.firstChild;
	    	if ( child.scn != scn ){
	        	row.removeChild( child );	        	
	        }
    	} 
	}
	insertCliparts.defer( scn, showArray );
	
	
}


function selectClipartCategory( byId ){
	var result = ClipartCategory.clipartCategoryArray.find( function(cc){
		return (cc.extId == byId);
	});
	ClipartCategory.selectedClipartCategory = result;
	showSelectedCliparts();
}


function clipartCategorySubmit(){
	var theId=0; 
	if ( null != ClipartCategory.selectedClipartCategory ){
		theId = ClipartCategory.selectedClipartCategory.extId;
	}
	
	var url = SPCM.ajaxUrl( "selectContentCategoryAjax" );
	new Ajax.Request(url,{
		method:'post',
		parameters : { "contentCategoryId" : theId },
		onSuccess: function(resp){
			var ans = resp.responseText;
			// alert(ans);
	 	}.bind(this),
		onFailure: function(){ 
		}
	});	
		
	// return result;
}


function insertTDImage( scn, id, image, td, len ){
	if ( scn != ClipartCategory.scn ) return;
	if ( td.hasChildNodes() ) return;
	// img.src = image.src;
	// alert ("image: " + image + "src" + image.src + ":" + image.width + "," + image.height );
	
	var img = new Element('img', { id:id, src:image.src, width:image.width, height:image.height });
	img.addClassName('draggable_image');
	
	td.appendChild(img);
	
	makeDragableImage( id );
	if ( isBrowserIEOrOpera() ) img.setStyle( { position:"static" });
	img.style.zIndex =10000;
}

var clipartArray = new Array();

var Clipart = Class.create();
Clipart.tdId = 1;

// Clipart.imageHash = new Hash();

Clipart.prototype = {
	initialize: function( clipartPk, imageUrl ) {   
		// alert("constructor Clipart: " + clipartPk + ", " +  imageUrl );
		this.extId = "draggableClipart_" + clipartPk;
		this.imageUrl = imageUrl;
		clipartArray.push(this);
		this.td = null;
	},
	
	makeTD : function( scn, parentRow, len ){
		if ( scn != ClipartCategory.scn ) return;
		var td = this.td;
		if (!td){ 
			td = new Element('td');
			td.id = "TD_" + Clipart.tdId;
			td.scn = scn;
			Clipart.tdId++;
			this.td = td;
		}
		parentRow.appendChild( td );
		
		
		var img = new Image();
		img.onload = function(){
			if ( scn != ClipartCategory.scn ) return;
			ClipartCategory.procCount++;
			// console.log("onload: " + scn + "; cnt: " + cnt + "; hash: " + ClipartCategory.scn2procCount.get(scn) );
			insertTDImage(scn, this.extId,img,td,len);
		}.bind(this);
		img.onerror = function(){
			if ( scn != ClipartCategory.scn ) return;
			ClipartCategory.procCount++;
		}.bind(this);
		img.src = this.imageUrl;

	}	
}

function clipartById( anId ){ return clipartArray.find( function(c){ return (anId == c.extId) }); }


var ParseHtml = {
	scTagOpen:'<span class="wrapSpecialChar">',
	scTagClose:'</span>',
	scUnwrapRE:null,
	scWrapRE:null,
	fontSizeDecodeRE : /<font([^>]*)size=\"?([1-7])\"?([^>]*)>/gi,
	fontSizeEncodeRE : /<font([^>]*)class=\"?fontSize([1-7])\"?([^>]*)>/gi,
	isInitalised:false
};

ParseHtml.init = function(){
	if ( ParseHtml.isInitalised ) return;
	var wrapInFontArray=$w("harr crarr lArr uArr rArr dArr hArr hArr forall part exist empty nabla isin notin ni prod sum minus lowast radic prop infin ang and or cap cup int there4 sim cong asymp ne equiv le ge sub sup nsub sube supe oplus otimes perp sdot lceil rceil lfloor rfloor lang rang loz spades clubs hearts diams");
	var scWrapPat = '(&(' + wrapInFontArray[0];
	for (var i = 1, len = wrapInFontArray.length; i < len; ++i ){
		scWrapPat += "|";
		scWrapPat += wrapInFontArray[i];
	}
	scWrapPat += ");)"
	var scUnwrapPat = ParseHtml.scTagOpen + scWrapPat + ParseHtml.scTagClose;
	ParseHtml.scUnwrapRegex = new RegExp(scUnwrapPat, "gmi");
	ParseHtml.scWrapRegex = new RegExp(scWrapPat, "gmi");
	ParseHtml.isInitalised=true;
}


ParseHtml.decode = function( content ){
	ParseHtml.init();
	//alert("0: " + content);
 	content = content.replace(/<font([^>]*)size="\+0"([^>]*)>/gi, "<font$1$2>"); 
 	content = content.replace(/<font([^>]*)size="\-0"([^>]*)>/gi, "<font$1$2>"); 
 	content = content.replace(/<font\s*>/gi, "<font>"); 
	//alert("1: " + content);
	content = content.replace(ParseHtml.fontSizeDecodeRE, '<font$1class=\"fontSize$2\"$3>'); 
	//alert("2: " + content);
	
	content = content.replace(/<p\s+\/>/gi, '<p>&nbsp;</p>'); 
	content = content.replace(/<font\s+\/>/gi, ''); 
	//alert("3: " + content);
	
	// wrap special characters for BOLD printing
	content = content.replace(ParseHtml.scUnwrapRegex, '$1' ); 
	content = content.replace(ParseHtml.scWrapRegex, ParseHtml.scTagOpen + '$1' + ParseHtml.scTagClose ); 
	// Bugfix alignment in safari is written in body
	if ( selectedContentbox && !selectedContentbox.isImage() ){
		var editBody = selectedContentbox.editorBody();
		var align = Element.getStyle( editBody,"text-align");
		if ( ( align ) && ( align != "left" ) ){
			content = "<div style='text-align:"+align+";'>" + content + "</div>";
			Element.setStyle( editBody,"text-align",null);
		}
	}	
	//alert("4: " + content);
 	return content; 
} 


ParseHtml.encode = function(content) {
	ParseHtml.init();
 	content = content.replace( ParseHtml.fontSizeEncodeRE, '<font$1size=$2$3>'); 
	return content; 
} 

// Upload images
var SPCMUploadImage = Class.create({
	initialize: function( imgDiv ) {
		this.div = imgDiv;
		this.div.show();
		
		this.img = this.div.down("img.upload_image");
		this.imageId = this.img.id;
		this.id = this.imageId.replace("draggableImage_","");
		
		this.imgDel = this.div.down("img.delimg");
		this.imgDel.hide();
			
		this.div.observe( 'mouseover', function(e){ 
			this.imgDel.show(); 
		}.bindAsEventListener(this) );
		this.div.observe( 'mouseout', function(e){ 
			if ( !isMouseOverElement(e,this.imgDel) ){
				this.imgDel.hide(); 
			}
		}.bindAsEventListener(this))
		this.imgDel.observe( 'click', function(e){ 
			this.remove(); 
		}.bindAsEventListener(this));
		
		makeDragableImage( this.imageId );
	},

	remove : function(){
		var url = SPCM.ajaxUrl( "removeUploadImageAjax" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { "uploadImageId" : this.id },
			onSuccess: function(resp){
		 		Effect.Fade(this.div, {
		 			duration:0.5, 
		 			afterFinish: function() { 
			 			this.div.remove(); 
						updateTipps.defer();
			 		}.bind(this) 
			 	})
		 	}.bind(this),
			onFailure: function(){ 
			}
		});		
	}	
});

Event.observe(window, 'load', function() {
	var imgEditDiv = $("imageEdit");
	if ( !imgEditDiv ) return;
	imgEditDiv.select("div.imgcontainer").each( function ( imgDiv ) {
		new SPCMUploadImage(imgDiv);
	});
});

// INIT Folder
var SPCMDesignFolder = Class.create({
	initialize: function( item ) {
		this.item = item;
		this.name = this.item.readAttribute("spcm_folder");
		this.header = this.item.down("div.header");
		this.link = this.header.down("a.toggle");
		this.content = this.header.next("div.content_listitem");
		
		this.link.observe("click", function( ev ){
			ev.stop();
			this.toggle();
		}.bindAsEventListener(this) );
	},
	
	notify : function( open ){
		var url = SPCM.ajaxUrl( "folderOpenStateNotify" );
		new Ajax.Request(url,{
			method:'post',
			parameters : { "folder" : this.name, "open" : open },
			onSuccess: function(resp){
			}.bind(this),
			onFailure: function(){ 
			}.bind(this)
			
			
		});	
	},
	
	isOpen : function(){
		return this.header.hasClassName("header_open");
	},
	
	hide : function(){
		hideTipps();
		this.header.removeClassName("header_open");
		this.content.hide();
		this.notify( false );
		updateTipps.defer();
	},
	hasUploadedImages : function(){
		var editDiv = $("imageEdit");
		if ( !editDiv ){
			return false;
		}
		return ( editDiv.select("div.imgcontainer").size() > 0 );
	},
	
	show : function(){
		hideTipps();
		if ( this.name == "clipart"){
			if ( this.hasUploadedImages() ){
				var imageFolder = name2Folder.get("image");
				if ( imageFolder ){
					imageFolder.hide();
				}
			}
		} else if ( this.name == "image"){
			if ( this.hasUploadedImages() ){
				var clipartFolder = name2Folder.get("clipart");
				if ( clipartFolder ){
					clipartFolder.hide();
				}
			}
		}		
		this.header.addClassName("header_open");
		this.content.show();
		this.notify( true );
		updateTipps.defer();
	},
	toggle : function(){
		if ( this.isOpen() ){
			this.hide();
		}	else {
			this.show();
		}
	}


});
 
var name2Folder = new Hash();


Event.observe(window, 'load', function() {
	$("designcolleft").select("div.listitem").each( function(item){
		var folder = new SPCMDesignFolder( item );
		name2Folder.set( folder.name, folder ); 
	});

});



