function changeProduct(id) {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response) {
			resetDesigner();
			initProduct(response);
			addProductColorEvents();
			$('region_list').innerHTML = response.regionListHTML;
			getPrice();
			//show product name
            $('productName').innerHTML = response.name;
		}
	}).post({'functionName': 'changeProduct', 'param': id});
}

function setShirtColor(param) {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response) {
			productImage.set('src', pictureBase+'products/'+response.shirtColorHTML);
			$('region_list').innerHTML = response.regionListHTML;
			getFontColors();
			getMotivListe($$('div#motiv_category select').get('value')[0]);
			if(getActiveMotiv() != null)
			{
    			getMotivState(getActiveMotiv().get('id'));
    			reloadMotivImage(getActiveMotiv().get('id'),response);
			}
		}
	}).post({'functionName': 'setShirtColor', 'param': param});
}

function getMotivListe(param) {
	var request = new Request.HTML({
		url: ajaxBridge,
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
            if(typeof myTips != "undefined")
            {
                myTips.detach('.motiv');
                myTips.hide();
            }
            if(typeof myTips2 != "undefined")
            {
                myTips2.detach('.motiv_noselect');
                myTips2.hide();
            }

			motivList.set('html', responseHTML);
			addMotivDragEvents();
			addMotivTooltips();
			postloadiepngfix();
		}
	}).post({'functionName': 'getMotivListe', 'param': param});
}

function addMotivTooltips()
{
    //myTips = new Tips('.motiv',{className: 'tooltip'});
    //myTips2 = new Tips('.motiv_noselect',{className: 'tooltip'});
/*    $$('.motiv').each(function(el){
        if(el.title != ''){
    		new Tips('#'+el.id,{className: 'tooltip'});
        }
    });
    $$('.motiv_noselect').each(function(el){
        if(el.title != ''){
    		new Tips('#'+el.id,{className: 'tooltip'});
        }
    });
*/
}

function getProductListByCategory(param)
{
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response)
		{
		   $('produkte_list').innerHTML = '';

		   response.each(function(el){

		       var a = document.createElement('a');
		       a.href = 'javascript:;';
		       a.id = 'productselector_'+el.id;
		       a.setAttribute('onclick','changeProduct('+el.id+');');

		       var img = document.createElement('img');
		       img.id = "products_"+el.id;
		       img.className = "products_tn";
		       img.title     = el.name;
		       img.height = 50;
		       img.width = 50;
		       img.src = pictures_products+el.fileName;

		       a.appendChild(img);
		       $('produkte_list').appendChild(a);

	       });
	       //now reset the tooltips
           myTips2 = new Tips('.products_tn',{className: 'tooltip'});


		}
	}).post({'functionName': 'getProductListByCategory', 'param': param});
}

function getEigeneMotivListe(param) {
	var request = new Request.HTML({
		url: ajaxBridge,
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			$('eigeneMotiv_list').set('html', responseHTML);
			addEigeneMotivDragEvents();
		}
	}).post({'functionName': 'getEigeneMotivListe', 'param': param});
}

function addMotiv(param, position) {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response) {
			if(response != false) {
				addMotivToPrintArea(response, position);
			}
		}
	}).post({'functionName': 'addMotiv', 'param': param});
}

function addUppedMotiv(param, position) {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response) {
			if(response != false) {
				addMotivToPrintArea(response, position);
			}
		}
	}).post({'functionName': 'addUppedMotiv', 'param': param});
}

function addTextMotiv(param, position) {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response) {
			if(response != false) {
				addMotivToPrintArea(response, position);
			}
		}
	}).post({'functionName': 'addTextMotiv', 'param': param});
}

function delMotiv() {
	var motiv = this.getParent();
	var request = new Request.HTML({
		url: ajaxBridge,
		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
			if(responseHTML == 1) {
				$('motivattribut_color').set('html', '');
				motiv.destroy();
				getPrice();
			}
		}
	}).post({'functionName': 'delMotiv', 'param': motiv.get('id')});
}

function getMotivState(param) {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response){
			setMotiveState(response);
		}
	}).post({'functionName': 'getMotivState', 'param': param});
}

function setMotivParam(MotivObjektId, param, value) {
	/**
	 *
	 * if we want to increase the image size, we have to check
	 * if the new dimensions fit into the printable region and
	 * only call the function if thats the case
	 * also there is a border-collision-detection for the rotations wich
	 * pretty much has the same effect
	 *
	 */
	if(param == 'rotation')
	{

		motiv = getActiveMotiv();
		rotation       = motiv.retrieve('rotation');
		faktor         = motiv.retrieve('faktor');
		width          = motiv.retrieve('originalWidth');
		height         = motiv.retrieve('originalHeight');

		//before we start with the math of the rotation, we have to calculate
		//the dimensions of the unrotated image and calc with these values

		//rotation normalisieren
		//damit wir nur mit positiven winkelzahlen rechnen
		//und innerhalb eines 90° winkels bleiben

		//achtung, bei rotation zwischen 90 und 180 sowie zwischen 270 und 360
		//(oder auch bei mehrfachen dieser -> modulo!!!)
		//grad m&uuml;ssen breite und h&ouml;he getauscht werden, da sonst bei der
		//winkelberechnung die falschen seiten zu grunde gelegt werden
		modRot = Math.abs(rotation + value) % 360;

		if((modRot >= 90 && modRot < 180)
		|| (modRot >= 270 && modRot < 360))
		{
			tmp    = width;
			width  = height;
			height = tmp;
		}
		normalizedRotation  = Math.abs(rotation + value) % 90;

		//laenge der diagonalen berechnen
		diagonale           = Math.sqrt((width * width) + (height * height));

		//aus der diagonalen k&ouml;nnen wir anhand des winkels die neue breite berechnen
		diagWinkelWidthRAD  = Math.acos(width / diagonale);
		diagWinkelWidthDEG  = diagWinkelWidthRAD * (180 / Math.PI);
		winkelBreite        = Math.abs(diagWinkelWidthDEG - normalizedRotation);
		cosBreite           = Math.cos(winkelBreite * (Math.PI / 180));
		neueBreite          = Math.abs(cosBreite * diagonale);

		//und natuerlich auch die neue hoehe.
		diagWinkelHeightRAD = Math.acos(height / diagonale);
		diagWinkelHeightDEG = diagWinkelHeightRAD * (180 / Math.PI);
		winkelHoehe         = Math.abs(diagWinkelHeightDEG - normalizedRotation);
		cosHoehe            = Math.cos(winkelHoehe * (Math.PI / 180));
		neueHoehe           = Math.abs(cosHoehe * diagonale);

		//die neuen maße anhand des faktors in shirtdesigner-maße umrechnen
		realWidth           = neueBreite * faktor;
		realHeight          = neueHoehe  * faktor;

		//wenn die neuen maße in die PrintRegion passen > anwenden
		if((realWidth < print_area.offsetWidth) && (realHeight < print_area.offsetHeight))
		{
			//store the new rotation
			motiv.store('rotation', rotation + value);
			//and call rotate function
			var request = new Request.JSON({
				url: ajaxBridge,
				onComplete: function(response) {
					reloadMotivImage(MotivObjektId,response);
					getMotivState(MotivObjektId);
				}
			}).post({'functionName': 'setMotivParam', 'MotivObjektId': MotivObjektId, 'param': param, 'value': value});
		}
	}
	else if(param == 'size' && (value == 'up' || value == 'moreup'))
	{
		motiv = getActiveMotiv();

		//retrieve current size information
		faktor         = motiv.retrieve('faktor');
		originalWidth  = motiv.retrieve('currentWidth');
		originalHeight = motiv.retrieve('currentHeight');


		//get the kind of resizement
		if(value == 'up'){
		    resizeByFaktor = 19;
		}else{
		    resizeByFaktor = 1;
		}

		//calcualate dimensions the image would have after resize
		newFaktor = faktor + (faktor / resizeByFaktor);
		newHeight = Math.floor(originalHeight / faktor * newFaktor);
		newWidth  = Math.floor(originalWidth / faktor * newFaktor);

		if(newHeight < print_area.offsetHeight
		&& newWidth < print_area.offsetWidth)
		//and if the new size fits into printable range
		{
			//call resize function
			var request = new Request.JSON({
				url: ajaxBridge,
				onComplete: function(response) {
					if(param == 'rotation' || param == 'size' || param == 'color'){
						reloadMotivImage(MotivObjektId,response);
						getMotivState(MotivObjektId);
					} else if(param == 'level') {
						reorderMotive(response);
					}

				}
			}).post({'functionName': 'setMotivParam', 'MotivObjektId': MotivObjektId, 'param': param, 'value': value});
		}
	}
	else
	{
		var request = new Request.JSON({
			url: ajaxBridge,
			onComplete: function(response) {
				if(param == 'rotation' || param == 'size' || param == 'color' || param == 'textColor' || param == 'font' || param == 'text'){
					reloadMotivImage(MotivObjektId,response);
					getMotivState(MotivObjektId);

				} else if(param == 'level') {
					reorderMotive(response);
				}

			}
		}).post({'functionName': 'setMotivParam', 'MotivObjektId': MotivObjektId, 'param': param, 'value': value});
	}
}

/* ------------- HELPER FUNCTIONS ------------- */

function addProductColorEvents() {
	$$('div#product-colors .product-color').addEvent('click', function(){
		setShirtColor(this.get('value'));
	});
}

function addMotivDragEvents() {
	$$('div#motive div.motiv_container').each(function(el){

		el.addEvent('click',function(element){
			$('print-area').highlight();
			addMotiv(el.getFirst('.motiv').get('id'), {'top': 0, 'left': 0});
		});
/*
this is the old event for adding motives to the printarea by drag and drop

		var motivdrag = new Drag.Move(el, {

		    droppables: 'div#print-area',

		    onDrop: function(element, droppable){
		        if (droppable) {
					$('print-area').highlight();
					addMotiv(element.get('id'), element.getCoordinates());
		        }
		        element.setStyles({'top': 0, 'left': 0});
		    }

		});
*/	});
}

function addEigeneMotivDragEvents() {
	$$('div#eigenemotive img.eigenesmotiv').each(function(el){

		el.addEvent('click',function(element){
			$('print-area').highlight();

			addUppedMotiv({'id':element.target.get('id'),'extension':element.target.get('name'),'isCustom':true,'success':true}, {'top': 0, 'left': 0});
		});
	});
}

function addMotivToPrintArea(response, position) {
	new_position_top = position.top - print_area.getCoordinates().top;
	new_position_left = position.left - print_area.getCoordinates().left;

		var motiv_container = new Element('div', {
			'id': response.id,
			'styles': {
				'top': new_position_top,
				'left': new_position_left,
				'visibility': 'hidden'
			},
			'events': {
				'mousedown': changeActiveMotiv
			}
		});
		var motiv = new Asset.image(imageOutput+'?motivObjektId='+response.id+'&'+$time()+'&type=png', {
			onload: function() {
				addMotivPrintAreaEvent(this, motiv_container);
				postloadiepngfix();
			}
		});

		var motiv_remove = new Element('div', {
			'html': 'x',
			'class': 'remove',
			'events': {
				'click': delMotiv
			}
		});

		changeActiveMotiv.run('', motiv_container);
		motiv_container.grab(motiv_remove);
		motiv_container.grab(motiv);
		print_area.grab(motiv_container);
}

function addMotivPrintAreaEvent(motiv, motiv_container) {
	var motivdrag = new Drag.Move(motiv_container, {
	    droppables: 'div#print-area',
	   	onDrop: function(element, droppable){
	       	if (droppable) {
				setMotivParam(element.get('id'), 'position', [element.getCoordinates().left, element.getCoordinates().top]);
	       	} else {
	       		window.removeEvents('mouseup');
	       	}
	   	},
	    onLeave: function(element, droppable){
	    	if(droppable){
	    		window.addEvent('mouseup', function(){
	    			setMotivParam(element.get('id'), 'position', [element.getCoordinates().left, element.getCoordinates().top]);
	    		});

	    	}
	    },
	    onEnter: function(element, droppable){
	    	//if(droppable){
	    		window.removeEvents('mouseup');
	    	//}
	    },
/*	    onDrag: function(element)
	    {
	        if(checkMotivCollisions(element) == true)
	        {
	            paCoords = $('print-area').getCoordinates();

	            element.setStyle('left',(lastleft - paCoords.left)+'px');
	            element.setStyle('top',(lasttop - paCoords.top)+'px');
	        }
	        else
	        {
	            //store the "last working position" for reset
	            lasttop =  element.getCoordinates().top;
	            lastleft = element.getCoordinates().left;


	        }
	    },
*/	   	limit: {'x': [0,print_area.getSize().x - motiv.getSize().x], 'y': [0,print_area.getSize().y - motiv.getSize().y]}
	});
	motiv_container.setStyle('visibility', 'visible');

	//check bounds
	if(motiv_container.offsetLeft < 0)
	{
		motiv_container.setStyle('left',0);
	}

	if(motiv_container.offsetTop < 0)
	{
		motiv_container.setStyle('top',0);
	}

	if(motiv_container.offsetLeft + motiv_container.offsetWidth > print_area.offsetWidth){
		motiv_container.setStyle('left',print_area.offsetWidth - motiv_container.offsetWidth);
	}

	if(motiv_container.offsetTop + motiv_container.offsetHeight > print_area.offsetHeight){
		motiv_container.setStyle('top',print_area.offsetHeight - motiv_container.offsetHeight);
	}
}

function checkMotivSize(element)
{
    result = false;
    //calculate the four corner-coordinates
    coords = $('print-area').getCoordinates();

    tl = {'x': coords.left,                 'y': coords.top };
    tr = {'x': coords.left + coords.width , 'y': coords.top };
    lr = {'x': coords.left + coords.width , 'y': coords.top + coords.height };
    ll = {'x': coords.left,                 'y': coords.top + coords.height };

    //check boundaries of region
    check = $(element).getCoordinates();

    if(check.top < tl.y || check.left < tl.x)
    {
        //top left out of bounds
        result = true;
    }

    if( check.width + check.left > tr.x
     || check.top < tr.y)
    {
        //topright corner
        result = true;
    }

    if( check.left + check.width > lr.x
     || check.top + check.height > lr.y)
    {
        //lower right
        result = true;
    }

    if( check.left < ll.x
     || check.top + check.height > ll.y)
    {
        //lower left
        result = true;
    }

    if(result == true)
    {
        //delete the motiv
    	var motiv = $(element);
    	var request = new Request.HTML({
    		url: ajaxBridge,
    		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
    			if(responseHTML == 1) {
    				$('motivattribut_color').set('html', '');
    				motiv.destroy();
    				getPrice();
    			}
    		}
    	}).post({'functionName': 'delMotiv', 'param': element});

    }


}

function checkMotivCollisions(element)
{
    //calculate the four corner-coordinates
    coords = $('print-area').getCoordinates();

    tl = {'x': coords.left,                 'y': coords.top };
    tr = {'x': coords.left + coords.width , 'y': coords.top };
    lr = {'x': coords.left + coords.width , 'y': coords.top + coords.height };
    ll = {'x': coords.left,                 'y': coords.top + coords.height };

    //check boundaries of region
    check = element.getCoordinates();

    if(check.top < tl.y || check.left < tl.x)
    {
        //top left out of bounds
        return true;
    }

    if( check.width + check.left > tr.x
     || check.top < tr.y)
    {
        //topright corner
        return true;
    }

    if( check.left + check.width > lr.x
     || check.top + check.height > lr.y)
    {
        //lower right
        return true;
    }

    if( check.left < ll.x
     || check.top + check.height > ll.y)
    {
        //lower left
        return true;
    }

    checkResult = false;

    $$('div#print-area img').each(
        function(el){
            if(el.className != 'remove' && el != element)
            {
                coords = el.getCoordinates();

                tl = {'x': coords.left,                 'y': coords.top };
                tr = {'x': coords.left + coords.width , 'y': coords.top };
                lr = {'x': coords.left + coords.width , 'y': coords.top + coords.height };
                ll = {'x': coords.left,                 'y': coords.top + coords.height };

                //now check if the bounds are somewhere in another element

                //check top left
                if(check.left > tl.x && check.left < tr.x
                 && check.top > tl.y && check.top < ll.y)
                {
                    checkResult = true;
                    return true;
                }

                //check top right
                if(check.left + check.width > tl.x && check.left + check.width < tr.x
                 && check.top > tl.y && check.top < ll.y)
                {
                    checkResult = true;
                    return true;
                }

                //check lower left
                if(check.left > ll.x && check.left < lr.x
                 && check.top + check.height > tl.y && check.top + check.height < ll.y)
                {
                    checkResult = true;
                    return true;
                }

                //check lower right
                if(check.left + check.width > ll.x && check.left + check.width < lr.x
                 && check.top + check.height < lr.y && check.top + check.height > tr.y)
                {
                    checkResult = true;
                    return true;
                }

            }
        }
    );

    return checkResult;
}


function reloadMotivPrintAreaEvent(motiv, motiv_container) {
	$(motiv_container).removeEvents();
	//check bounds
	if(motiv.offsetLeft < 0)
	{
		motiv.setStyle('left',0);
	}

	if(motiv.offsetTop < 0)
	{
		motiv.setStyle('top',0);
	}

	if(motiv.offsetLeft + motiv.offsetWidth > print_area.offsetWidth){
		motiv.setStyle('left',print_area.offsetWidth - motiv.offsetWidth);
	}

	if(motiv.offsetTop + motiv.offsetHeight > print_area.offsetHeight){
		motiv.setStyle('top',print_area.offsetHeight - motiv.offsetHeight);
	}
	$(motiv_container).addEvent('mousedown',changeActiveMotiv);
	var motivdrag = new Drag.Move(motiv_container, {
	    droppables: 'div#print-area',
	   	onDrop: function(element, droppable){
	       	if (droppable) {
				setMotivParam(element.get('id'), 'position', [element.getCoordinates().left, element.getCoordinates().top]);
	       	}
	   	},
	   	limit: {'x': [0,print_area.getSize().x - motiv.getSize().x], 'y': [0,print_area.getSize().y - motiv.getSize().y]}
	});
}

function changeActiveMotiv() {
	if(!this.hasClass('active')) {
		print_area.getChildren('div').removeClass('active');
		this.addClass('active');
		getMotivState(this.get('id'));
	}
}

function setMotiveState(response) {
	motiv = getActiveMotiv();
	if(response.rotation || (response.rotation == 0))
	{
		motiv.store('rotation',response.rotation);
	}
	if(response.faktor)
	{
		motiv.store('faktor',response.faktor);
	}
	if(response.width && motiv.retrieve('originalWidth') == null)
	{
		motiv.store('originalWidth', response.width);
	}

	if(response.height && motiv.retrieve('originalHeight') == null)
	{
		motiv.store('originalHeight',response.height);
	}
	if(response.width)
	{
		motiv.store('currentWidth', response.width);
	}

	if(response.height)
	{
		motiv.store('currentHeight',response.height);
	}
	//check bounds
	if(motiv.offsetLeft + motiv.offsetWidth > print_area.offsetWidth){
		motiv.setStyle('left',print_area.offsetWidth - motiv.offsetWidth);
	}

	if(motiv.offsetTop + motiv.offsetHeight > print_area.offsetHeight){
		motiv.setStyle('top',print_area.offsetHeight - motiv.offsetHeight);
	}

	$('motivattribut_color').set('html', response.colors);

//this was something with the collision detection > causes errors with new region and image models
//	if(response.width && response.height && response.faktor) {
//		motiv.getChildren('img').setStyles({'width': response.width*response.faktor, 'height': response.height*response.faktor});
//	}

	if(response.resizable == '1')
	{
    	$('motivattribut_size').style.display = 'block';
	}
	else
	{
    	$('motivattribut_size').style.display = 'none';
	}

	addMotivColorEvents();
}

function getActiveMotiv() {
	return $$('div#print-area div.active').getLast();
}

function getActiveMotivContainer() {
	return $$('div#print-area div.active');
}


function addMotivColorEvents() {
	$$('.motiv-color').addEvent('click', function() { setMotivParam(getActiveMotiv().get('id'), 'color', this.get('value')); });
	getPrice();
}

function rotateMotiv(id, direction) {
	var value = $('rotation_status').set('value');
	$('rotation_status').set('value');
	rotateMotiv(getActiveMotiv().get('id'), 'left')
}

function reorderMotive(list) {
	for(i=0; i < list.length; i++) {
		var id = list[i];
		var el = $(id);
		el.setStyle('z-index', 1000+i);
	}
}

function reloadMotivImage(MotivObjektId,response) {
	//$(MotivObjektId).getFirst('img').set('src', imageOutput+'?motivObjektId='+MotivObjektId+'&time='+$time());
	//var newMotivImage = new Element('img', { 'src': imageOutput+'?motivObjektId='+MotivObjektId+'&time='+$time() });
	//newMotivImage.cloneEvents($(MotivObjektId).getFirst('img'));
	//newMotivImage.replaces($(MotivObjektId).getFirst('img'));
	var motivRLD = new Asset.image(imageOutput+'?motivObjektId='+MotivObjektId+'&time='+$time()+'&type=png', {
		onload: function() {
			this.cloneEvents($(MotivObjektId).getFirst('img'));
			this.replaces($(MotivObjektId).getFirst('img'));
			postloadiepngfix();
			resetEvent();
		}
	});

	//set the new size-faktor and the original sizes
	motiv = getActiveMotiv();
	if(response.rotation)
	{
		motiv.store('rotation',response.rotation);
	}
	if(response.faktor)
	{
		motiv.store('faktor',response.faktor);
	}
	if(response.width)
	{
		motiv.store('currentWidth', response.width);
	}

	if(response.height)
	{
		motiv.store('currentHeight',response.height);
	}


	//check if out of x-bounds and move left if neccessary
	width  = Math.floor(response.width * response.faktor);

/*	if(($(MotivObjektId).offsetLeft + width) > $(print_area).getSize().x)
	{
		var pxToMoveLeft = $(MotivObjektId).offsetLeft + width - $(print_area).getSize().x;
		$(MotivObjektId).setStyle('left',$(MotivObjektId).offsetLeft - pxToMoveLeft);
	}

	//check if out of y-bounds and move up if neccessary
	height = Math.floor(response.height * response.faktor);
	if(($(MotivObjektId).offsetTop + height) > $(print_area).getSize().y)
	{
		var pxToMoveUp = $(MotivObjektId).offsetTop + height - $(print_area).getSize().y;
		$(MotivObjektId).setStyle('top',$(MotivObjektId).offsetTop - pxToMoveUp);
	}
*/	/*
	as you may have noticed, the top and left borders are not checked here
	but a overflow to the top or left is not possible, because prior to resize
	it is checked, if the new dimensions would fit into the printable space.
	*/


}

function initProduct(product) {

	productImage.set('src', pictureBase+'products/'+product.adresse);
	product_colors.set('html', product.colors);

	$('productSize').innerHTML = '';

    var item = document.createElement('option');
    item.value = -1;
    item.innerHTML = 'bitte w&auml;hlen';

    $('productSize').appendChild(item);


	product.sizes.each(function(el)
	{
	    item = document.createElement('option');
	    item.value = el.sizeId;
	    item.innerHTML = el.name;

	    $('productSize').appendChild(item);

	});
	var print_area_coords = {};
//	print_area_coords.top = productImage.getCoordinates().top+(product.printRegion.printRegionY1).toInt()+'px';
//	print_area_coords.left = productImage.getCoordinates().left+(product.printRegion.printRegionX1).toInt()+'px';
	print_area_coords.top = (product.printRegion.printRegionY1).toInt()+'px';
	print_area_coords.left = (product.printRegion.printRegionX1).toInt()+'px';
	print_area_coords.width = product.printRegion.printRegionX2+'px';
	print_area_coords.height = product.printRegion.printRegionY2+'px';

	print_area.setStyles({
		'top': print_area_coords.top,
		'left': print_area_coords.left,
		'width': print_area_coords.width,
		'height': print_area_coords.height
	});
}

function setRegion(region) {
	var print_area_coords = {};
//	print_area_coords.top = productImage.getCoordinates().top+(region.printRegionY1).toInt()+'px';
//	print_area_coords.left = productImage.getCoordinates().left+(region.printRegionX1).toInt()+'px';
	print_area_coords.top = (region.printRegionY1).toInt()+'px';
	print_area_coords.left = (region.printRegionX1).toInt()+'px';
	print_area_coords.width = region.printRegionX2+'px';
	print_area_coords.height = region.printRegionY2+'px';

	print_area.setStyles({
		'top': print_area_coords.top,
		'left': print_area_coords.left,
		'width': print_area_coords.width,
		'height': print_area_coords.height
	});
}


function resetDesigner() {
	print_area.empty();
	$('motivattribut_color').empty();
}

function resetEvent(){
	motiv = getActiveMotiv();
	reloadMotivPrintAreaEvent(motiv,motiv);
}

function reloadMotiveOnRegion()
{
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response){
		    response.each(
		        function(el){
                	var motivRLD = new Asset.image(imageOutput+'?motivObjektId='+el+'&time='+$time()+'&type=png', {
                		onload: function() {
                			this.cloneEvents($(el).getFirst('img'));
                			this.replaces($(el).getFirst('img'));
                			postloadiepngfix();
                			resetEvent();
                			checkMotivSize(el);
                		}
                	});
		        }
		    );
		}
	}).post({'functionName': 'getMotiveOnRegion'});

}

function setProductSize(sizeId)
{
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response){
            getMotivListe($('motivcategoryselector').value);
            reloadMotiveOnRegion();
		}
	}).post({'functionName': 'setProductSize','param':sizeId});
}

function addCustomMotiv(response)
{
	response = JSON.decode(response);

	if(response.success == true)
	{
		addUppedMotiv({'id':response.id,'extension':response.extension,'isCustom':true,'success':true}, {'top': 0, 'left': 0});
	}
	else
	{
		alert('Fehler beim hochladen der Datei.\nEs werden nur Bilder im JPG-Format unterstützt.');
	}

	document.getElementById('loader_imageUpload').style.display = 'none';
}

function getRegionList() {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response){
			$('region_list').innerHTML = response.html;
		}
	}).post({'functionName': 'getRegionList'});
}

function loadRegion(regionId)
{
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response){
			//clear printArea
			print_area.empty();
			//set product image
			productImage.set('src', pictureBase+'products/'+response.address);
			//and set the correspoinding region
			setRegion(response.region);
			//after we got the bounds, fill it
			if(response.content)
			{
				//fill the printarea with all the nifty objects we got
				for(i = 0 ; i < response.content.length ; i++)
				{
					reAddMotivToPrintArea(response.content[i]);
				}
				//fin
			}
            getMotivListe($('motivcategoryselector').value);

		}
	}).post({'functionName': 'loadRegion','param':regionId});
}

function reAddMotivToPrintArea(item) {
	new_position_top = item.posY - print_area.getCoordinates().top;
	new_position_left = item.posX - print_area.getCoordinates().left;
		var motiv_container = new Element('div', {
			'id': item.motivObjektId,
			'styles': {
				'top': new_position_top,
				'left': new_position_left,
				'visibility': 'hidden'
			},
			'events': {
				'mousedown': changeActiveMotiv
			}
		});
		var motiv = new Asset.image(imageOutput+'?motivObjektId='+item.motivObjektId+'&'+$time()+'&type=png', {
			onload: function() { addMotivPrintAreaEvent(this, motiv_container); postloadiepngfix(); }
		});

		var motiv_remove = new Element('div', {
			'html': 'x',
			'class': 'remove',
			'events': {
				'click': delMotiv
			}
		});

		changeActiveMotiv.run('', motiv_container);
		motiv_container.grab(motiv_remove);
		motiv_container.grab(motiv);
		print_area.grab(motiv_container);
}

function setTextColor(color)
{
    //first of all remove the "fontcolor_" from the colorId
    color = color.substring(10);

    motiv = getActiveMotiv();
    if(motiv != null)
    {
        //if we got a motiv active, set its color
        setMotivParam(motiv.get('id'), 'textColor', color);
    }

    //and also set the hidden field's color value
    $('fontColorSelect').value = color;

}

function setTextText(param)
{
    motiv = getActiveMotiv();

    if(motiv != null)
    {
        //if we got a motiv active, set its color
        setMotivParam(motiv.get('id'), 'text', param);
    }
}

function selectFont(item)
{
    $('fontMenuText').innerHTML = item.title;
    $('fontMenuText').title = item.getAttribute('value');

    motiv = getActiveMotiv();
    if(motiv != null)
    {
        //if we got a motiv active, set its color
        setMotivParam(motiv.get('id'), 'font', item.getAttribute('value'));
    }

}

function checkSubmission(count,size)
{


	document.getElementById('loader').style.display = 'block';
	
	if(getActiveMotiv()) {
	    failure = checkMotivCollisions(getActiveMotiv());
	    overlap = failure;
	} else {
		failure = true;
		overlap = false;
	}
	
    nosize = false;


    $$('div#print-area img').each(
        function(el){
            if(el.className != 'remove')
            {
                if(checkMotivCollisions(el) == true)
                {
                    failure = true;
                    overlap = true;
                };
            }
    });




    if(size == -1)
    {
        failure = true;
        nosize = true;
    }


    if(failure == true)
    {
        if(overlap == true)
        {
            alert('Ein oder mehrere Motive befinden sich ausserhalb des bedruckbaren Bereiches oder überschneiden sich. Bitte prüfen.');
        }
        else
        {
            if(nosize == true)
            {
                alert('Bitte wählen Sie eine Produktgröße');
            }
        }

        document.getElementById('loader').style.display = 'none';
    }
    else
    {
        document.location.href='addToCart.php?count='+count+'&size='+size;
    }
}


function getPrice() {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response) {
		    $('price').innerHTML = response.price;
		}
	}).post({'functionName': 'getPrice'});

}


function getFontColors() {
	var request = new Request.JSON({
		url: ajaxBridge,
		onComplete: function(response){

		    //clear textcolor-div content
		    $('fontColorList').innerHTML = '';
		    var initVeredelung = 0;

		    for(var i = 0; i < response.length ; i++)
		    {
		        if(response[i].veredelungsId != initVeredelung)
		        {
		            initVeredelung = response[i].veredelungsId;
		            head = document.createElement('div');
		            head.innerHTML = response[i].veredelungsName;
		            head.style.clear = 'left';
		            $('fontColorList').appendChild(head);
		        }


		        //create and append textcolor-selector-buttons
		        var fontColor = document.createElement('input');
		        fontColor.className     = 'font-color';
		        fontColor.type          = 'button';
		        fontColor.title         = response[i].name;
		        fontColor.id            = 'fontcolor_'+response[i].id;

		        fontColor.style.backgroundColor = '#'+response[i].code;
		        if(response[i].patternThumb != '')
		        {
		            fontColor.style.backgroundImage = 'url("_images/patterns/thumbs/'+response[i].patternThumb+'")';
		        }
		        

		        $('fontColorList').appendChild(fontColor);

		    }
        $$('.font-color').addEvent('click', function() {setTextColor(this.id) });

		}
	}).post({'functionName': 'getFontColors', 'param': null});
}



