/* base */
function $(element)
{
  if (arguments.length > 1)
  {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

function gotoForNavHor(link,level){
	if(actualLevel < level){
	actualLevel = level;
	document.location = link;
	}
}

function goto(link){
	document.location = link;
}

function getCookie(name, fuzzy)
{
	if(fuzzy == null)
	{
		fuzzy = false;
	}
	
	var cName, separator, cookies = document.cookie.split(';');
	for(var i = 0; i < cookies.length; i++)
	{
		separator = cookies[i].indexOf('=');
		cName = cookies[i].substr(0, separator);
		if(	(fuzzy && cName.indexOf(name) != -1)
			||(!fuzzy && cName == name)
		)
		{
			return cookies[i].substr(separator+1);
		}
	}
	return false;
}

//use browser sniffing to determine if IE or Opera (ugly, but required)
var isOpera, istIE = false;

if(typeof(window.opera) != 'undefined'){
	isOpera = true;
}

if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){
	istIE = true;
}

//fix both IE and Opera (adjust when they implement this method properly)
if(isOpera || istIE){
	document.nativeGetElementById = document.getElementById;
	//redefine it!1
	document.getElementById = function(id){
		var elem = document.nativeGetElementById(id);
		if(elem){
	    	//verify it is a valid match!
			if(elem.id == id){
				//valid match!
				return elem;
			} else {
				//not a valid match!
				//the non-standard, document.all array has keys for all name'd, and id'd elements
				//start at one, because we know the first match, is wrong!
				for(var i=1;i<document.all[id].length;i++){
					if(document.all[id][i].id == id){
						return document.all[id][i];
					}
				}
			}
		}
		return null;
	};
}

function switchSrc(elem, img){
	elem.src = img;
}

var atsynonym  = '.23.';  // für das @
var dotsynonym = '!_&_!'; // für Punkt

function decodeString(myEncStr) {
	var tmp;
	tmp = myEncStr.replace( eval("/" + atsynonym + "/"), '@');
	tmp = tmp.replace( eval("/" + dotsynonym + "/g"), '.');
	return(tmp);
}

function openLink(myEncStr) {
  var decStr	= decodeString(myEncStr);
  location.href = "mailto:" + decStr;
}

function printLink(myEncStr) {
  var decStr = decodeString(myEncStr);
  document.write( decStr );
}

function changeClassName(id, newclass){
	$(id).className = newclass;
}

/* preview stuff begin */

function toggleGlossyPreview()
{	
	if($('preview_glossy').style.display == 'inline')
	{
		$('preview_glossy').style.display = 'none';
		$('preview_glossy_button').style.border = '1px solid #503017';
	}
	else
	{	
		$('preview_glossy').style.left	= '0px';
		if(previewData['geoType'] == 'portrait')
		{
			if(previewData['showing'] == 'inner')
			{
				$('preview_glossy').style.top		= '16px';
				$('preview_glossy').style.left		= '3px';
				$('preview_glossy').src				= previewData['rootUrl'] + 'images/all/cat_preview/glossy-p-inner.png';
				$('preview_glossy').style.display	= 'inline';
			}
			else
			{
				$('preview_glossy').style.top		= '23px';
				$('preview_glossy').style.left		= '105px';
				$('preview_glossy').src				= previewData['rootUrl'] + 'images/all/cat_preview/glossy-p.png';
				$('preview_glossy').style.display	= 'inline';
			}
		}
		else if(previewData['geoType'] == 'squared')
		{
			if(previewData['showing'] == 'inner')
			{
				$('preview_glossy').style.top		= '15px';
				$('preview_glossy').style.left		= '0px';
				$('preview_glossy').src				= previewData['rootUrl'] + 'images/all/cat_preview/glossy-s-inner.png';
				$('preview_glossy').style.display	= 'inline';
			}
			else
			{	
				$('preview_glossy').style.top		= '23px';
				$('preview_glossy').style.left		= '17px';
				$('preview_glossy').src				= previewData['rootUrl'] + 'images/all/cat_preview/glossy-s.png';
				$('preview_glossy').style.display	= 'inline';
			}
		}
		else		//landscape
		{
			if(previewData['showing'] == 'inner')
			{
				$('preview_glossy').style.top		= '16px';
				$('preview_glossy').style.left		= '4px';
				$('preview_glossy').src				= previewData['rootUrl'] + 'images/all/cat_preview/glossy-l-inner.png';
				$('preview_glossy').style.display	= 'inline';
			}
			else
			{
				$('preview_glossy').style.top		= '16px';
				$('preview_glossy').style.left		= '4px';
				$('preview_glossy').src				= previewData['rootUrl'] + 'images/all/cat_preview/glossy-l.png';
				$('preview_glossy').style.display	= 'inline';
			}
		}
		
		$('preview_glossy_button').style.border = '2px solid #503017';
	}
}

function switchPreviewPic(toShow)
{
	resetPreviewWindow();
	$('preview_shadow_bottom1').style.left	= '0px';
	$('preview_shadow_bottom1').style.top	= '11px';
	switch(toShow)
	{
		case 'front'	:	if(previewData['geoType'] == 'portrait')
							{
								$('preview_fold_top').src			= previewData['rootUrl'] + 'images/all/cat_preview/fold-p.png';
								$('preview_big_1').src 				= '' + previewData['img_url'];
								$('preview_fold_top').style.display	= 'inline';
								$('preview_big_1').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_portrait';
								$('preview_shadow_bottom1').style.left	= '105px';
								$('preview_shadow_bottom1').style.top	= '439px';
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-side.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-bottom.png';
							}
							else if(previewData['geoType'] == 'squared')
							{
								$('preview_fold_top').src			= previewData['rootUrl'] + 'images/all/cat_preview/fold-s.png';
								$('preview_big_1').src 				= '' + previewData['img_url'];
								$('preview_fold_top').style.display	= 'inline';
								$('preview_big_1').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_squared';
								$('preview_shadow_bottom1').style.left			= '17px';
								$('preview_shadow_bottom1').style.top			= '439px';
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-side.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-bottom.png';
							}else
							{//landscape
								$('preview_big_1').src 				= '' + previewData['img_url'];
								$('preview_fold_side').style.display= 'inline';
								$('preview_big_1').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_landscape';
								
								$('preview_shadow_bottom1').style.left = '5px';
								$('preview_shadow_bottom1').style.top	= '315px';
	
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-side.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-bottom.png';
							}
							previewData['showing'] = 'front';
							$('preview_frontpage').style.border			= '1px solid #442801';
							$('preview_frontpage_text').style.color 	= '#442801';
							break;
							
		case 'inner'	:	$('preview_big_1').src				= '' + previewData['inner_url1_big'];
							$('preview_big_1').style.display	= 'inline';
							if(previewData['geoType'] == 'portrait')
							{
								$('preview_big_2').src				= '' + previewData['inner_url2_big'];
								$('preview_big_2').style.display	= 'inline';
								$('preview_big_container_inner').className = 'category_preview_big_container_inner_portrait_inlay';
								
								$('preview_shadow_bottom1').style.left = '3px';
								$('preview_shadow_bottom1').style.top	= '365px';
								
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-side-inner.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-bottom-inner.png';
							}
							else if(previewData['geoType'] == 'squared')
							{
								$('preview_big_2').src				= '' + previewData['inner_url2_big'];
								$('preview_big_2').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_squared_inlay';
								
								$('preview_shadow_bottom1').style.left = '0px';
								$('preview_shadow_bottom1').style.top	= '267px';
								
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-side-inner.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-bottom-inner.png';
							}
							else 
							{//landscape
								$('preview_big_3').src				= '' + previewData['inner_url2_big'];
								$('preview_big_3').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_landscape_inlay';
								
								$('preview_shadow_bottom1').style.top	= '518px';
								$('preview_shadow_bottom1').style.left	= '5px';
									
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-side-inner.png';
								$('preview_shadow_side2').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-side-inner.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-bottom-inner.png';
								$('preview_shadow_side2').style.display	= 'inline';
							}
							previewData['showing'] = 'inner';
							$('preview_innerpages').style.border = '1px solid #442801';
							$('preview_innerpages_text').style.color 	= '#442801';
							break;
							
		case 'back'		:	if(previewData['geoType'] == 'portrait')
							{
								$('preview_fold_top').src			= previewData['rootUrl'] + 'images/all/cat_preview/fold-p-back.png';
								$('preview_big_1').src 				= '' + previewData['back_url_big'];
								$('preview_fold_top').style.display	= 'inline';
								$('preview_big_1').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_portrait';
								$('preview_shadow_bottom1').style.left	= '105px';
								$('preview_shadow_bottom1').style.top	= '439px';
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-side.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-bottom.png';
							}
							else if(previewData['geoType'] == 'squared')
							{
								$('preview_fold_top').src			= previewData['rootUrl'] + 'images/all/cat_preview/fold-s-back.png';
								$('preview_big_1').src 				= '' + previewData['back_url_big'];
								$('preview_fold_top').style.display	= 'inline';
								$('preview_big_1').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_squared';
								$('preview_shadow_bottom1').style.left			= '17px';
								$('preview_shadow_bottom1').style.top			= '439px';
								
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-side.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-bottom.png';
							}
							else
							{//landscape
								$('preview_big_1').src 				= '' + previewData['back_url_big'];
								$('preview_fold_side').style.display= 'inline';
								$('preview_big_1').style.display	= 'inline';

								$('preview_big_container_inner').className = 'category_preview_big_container_inner_landscape';
								$('preview_shadow_bottom1').style.left = '5px';
								$('preview_shadow_bottom1').style.top	= '315px';
								
								$('preview_shadow_side1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-side.png';
								$('preview_shadow_bottom1').src		= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-bottom.png';
							}
							previewData['showing'] = 'back';
							$('preview_backpage').style.border 			= '1px solid #442801';
							$('preview_backpage_text').style.color 		= '#442801';
							break;
	}
	
	$('preview_shadow_side1').style.display		= 'inline';
	$('preview_shadow_bottom1').style.display	= 'inline';
	
	if($('preview_glossy').style.display == 'inline')
	{
		toggleGlossyPreview();
		toggleGlossyPreview();
	}
}

function openPreviewOld(title, img_url, link, card_type, card_size, designer)
{
	//change y position if its first displayed oder IE6
	if($("kategorie_vorschau").style.visibility != "visible" || IE)
	{
		if(IE && !isIE7 && !isIE8)
		{
			$("kategorie_vorschau").style.top = (tempY-250)+"px";
		}
	}
	$("kategorie_vorschau").style.visibility = "visible";
	$("kategorie_vorschau_header_headline").innerHTML = unescape(title);
	$("kategorie_vorschau_img").src = img_url;
	$("kategorie_vorschau_card_type").innerHTML = card_type;
	$("kategorie_vorschau_card_size").innerHTML = card_size;
	$("kategorie_vorschau_card_designer").innerHTML = designer;
	$("kategorie_vorschau_card_href_1").href = link;
	$("kategorie_vorschau_card_href_2").href = link;
}

function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

var r = getXmlHttpRequestObject();
var previewData			= new Array();
previewData['showing']	= 'front';

function requestPreview(id)
{	
	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		r.open("GET", '/ajx/getCatPreviewData.php?id=' + id, true);
		r.onreadystatechange = openPreview;
		r.send(null);
	}
}

function openPreview(title, img_url, link, front_url, inner_url1, inner_url1_big, inner_url2, inner_url2_big)
{
	//if all but the first var is not set, this method is called as callback for the ajax request
	if(img_url == null && link == null && front_url == null)
	{
		if(r.readyState == 4)
		{
			previewData = eval('('+r.responseText+')');
		}
		else return;
	}
	//if the vars are set, the user clicked on a related product (same card with other color)
	else
	{
		previewData['title']		= title;
		previewData['img_url']		= img_url;
		previewData['link']			= link;
		previewData['front_url']	= front_url;
		previewData['inner_url1']	= inner_url1;
		previewData['inner_url1_big']=inner_url1_big;
		previewData['inner_url2']	= inner_url2;
		previewData['inner_url2_big']=inner_url2_big;
	}

	if((previewData['productTypeID'] == '3')||(IE && !isIE7 && !isIE8))
	{
		openPreviewOld(previewData['title'], previewData['oldFrontUrl'], previewData['link'], previewData['geoType'], previewData['card_size'], '');
		return;
	}

	resetPreviewWindow();
	
	//change y position if its first displayed or IE6
	if($("category_preview").style.visibility != "visible" || IE)
	{
		if(IE && !isIE7 && !isIE8)
		{
			$("category_preview").style.top = (tempY-250)+"px";
		}
	}
	
	$("category_preview").style.visibility = "visible";
	$("category_preview_header_headline").innerHTML = unescape(previewData['title']);
	$("category_preview_card_size").innerHTML = previewData['card_size'];
	
	$('preview_frontpage').src	= previewData['front_url'];
	$('preview_backpage').src	= previewData['back_url'];
		
	if(previewData['geoType'] == 'portrait')
	{
		$('preview_fold_top').src			= previewData['rootUrl'] + 'images/all/cat_preview/fold-p.png';
		$('preview_big_1').src				= '' + previewData['img_url'];
		$('preview_fold_top').style.display = 'inline';
		$('preview_big_1').style.display	= 'inline';
		$('preview_innerpages').innerHTML 	= '<img src="' + previewData['inner_url1'] + '" style="cursor:pointer;" /><img src="' + previewData['inner_url2'] + '" style="cursor:pointer;" />';
		$('preview_big_container_inner').className = 'category_preview_big_container_inner_portrait';
		$('preview_innerpages').style.width	= '144px';
		$('preview_innerpages').style.height= '100px';
		$('preview_shadow_bottom1').style.left	= '105px';
		$('preview_shadow_bottom1').style.top	= '439px';
		$('preview_shadow_side1').src			= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-side.png';
		$('preview_shadow_bottom1').src			= previewData['rootUrl'] + 'images/all/cat_preview/shadow-p-bottom.png';
	}
	else if(previewData['geoType'] == 'squared')
	{
		$('preview_fold_top').src			= previewData['rootUrl'] + 'images/all/cat_preview/fold-s.png';
		$('preview_big_1').src				= '' + previewData['img_url'];
		$('preview_fold_top').style.display = 'inline';
		$('preview_big_1').style.display	= 'inline';
		$('preview_innerpages').innerHTML 	= '<img src="' + previewData['inner_url1'] + '" style="cursor:pointer;" /><img src="' + previewData['inner_url2'] + '" style="cursor:pointer;" />';
		$('preview_big_container_inner').className = 'category_preview_big_container_inner_squared';
		$('preview_innerpages').style.width	= '144px';
		$('preview_innerpages').style.height= '72px';
		$('preview_shadow_bottom1').style.left	= '17px';
		$('preview_shadow_bottom1').style.top	= '439px';
		$('preview_shadow_side1').src			= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-side.png';
		$('preview_shadow_bottom1').src			= previewData['rootUrl'] + 'images/all/cat_preview/shadow-s-bottom.png';
	}
	else	//must be landscape
	{
		$('preview_big_1').src				= '' + previewData['img_url'];
		$('preview_fold_side').style.display= 'inline';
		$('preview_big_1').style.display	= 'inline';
		$('preview_innerpages').innerHTML	= '<img src="' + previewData['inner_url1'] + '" style="cursor:pointer;" /><br/><img src="' + previewData['inner_url2'] + '" style="cursor:pointer;" />';
		//position and size main container
		$('preview_big_container_inner').className = 'category_preview_big_container_inner_landscape';
		//size innerpages
		$('preview_innerpages').style.width		= '100px';
		$('preview_innerpages').style.height	= '144px';
		// position shadows
		$('preview_shadow_bottom1').style.top	= '315px';
		$('preview_shadow_bottom1').style.left	= '5px';
		$('preview_shadow_side1').src			= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-side.png';
		$('preview_shadow_bottom1').src			= previewData['rootUrl'] + 'images/all/cat_preview/shadow-l-bottom.png';
	}
	
	$('preview_shadow_side1').style.display	= 'inline';
	$('preview_shadow_bottom1').style.display= 'inline';
	
	var related_products = previewData['related_products'];
	var innerToSet = '';
	for(var i = 0; i < related_products.length; i++)
	{
		var tTitle		= related_products[i].name;
		var tImgUrl		= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].files['big_little_text'];
		var tLink		= related_products[i].product_link;
		var tfUrl		= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].files['thumb_text_100'];
		
		if(!related_products[i].inlaysForPreview)
		{
			var geoSelector = (previewData['geoType'] == 'portrait' || previewData['geoType'] == 'squared') ? 'p' : 'l';
			var tI1Url		= previewData['rootUrl'] + 'images/all/cat_preview/blanko-' + geoSelector + '.gif';
			var tI1UrlBig	= previewData['rootUrl'] + 'images/all/cat_preview/blanko-' + geoSelector + '-big.gif';
			var tI2Url		= previewData['rootUrl'] + 'images/all/cat_preview/blanko-' + geoSelector + '.gif';
			var tI2UrlBig	= previewData['rootUrl'] + 'images/all/cat_preview/blanko-' + geoSelector + '-big.gif';
		}
		else
		{
			if((previewData['geoType'] == 'squared'))
			{
				var tI1Url		= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['left'].files['thumb_text_72'];
				var tI1UrlBig	= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['left'].files['medium_text_squared_ns'];
				var tI2Url		= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['right'].files['thumb_text_72'];
				var tI2UrlBig	= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['right'].files['medium_text_squared_ns'];
			}else
			{
				var tI1Url		= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['left'].files['thumb_text_100'];
				var tI1UrlBig	= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['left'].files['medium_text_ns'];
				var tI2Url		= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['right'].files['thumb_text_100'];
				var tI2UrlBig	= 'http://static-1.wunderkarten.de/live/cards/' + related_products[i].inlaysForPreview['right'].files['medium_text_ns'];
			}
		}
		
		var previewCall =	"openPreview('"+tTitle+"','"+tImgUrl+"','"+tLink+"','"+tfUrl+"','"+tI1Url+"','"+tI1UrlBig+"','"+tI2Url+"','"+tI2UrlBig+"');";
		innerToSet += '<span class="product_affine_chooser_button" onclick="'+previewCall+'" style="background-color:#'+related_products[i].color+'"></span>&nbsp;';
	}
	if(innerToSet == '')
	{
		//no related product, so disable the div
		$('preview_colorchooser_container_p').style.display = 'none';
	}
	else
	{
		$('preview_colorchooser_container').innerHTML = innerToSet;
		$('preview_colorchooser_container_p').style.display = 'block';
	}
	
	if($('preview_glossy').style.display == 'inline')
	{
		toggleGlossyPreview();
		toggleGlossyPreview();
	}
	
	if(previewData['link'].indexOf('http') != -1)
	{
		$('preview_commit').href = previewData['link'];
	}
	else
	{
		$('preview_commit').href = previewData['rootUrl'] + 'product/' + previewData['link'];
	}
	
	$('preview_frontpage').style.border	= '1px solid #442801';
	$('preview_innerpages').style.border= '1px solid transparent';
	$('preview_backpage').style.border	= '1px solid transparent';
	$('preview_frontpage_text').style.color 	= '#442801';
}

function resetPreviewWindow()
{
	$('preview_big_1').style.display		= 'none';
	$('preview_big_2').style.display		= 'none';
	$('preview_big_3').style.display		= 'none';
	$('preview_fold_top').style.display		= 'none';
	$('preview_fold_side').style.display	= 'none';
	$('preview_shadow_side1').style.display	= 'none';
	$('preview_shadow_side2').style.display	= 'none';
	$('preview_shadow_bottom1').style.display= 'none';
	$('preview_frontpage').style.border		= '1px solid transparent';
	$('preview_innerpages').style.border	= '1px solid transparent';
	$('preview_backpage').style.border		= '1px solid transparent';
	$('preview_frontpage_text').style.color = '#a08260';
	$('preview_innerpages_text').style.color= '#a08260';
	$('preview_backpage_text').style.color	= '#a08260';
}

function closePreviewOld()
{
	$("kategorie_vorschau").style.visibility = "";
}

function closePreview()
{
	if(IE && !isIE7 && !isIE8)
	{
		closePreviewOld();
		return;
	}
	
	$('preview_glossy').style.display 		= 'none';
	$('preview_glossy_button').style.border = '1px solid #503017';
	$('preview_glossy').src					= '';
	$('category_preview').style.visibility	= '';
}
/* preview stuff end */

/* ajax stuff */


//function to retrieve mouse x-y pos
//dont forget to set variables tempX, tempY and IE on the page
function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.documentElement.scrollLeft;
    tempY = event.clientY + document.documentElement.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0;}
  if (tempY < 0){tempY = 0;} 
  return true
}

function getMouseAbsoluteXY(e) {
  if (true) { // grab the x-y pos.s if browser is IE
  
    tempX = document.documentElement.scrollLeft;
    tempY = document.documentElement.scrollTop;
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0;}
  if (tempY < 0){tempY = 0;} 
  return true
}

/* forms submit */
function submitRegister(){
	document.user_register.submit();
	return false;
}

function passwordForgottenSubmit(){
	document.pwd_forgotten.submit();
	return false;
}

function productSubmit(){
	document.product.submit();
	return false;
}

function personalize_form_submit(){
	document.personalize.submit();
	return false;
}

function change_form_submit(action, frontDivWidth, inlayDivWidth)
{
	if(!inlayIsDisplayed && frontDivWidth && inlayDivWidth)
	{
		switchFrontAndInside(false , frontDivWidth, inlayDivWidth);
		return false;
	}
	
	if(!action)
	{
		document.change.submit();
	}
	else
	{
		$('action').value = action;
		document.change.submit();
	}
	return false;
}

function loadold_form_submit(action){
	if(!action){
		document.loadold.submit();
	}else{
		$('action').value = action;
		document.loadold.submit();
	}
	return false;
}

function narrowCardsSubmit(){
	document.selectCards.submit();
	return false;
}
function submitSampleSet(){
	document.sampleset.submit();
	return false;
}

function deleteSetFromShoppingCart(id){
	if(confirm("Dieses Set aus Ihrem Warenkorb entfernen ?")){
		$('cart_data_action').value 	= 'delete_set';
		$('delete_set_id').value 		= id;
		document.cart_data.submit();
	}
}

function updateShoppingCart(id, obj, addOpt, productTypeID)
{
	if(addOpt == null)
	{
		addOpt = 0;
	}
	
	if(productTypeID != null && (productTypeID == 1 || productTypeID == 2))
	{
		if($('glossyoptionbox_'+id).checked)
		{
			var myAjax = new Ajax.Request(
					'/ajx/getOptionPrice.php?prtid=' + productTypeID,
					{ method: 'get', onComplete: applyOptionPrice}
			);
			
			myAjax.uid = id;
			myAjax.applyTo	= 'Shoppingcart'
			
			return;
		}
	}
	
	var priceBefore = 0;
	var priceEnvelopeBefore = 0;
	var priceAdditionalEnvelopeBefore;
	var totalBefore;

	var percentage_reduction;
	var absolute_reduction;
	
	if("," == ".")
	{
		priceBefore						= parseFloat(cutPreCurrencyString(($('price_content_' + id).innerHTML).replace(/\,/,"")));
		if($('price_envelope_'+id)){
			priceEnvelopeBefore 		= parseFloat(cutPreCurrencyString(($('price_envelope_'+id).innerHTML).replace(/\,/,"")));
		}else{
			priceEnvelopeBefore			= 0;
		}	

		priceAdditionalEnvelopeBefore 	= parseFloat(cutPreCurrencyString(($('price_add_envelope_'+id).innerHTML).replace(/\,/,"")));
		totalBefore						= parseFloat(cutPreCurrencyString(($('total_content').innerHTML).replace(/\,/,"")));

		percentage_reduction			= parseFloat(cutPreCurrencyString(($('percentage_reduction').value).replace(/\,/,"")));
		absolute_reduction				= parseFloat(cutPreCurrencyString(($('absolute_reduction').value).replace(/\,/,"")));
		
	
	} else {
		priceBefore						= parseFloat(cutPreCurrencyString(($('price_content_' + id).innerHTML).replace(/\./,'').replace(/\,/,".")));
		if($('price_envelope_'+id)){
			priceEnvelopeBefore 		= parseFloat(cutPreCurrencyString(($('price_envelope_'+id).innerHTML.replace(/\./,'')).replace(/\,/,".")));
		}else{
			priceEnvelopeBefore			= 0;
		}	

		priceAdditionalEnvelopeBefore 	= parseFloat(cutPreCurrencyString(($('price_add_envelope_'+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
		totalBefore						= parseFloat(cutPreCurrencyString(($('total_content').innerHTML).replace(/\./,'').replace(/\,/,".")));

		percentage_reduction			= parseFloat(cutPreCurrencyString(($('percentage_reduction').value).replace(/\./,'').replace(/\,/,".")));
		absolute_reduction				= parseFloat(cutPreCurrencyString(($('absolute_reduction').value).replace(/\./,'').replace(/\,/,".")));
	}
	


	var singlePrice						= parseFloat(obj.value) + parseFloat(addOpt);

	var quantity 						= obj[obj.selectedIndex].innerHTML;
	
	var singlePriceString 				=  parseFloat(singlePrice/100).toFixed(2).toString().replace(/\./, ",") + " &euro;";

	var priceString						=  ((singlePrice * quantity /100).toFixed(2).toString()).replace(/\./,",") + " &euro;";
	
	$('single_price_content_' + id).innerHTML 	= singlePriceString;
	$('price_content_' + id).innerHTML 			= priceString;
	
	if($("envelope_quantity_" + id)){
		$("envelope_quantity_" + id).innerHTML 	= quantity;
	}
	
	var envelopeSinglePrice;
	var priceAdditionalEnvelopes;
	if("," == ".")
	{
		if($('single_price_envelope_'+id)){
			envelopeSinglePrice				= parseFloat(cutPreCurrencyString(($('single_price_envelope_'+id).innerHTML).replace(/\,/,"")));
		}else{
			envelopeSinglePrice				= 0;	
		}
		priceAdditionalEnvelopes 			= parseFloat(cutPreCurrencyString(($("price_add_envelope_"+id).innerHTML).replace(/\,/,"")));
	} else {
		if($('single_price_envelope_'+id)){
			envelopeSinglePrice				= parseFloat(cutPreCurrencyString(($('single_price_envelope_'+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
		}else{
			envelopeSinglePrice				= 0;	
		}	
		priceAdditionalEnvelopes 			= parseFloat(cutPreCurrencyString(($("price_add_envelope_"+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
	}
	
	if($("price_envelope_"+id)){
		$("price_envelope_"+id).innerHTML 		=  parseFloat(envelopeSinglePrice*quantity).toFixed(2).toString().replace(/\./, ",") + " &euro;";
	}
	
	
	var priceDelta 							= (priceBefore*100) - (singlePrice * quantity) 
												- (envelopeSinglePrice * 100 * quantity ) 
												- (priceAdditionalEnvelopes * 100) 
												+ (priceEnvelopeBefore *100) 
												+ (priceAdditionalEnvelopeBefore * 100);
		 
	var total						= (totalBefore*100 - priceDelta)/100;
	
	var voucherTotalContent			= total - (total * (1 - percentage_reduction/100));
	if (absolute_reduction != 0){
		voucherTotalContent = (absolute_reduction/100);
	}
	 
	var totalInkVoucher				= total - voucherTotalContent;
	
	var mwst						= (totalInkVoucher / 119) * 19;
	var mwstString					=  mwst.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var totalString					=  total.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var totalInkVoucherString		=  totalInkVoucher.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var voucherTotalContentString	= "-" +  voucherTotalContent.toFixed(2).toString().replace(/\./, ",") + " &euro;";

	
	if($('voucher_total_content')){
		$('voucher_total_content').innerHTML = voucherTotalContentString;
	}
	if ($('mwst_content')){
		$('mwst_content').innerHTML = mwstString;
	}
	if($('total_content')){
		$('total_content').innerHTML = totalString;
	}
	if($('total_content_ink_voucher') && (percentage_reduction != 0 || absolute_reduction != 0)){
		$('total_content_ink_voucher').innerHTML = totalInkVoucherString;
	}
	$("quantity_" + id).value = quantity;
}

function setEnvelopeQuantityInSC(id, obj){
	
	var envelope_add_quantity;
	var totalBefore;
	var addPriceBefore;
	var single_add_price;
	var percentage_reduction;
	var absolute_reduction;

	if("," == ".")
	{
		envelope_add_quantity 			= obj.value;
		totalBefore						= parseFloat(cutPreCurrencyString(($('total_content').innerHTML).replace(/\,/,"")));
		addPriceBefore					= parseFloat(cutPreCurrencyString(($("price_add_envelope_"+id).innerHTML).replace(/\,/,"")));
		single_add_price 				= parseFloat(cutPreCurrencyString(($('single_price_add_envelope_'+id).innerHTML).replace(/\,/,"")));
		percentage_reduction			= parseFloat(cutPreCurrencyString(($('percentage_reduction').value).replace(/\,/,"")));
		absolute_reduction				= parseFloat(cutPreCurrencyString(($('absolute_reduction').value).replace(/\,/,"")));
	} else {
		envelope_add_quantity 			= obj.value;
		totalBefore						= parseFloat(cutPreCurrencyString(($('total_content').innerHTML).replace(/\./,'').replace(/\,/,".")));
		addPriceBefore					= parseFloat(cutPreCurrencyString(($("price_add_envelope_"+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
		single_add_price 				= parseFloat(cutPreCurrencyString(($('single_price_add_envelope_'+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
		percentage_reduction			= parseFloat(cutPreCurrencyString(($('percentage_reduction').value).replace(/\./,'').replace(/\,/,".")));
		absolute_reduction				= parseFloat(cutPreCurrencyString(($('absolute_reduction').value).replace(/\./,'').replace(/\,/,".")));	
	}
	$("price_add_envelope_"+id).innerHTML =  parseFloat(single_add_price*envelope_add_quantity).toFixed(2).toString().replace(/\./, ",") + " &euro;";
	$("envelope_add_quantity_"+id).value = envelope_add_quantity;
	
	var total				= totalBefore - addPriceBefore + (single_add_price*envelope_add_quantity);
	
	var voucherTotalContent	= total - (total * (1 - percentage_reduction/100));
	if (absolute_reduction != 0){
		voucherTotalContent = (absolute_reduction/100);
	}
	
	var totalInkVoucher		= total - voucherTotalContent;
	
	var mwst				= (totalInkVoucher / 119) * 19;
	
	var mwstString			=  mwst.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var totalString			=  total.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var totalInkVoucherString		=  totalInkVoucher.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var voucherTotalContentString	= "-" +  voucherTotalContent.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	
	if($('voucher_total_content')){
		$('voucher_total_content').innerHTML = voucherTotalContentString;
	}
	$('mwst_content').innerHTML = mwstString;
	$('total_content').innerHTML = totalString;
	if($('total_content_ink_voucher') && (percentage_reduction != 0 || absolute_reduction != 0)){
		$('total_content_ink_voucher').innerHTML = totalInkVoucherString;
	}
}

function submitShoppingCart()
{
	document.getElementById('cart_data_action').value 	= 'save_cart';
	document.cart_data.submit();
}

function submitShoppingAddress(){
	document.address_data.submit();
}

function submitShoppingPayment(){
	document.payment_data.submit();
}

function askToConfirm(id){
	
	if (rConfirm.readyState == 4 || rConfirm.readyState == 0) {
		rConfirm.open("GET", '/ajx/ajx_shopping_confirm.php?id=' + id, true);
		rConfirm.onreadystatechange = submitShoppingConfirm;
		rConfirm.send(null);
	}
}

function submitShoppingConfirm(){
	if(rConfirm.readyState == 4 && rConfirm.responseText == 'free')
	{
		$('ajx_notice').innerHTML 	= '';
		document.payment_data.submit();
	}else if(rConfirm.readyState == 4 && rConfirm.responseText == 'blocked')
	{
		$('ajx_notice').innerHTML 	= 'Ihre Bestellung wird bereits verarbeitet. Sie erhalten in K&uuml;rze eine E-Mail.';
	}
}

function submitMyAccountShoppingAddress(){
	document.user_address.submit();
}

function deleteSet(id){
	if(confirm('Möchten Sie dieses Kartenset wirklich löschen?')){
		$('set_data_action').value 	= 'delete_set';
		$('delete_set_id').value 		= id;
		document.my_order.submit();
	}
}

function copySet(id){
	$('set_data_action').value 	= 'copy_set';
	$('copy_set_id').value 		= id;
	document.my_order.submit();
}

function submitEnvelope(){
	document.envelope.submit();
}
/* admin form submit */
function submitSeoProducts(action,card_id,page_id){
	$('hidden_action').value 	= action;
	$('card_id').value 			= card_id;
	$('page_id').value 			= page_id;
	document.update_category_seo.submit();
	return false;
}


/* nav_hor */
/* begin new nav_hor stuff */

/*
//this we need if old navi is deleted
var timeOutID = new Array();
var timeOutElem = new Array();
var oldFatherID;
*/
function createNavHorHTML(htmlContent){
	var navigationContainer 		= $('nav_hor_container');
	navigationContainer.innerHTML = htmlContent;
}

function createNavHorLinking(id,link){

	var navigationItem 		= $(id);
	navigationItem.onclick	= function(e) {goto(link);return false};
}

function createNavHorDisplay(parentId,chilId){
	var navigationParentItem 			= $(parentId);
	navigationParentItem.onmouseover	= function(e) {displayNavHorItem(chilId,true);return false};
	navigationParentItem.onmouseout		= function(e) {displayNavHorItem(chilId,false);return false};
}

function createNavHorHover(itemId)
{
	var navigationItem 			= $(itemId);
	navigationItem.onmouseover	= function(e) {changeHorNavBackground(navigationItem,true);return false};
	navigationItem.onmouseout	= function(e) {changeHorNavBackground(navigationItem,false);return false};
}

function displayNavHorItem(chilId,show){
	var navigationChildItem 			= $(chilId);
	if(show)
	{
		if(oldFatherID == chilId)
		{
			window.clearTimeout(timeOutID[chilId]);
		}
		navigationChildItem.style.display = 'block';
	}else
	{
		var tempElem = timeOutElem.pop();
		if(tempElem != navigationChildItem)
		{
			timeOutElem.push(tempElem);
			timeOutElem.push(navigationChildItem);
		}else{
			timeOutElem.push(navigationChildItem);
		}
		oldFatherID = chilId;
		timeOutID[chilId] = window.setTimeout('unDisplayNavElem()', 50);
	}
}

function changeHorNavBackground(elem, hover)
{
	if(hover)
	{
		elem.className = elem.className+'_hover';
	}else
	{
		var oldClassName = elem.className;
		elem.className = oldClassName.substring(0,oldClassName.length-6);
	}
}
/* end new nav_hor stuff */

/* begin old nav_hor stuff delete after testing */
var actualLevel = 0;

function changeNavBackground(elem){
	elem.className = 'nav_hor_sub_li_hover';
}

function changeBackNavBackground(elem){
	elem.className = 'nav_hor_sub_li';
}

function createNavHorUl(){
	var father 		= $('nav_hor_container');
	var ul			= document.createElement("ul");

	ul.id			= "nav_hor_ul";
	ul.className 	= "link";
	if(father){
		father.appendChild(ul);
	}
}

function appendNavHorFirstLayer(index, path){
	var father 	= $('nav_hor_ul');
	var li		= document.createElement("li");

	li.className 	= "nav_hor_li nav_hor_"+ index +"_a"; 
	li.onclick	= function(e) {gotoForNavHor(path,1);return false};
	li.id		= "nav_hor_" + index;
	
	if(father){
		father.appendChild(li);
	}
	return li;
}

var timeOutID = new Array();
var timeOutElem = new Array();
var oldFatherID;

function createNavHorUlSub(elem){
	var father 		= elem;
	var ul			= document.createElement("ul");
	
	ul.className 	= "nav_hor_sub_ul";

	if(father)
	{
		ul.id = father.id + 'sub';
	
		$(father.id).onmouseover = 
					function(e)
					{
						if(oldFatherID == father.id)
						{
							window.clearTimeout(timeOutID[father.id]);
						}
						ul.style.display = 'block';
					};
		$(father.id).onmouseout = 
					function(e)
					{
						var tempElem = timeOutElem.pop();
						if(tempElem != ul)
						{
							timeOutElem.push(tempElem);
							timeOutElem.push(ul);
						}
						else
						{
							timeOutElem.push(tempElem);
						}
						
						oldFatherID = father.id;
						timeOutID[father.id] = window.setTimeout('unDisplayNavElem()', 50);
					};
		
		father.appendChild(ul);
	}
	return ul;
}

function unDisplayNavElem()
{
	timeOutElem.pop().style.display = 'none';
}

function appendNavHorSecondLayer(elem, path, text){
	var father 	= elem;
	var li		= document.createElement("li");
 
	li.className 	= "nav_hor_sub_li"; 
	li.onmouseover	= function(e) {changeNavBackground(this);};
	li.onmouseout	= function(e) {changeBackNavBackground(this);};	
	li.onclick		= function(e) {gotoForNavHor(path,2); return false;};	
	li = appendNavHorSpan(li, path, text);
	if(father)
	{
		father.appendChild(li);
	}
	
}

function appendNavHorSpan(elem, path, text){
	var span		= document.createElement("span");
	span.className 	= "nav_hor_sub"; 
	span.onclick	= function(e) {goto(path); return false;};	
	span.appendChild(document.createTextNode(text));
	elem.appendChild(span);
	return elem;
}
/* end old nav_hor stuff delete after testing */

/* start ajax site search */

function prepareSearch(){
	var obj = $('header_search_input');
	if (obj.value == 'Suchbegriff eingeben' || obj.value == 'enter search') obj.value = '';
	obj.className = "text";
}


function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

var searchReq = getXmlHttpRequestObject();
var imageReq = getXmlHttpRequestObject();		
var country_id_save;
var fromSC_save;

var r = getXmlHttpRequestObject();
var r2 = getXmlHttpRequestObject();
var rConfirm = getXmlHttpRequestObject();

function getPostage(card_count, card_type, product_type, country_id){
	fromSC_save = true;	
	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		r.open("GET", '/ajx/get_postage.php?card_count=' + card_count + '&card_type=' + card_type + '&product_type=' + product_type + '&country_id=' + country_id, true);
		r.onreadystatechange = displayNewPostage; 
		r.send(null);
	}	
}

function getPostageFromSCByCountryId(country_id){
	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		r.open("GET", '/ajx/get_postage.php?country_id=' + country_id, true);
		r.onreadystatechange = displayNewPostage; 
		r.send(null);
	}	
}

function getPostageFromSCByCountryIdAndShippingType(country_id, fromSC){
	shippingType = 'standard';
	fromSC_save = fromSC;
	country_id_save = country_id;
	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		r.open("GET", '/ajx/get_postage.php?country_id=' + country_id_save + '&shippingtype=' + shippingType, true);
		r.onreadystatechange = displayNewPostage; 
		r.send(null);
	}	
}

function displayNewPostage(){
	if (r.readyState == 4) {
		$('postage_price').innerHTML =  (r.responseText / 100).toFixed(2).replace(/\./, ",") + " EUR";
		shippingType = 'express';
		if (!fromSC_save && (searchReq.readyState == 4 || searchReq.readyState == 0)) {
			r2.open("GET", '/ajx/get_postage.php?country_id=' + country_id_save + '&shippingtype=' + shippingType, true);
			r2.onreadystatechange = displayNewExpressPostage; 
			r2.send(null);
		}
	}	
}

function displayNewExpressPostage(){
	if (r2.readyState == 4) {
		$('premium_postage_price').innerHTML =  (r2.responseText / 100).toFixed(2).replace(/\./, ",") + " EUR";
	}
}

var change1 = getXmlHttpRequestObject();
var change2 = getXmlHttpRequestObject();

function loadChangeJsAndExecuteOnElems(uid, posInArray, i_id, i2_id)
{
    var url_string =  "/js/change_170.js";
    jQuery.getScript(url_string, function(){
	executeChangeJsOnHtmlElements(uid, posInArray, i_id, i2_id);
    });
}

var searchRequest = getXmlHttpRequestObject();
var searchResArr =  new Array();
var newHighlighted=-1;
var manualSearchText = '';

function showExampleSearch(e,text,url) {
	$('search_suggest_wrapper').style.visibility = 'visible';
	var isUpdownArrowKey=true;
	var unicode=e.keyCode? e.keyCode : e.charCode;
	var hasSearchEntry = (text!="")?true:false;
	switch(unicode){
	case 40: 
		if(hasSearchEntry){
			if($('search_suggest').innerHTML == ''){
				manualSearchText = text; isUpdownArrowKey=false;
			}else{
				changeMarkedListentryInSearch(true,text);
			}
		}
		break;//arrow-down
	case 38: 
		if(hasSearchEntry){
			if($('search_suggest').innerHTML == ''){
				manualSearchText = text; isUpdownArrowKey=false;
			}else{
				changeMarkedListentryInSearch(false,text);
			}
		}
		break;//arrow-down
	default: manualSearchText = text; isUpdownArrowKey=false; break;//others
	}
	if (!isUpdownArrowKey && (searchReq.readyState == 4 || searchReq.readyState == 0)) 
	{
		while(searchResArr.length!=0){
			searchResArr.pop();
		}
		var str = escape(text);
		searchReq.open("GET", url + 'ajx/example_search.php?search=' + str, true);
		searchReq.onreadystatechange = showExampleSearches; 
		searchReq.send(null);
	}
}

//event fired when ajx-search returns
function showExampleSearches() {
	if (searchReq.readyState == 4) {
		var ss = $('search_suggest');
		ss.innerHTML = '';
		var str = searchReq.responseText.split("_separator_!_");
		for(i=0; i < str.length - 1; i++) {
			if (str[i] && str[i] != "" && str[i] != " "){
				var result = (unescape((str[i]))).replace(/\+/g, " ");
				var suggest = '<div onmouseover="javascript: suggestOver(this);" ';
				suggest += 'onmouseout="javascript:suggestOut(this);" ';
				suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
				suggest += (i==0) ? 'class="suggest_link_over">' + result + '</div>' : 'class="suggest_link">' + result + '</div>';
//				ss.innerHTML += suggest;
				searchResArr[i] = suggest;
			}
		}
		for(var i = 0; i < searchResArr.length; i++){
			ss.innerHTML += searchResArr[i];
		}
	}
}

//Mouse over function
function suggestOver(div_value) {
	div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
	div_value.className = 'suggest_link';
}

function changeMarkedListentryInSearch(next,text){
	var pattern1 =  'suggest_link_over';
	var oldHighlighted = -1;
	for(var i = 0; i < searchResArr.length; i++){
		var erg = searchResArr[i].match(pattern1);
		if("suggest_link_over" == erg){oldHighlighted = i;}
	}
	if(oldHighlighted > -1){
		if(next){ //40 - down
			if(oldHighlighted+1 <= searchResArr.length-1){
				var repString1 = searchResArr[oldHighlighted+1];
				searchResArr[oldHighlighted+1] = repString1.replace(/suggest_link/,'suggest_link_over');
				var repString2 = searchResArr[oldHighlighted]
				searchResArr[oldHighlighted] = repString2.replace(/suggest_link_over/,'suggest_link');
				var testing = searchResArr[oldHighlighted+1];
				testing=testing.replace(/<div onmouseover="javascript: suggestOver\(this\);" onmouseout="javascript:suggestOut\(this\);" onclick="javascript:setSearch\(this.innerHTML\);" class="suggest_link_over">/g,'');
				testing=testing.replace(/<\/div>/g,'');
				$('header_search_input').value = testing;
			}else{
				while(searchResArr.length!=0){
					searchResArr.pop();
				}
				setSearch(manualSearchText);
				return;
			}
		}else{ //38 - up
			if(oldHighlighted-1 >= 0){
				var repString1 = searchResArr[oldHighlighted-1];
				searchResArr[oldHighlighted-1] = repString1.replace(/suggest_link/,'suggest_link_over');
				var repString2 = searchResArr[oldHighlighted]
				searchResArr[oldHighlighted] = repString2.replace(/suggest_link_over/,'suggest_link');
				var testing = searchResArr[oldHighlighted-1];
				testing=testing.replace(/<div onmouseover="javascript: suggestOver\(this\);" onmouseout="javascript:suggestOut\(this\);" onclick="javascript:setSearch\(this.innerHTML\);" class="suggest_link_over">/g,'');
				testing=testing.replace(/<\/div>/g,'');
				$('header_search_input').value = testing;
			}else{
				while(searchResArr.length!=0){
					searchResArr.pop();
				}
				setSearch(manualSearchText);
				return;
			}
		}
		$('search_suggest').innerHTML = '';
		for(var i = 0; i < searchResArr.length; i++){
			$('search_suggest').innerHTML += searchResArr[i];
		}
	}
}

//Click function
function setSearch(value) {
	$('header_search_input').value = value;
	$('search_suggest').innerHTML = '';
	$('search_suggest_wrapper').style.visibility = 'hidden';
	
}

/* end ajax site search */


/* narrow search */
function openSearch(obj, element){
	obj.className = (obj.className == 'selection_vert_minus') ? 'selection_vert_plus' : 'selection_vert_minus';
	$(element).style.display = ( $(element).style.display == 'none') ? '' : 'none';
	
}

/* start home teaser */
var switchAllowed = true;
var oldId = 0;
var chosenId = 0;
var automatikSwitch = null;
var counter = 0; 
var lastSwitchByClick = false;

var automatikSwitchCounter = 0; //ja mit k

function automaticSwitcher(timeSec)
{
	if(!firstCall)
	{
		switchmenu("slide_right");
	} else {
		oldId = teaserArray[0];
	}
	firstCall = false;
	automatikSwitch = window.setTimeout("automaticSwitcher(5)",5000);
}

function switchmenu(side)
{
	if(switchAllowed)
	{
		switchAllowed = false;
		for(var i=0;i<teaserArray.length;i++)
		{
			if(teaserArray[i] == oldId)
			{
				if(side == "left"){
					window.clearTimeout(automatikSwitch);
					lastSwitchByClick = true;
					if(i-1 < 0){
						showHomeTeaser(teaserArray[teaserArray.length-1]);
					}else{			
						showHomeTeaser(teaserArray[i-1]);
					}
				}else if(side == "right"){
					window.clearTimeout(automatikSwitch);
					lastSwitchByClick = true;
					if(i+1 > teaserArray.length-1){
						showHomeTeaser(teaserArray[0]);
					}else{
						showHomeTeaser(teaserArray[i+1]);
					}
				} else {
					lastSwitchByClick = false;
					if(i+1 > teaserArray.length-1){
						showHomeTeaser(teaserArray[0]);
					}else{
						showHomeTeaser(teaserArray[i+1]);
					}
					window.clearTimeout(automatikSwitch);
				}
			}		
		}
	}	
}

function showHomeTeaser(id)
{	
	if(oldId != id){
		chosenId = id;
		fadeImages(2);
	}
}

function fadeImages(speed)
{
	if(counter+speed >100)
	{
		counter = 100;
	}else{	
		counter = counter+speed;
	}
	if(isIE)
	{
		//IE opacity
		document.getElementById("teaser"+chosenId).style.filter = "Alpha(opacity="+counter+")";
		document.getElementById("teaser"+oldId).style.filter = "Alpha(opacity="+(100 - counter)+")";
	}else{
		//FF opacity
		document.getElementById("teaser"+chosenId).style.opacity = (1/100 * counter);
		document.getElementById("teaser"+oldId).style.opacity = (1/100 * (100 - counter));
	}
	if(counter <100)
	{ 
		window.setTimeout("fadeImages("+speed+")", 10);
	}else{
		counter=0; 
		document.getElementById("teaser"+chosenId).style.zIndex = 1;
		document.getElementById("teaser"+oldId).style.zIndex = 0;
		oldId = chosenId;
		switchAllowed = true;
		window.clearTimeout(automatikSwitch);
		if(lastSwitchByClick)
		{
			automatikSwitch = window.setTimeout("automaticSwitcher(5)",10000);
		} else {
			automatikSwitch = window.setTimeout("automaticSwitcher(5)",5000);
		}
	}

}

/* externen  actionscriptfunktion */
function thisMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

/* product.tpl page */

function openCalculateShipping(){
	if( $('product_calculate_shipping').style.display == '' ){
		$('product_calculate_shipping').style.display = 'none';
		$('product_calculate_shipping_text').innerHTML = 'berechnen';
	}else{
		$('product_calculate_shipping').style.display = '';
		$('product_calculate_shipping_text').innerHTML = 'schließen';
	}
}

function getCardType(){
	var c_value = 0;
	for (var i=0; i < document.product.card_type.length; i++){
	   if (document.product.card_type[i].checked){
			c_value = c_value + parseInt(document.product.card_type[i].value);
		}
	}
	return c_value;	
}

function getCountryId(){
	return document.product.shipping_country_id.value;
}

function getCardVolume(card_type)
{
	var c_value = 0;
	c_value =  $('quantity_'+card_type).value;
	return c_value;	
}

function showProductBoxFoto(){
	$('product_details_box_product').style.display = 'none';
	$('product_details_box_product_tab').className = 'product_details_box_tab';
	$('product_details_box_photo').style.display = '';
	$('product_details_box_photo_tab').className = 'product_details_box_tab product_details_box_tab_highlight';
}

function showProductBoxProduct(){
	$('product_details_box_product').style.display = '';
	$('product_details_box_product_tab').className = 'product_details_box_tab product_details_box_tab_highlight';
	$('product_details_box_photo').style.display = 'none';
	$('product_details_box_photo_tab').className = 'product_details_box_tab';
}

/* change.tpl */
var isIE = false;

// is reset in change.tpl
var isIEScrollX = 0;
var isIEScrollY = 0;


// An welchem Fotocontainer arbeiten wir gerade (um es später den Postfields zuzuordnen)
var imageFieldId	= 0; 

//Das Objekt, das gerade bewegt wird.
var dragobjekt = null;

// Position, an der das Objekt angeklickt wurde.
var dragx = 0;
var dragy = 0;

// Mausposition
var posx = 0;
var posy = 0;

// originale Objektposition
var image = new Array();

var obx = 0;
var oby = 0;

var hold 			= false;
var isMove 			= false;
var isNormalMove  	= false;

var width = 0;
var height = 0;
var rotate = 0;

var savedWidth = 0;

var origWidth  	= 0;
var origHeight 	= 0;

var savedImageArray = new Array();;

// Zahl, um die gezoomt wurde
var factor 		= 0;

// Seitenverhältnis
var ratio		= 0;

var mode = 'standard';

// active size-list and color select for text-fields -> style information
var activeList 	= new Array();
var activeColor = new Array();

// active size-list and color select for text-fields -> image information 
var textTop			= new Array();
var textLeft			= new Array();
var textWidth			= new Array();
var textHeight			= new Array();
var textSize			= new Array();
var textFont			= new Array();
var textColor 			= new Array();
var textOrient 			= new Array();
var textVerticalOrient		= new Array();
var textText 			= new Array();
var textFrontSide 		= new Array();
var textId			= new Array();
var textMouseFocus		= -1;

var pickedPic = false;
var pickedPicHr = false;

// id for auto placing image after upload
var photoUploadImageFieldId = false;

var newBackground = false;
var newBackgroundImg = false;

var holdX = 0;
var holdY = 0;

//array um die ursprungsqualitäten der bilder zu speichern
var qualityArray = new Array();

//array for saving textfieldactions - originally in change.js --> lost info on preview
var currentTextfieldValuesWithId = [];
//array for saving imagefieldactions - originally in change.js --> lost info on preview
var currentImagefieldValuesWithId = [];

function draginit() {
	document.onmousemove = drag;
	document.onmouseup = dragstop;
}

function dragstart(element) {
	pickedPic = element.style.background;
	dragobjekt = element;
	obx = dragobjekt.style.left;
	oby = dragobjekt.style.top;
	dragx = posx - dragobjekt.offsetLeft;
	dragy = posy - dragobjekt.offsetTop;
}

function movestart(element) {
	dragobjekt = element;
	isMove = true;
	dragx = posx - dragobjekt.offsetLeft;
	dragy = posy - dragobjekt.offsetTop;
}

function normalMove(element){
	dragobjekt   = element;
	isNormalMove = true;
	dragx = posx - dragobjekt.offsetLeft;
	dragy = posy - dragobjekt.offsetTop;
}

function dragstop() {
	if (isNormalMove){
		dragobjekt   = null;
		isNormalMove = false;
	}else if (isMove){
		image["image_field_"+imageFieldId]["holdX"] = posx;
		image["image_field_"+imageFieldId]["holdY"] = posy;
		dragobjekt	= null;
		isMove 		= false;
	} else {
		if(dragobjekt != null){
			dragobjekt.style.left = obx;
			dragobjekt.style.top = oby;
			hold = true;
			setTimeout ( "hold = false;", 500 ); 
			dragobjekt=null;
		}
	}
	isMove 		= false;
	isNormalMove = false;
}


function drag(ereignis) { 
	
	posx = document.all ? window.event.clientX : ereignis.pageX;
	posy = document.all ? window.event.clientY : ereignis.pageY;

	if(dragobjekt != null) {
		prevx = posx - dragx;
		prevy = posy - dragy;
		dragobjekt.style.left = (posx - dragx) + "px";
 		dragobjekt.style.top = (posy - dragy) + "px";
 		if(isMove){
 			$('photo_edit_photo_img').style.left = (posx - dragx) + "px";
 			$('photo_edit_photo_img').style.top = (posy - dragy) + "px";
 		}
	}else{
		if(isIE){
			isIEScrollX = document.documentElement.scrollLeft;
			isIEScrollY = document.documentElement.scrollTop;
		}
		if (textMouseFocus != -1){
			hideBorder(textMouseFocus);
		}
		textMouseFocus = -1;
		for (var i = 0; i < textTop.length; i++){
			if (posy + isIEScrollY > textTop[i] && posx + isIEScrollX > textLeft[i] && posy + isIEScrollY < (textTop[i] + textHeight[i]) && posx + isIEScrollX < (textLeft[i] + textWidth[i]) && frontSide == textFrontSide[i]){
				displayBorder(i);
				textMouseFocus = i;

				//document.body.style.cursor = "pointer";
				break;
			}
		}
		if (textMouseFocus == -1){
			//document.body.style.cursor = "";
		}
	}
}

function displayBorder(id){
	if($("image_text_field_"+id) && $("image_text_field_"+id).className != "change_box_text_field_red"){
			$("image_text_field_"+id).className ="change_box_text_field_solid";
	}
}

function hideBorder(id){
	if($("image_text_field_"+id) && $("image_text_field_"+id).className != "change_box_text_field_red"){
		if(showHelp){
			$("image_text_field_"+id).className ="change_box_text_field_grey";
		} else {
			$("image_text_field_"+id).className ="change_box_text_field";
		}
	}
}

function displayImageBorder(id){
	$("image_field_"+id).style.border = "solid 1px #736F6E";
}

function hideImageBorder(id){
	$("image_field_"+id).style.border = "0px";
}

function openTextEdit(id){

	resetYPosition($("text_field_"+id), 250, true);
	closeChangeTextboxWarning();
	if (id != -1){
		$("text_field_"+id).style.visibility = "visible";
		$("photo_upload_background").style.visibility = "visible";
		return false;
	}
}

function resetYPosition(elem, disposition, everyBrowser){
	//change y position if its first displayed oder IE6
	if(elem && (elem.style.visibility != "visible" || IE || everyBrowser))
	{
		if(everyBrowser || IE){
			if(everyBrowser || !isIE7){
				elem.style.top = (tempY+disposition)+"px";
			}
		}
	}
}


function closeTextEdit(id){
	$("text_field_"+id).style.visibility = "hidden";
	$("photo_upload_background").style.visibility = "hidden";
	return false;
}

function selectFirstList(elem, id){
	var element 	= "font_size_" + id + "_"+ elem;

	activeList[id] 	= element;
	$(element).style.display = "";
}

function changeTextSizeListIE6(elem, id){
	if(activeList[id]){
		$(activeList[id]).style.display = "none";
	}
	
	var element 	= "font_size_" + id + "_" + elem.value;
	$(element).style.display = "";
	activeList[id] 	= element;
	textFont[id]	= elem.value;
	textSize[id]	= $(element).value;
}

function changeTextSizeList(elem, id, newClassName)
{
	if(activeList[id]){
		$(activeList[id]).style.display = "none";
	}
	
	var element 	= "font_size_" + id + "_" + elem;
	$(element).style.display = "";
	activeList[id] 	= element;
	textFont[id]	= elem;
	textSize[id]	= $(element).value;
	
	/* show selected font by setting font selectors css-class */
	document.getElementById("fnt_selector_"+id).className = newClassName;
	
	/* close dropdown */
	document.getElementById("fnt_selector_sub_"+id).style.visibility = "hidden";
}

function showFontDropdown(id)
{
	document.getElementById("fnt_selector_sub_"+id).style.visibility = "visible";
}

function selectTextColor(text_field_id, color) {
	if(activeColor[text_field_id]){
		$(activeColor[text_field_id]).style.border = "solid 1px #736F6E";
	}	
	
	var id 						= "color_" + text_field_id + "_" + color;
	var elem 					= $(id);
	
	elem.style.border 			= "solid 2px #000000";
	activeColor[text_field_id] 	= id;
	textColor[text_field_id] 	= color;
}

function selectTextSize(elem, id) {
	textSize[id] = elem.value;
}

function changeOrientation(id, orient, elem){
	$("orientation_" + id + '_left').src = "/images/buttons/orient_left.gif";
	$("orientation_" + id + '_center').src = "/images/buttons/orient_center.gif";
	$("orientation_" + id + '_right').src = "/images/buttons/orient_right.gif";
	switch (orient){
		case 'left':
			$("orientation_" + id + '_left').src = "/images/buttons/orient_left_pressed.gif";
			$("image_text_form_field_" + id + "_orient").value = 'left';
			textOrient[id] = 'left';
			break;
		case 'center':
			$("orientation_" + id + '_center').src = "/images/buttons/orient_center_pressed.gif";
			$("image_text_form_field_" + id + "_orient").value = 'center';
			textOrient[id] = 'center';
			break;
		case 'right':
			$("orientation_" + id + '_right').src = "/images/buttons/orient_right_pressed.gif";
			$("image_text_form_field_" + id + "_orient").value = 'right';
			textOrient[id] = 'right';
			break;
		default:
			break;	
	}
}

function applyTextChange(id,displayFactor){

	if (textColor[id] == ''){
		textColor[id] = 'ffffff';
	}
	var field = 'image_text_field_' + id;
	var text  = $('text_field_area_'+id).value;
	text 	  = escape(text);
	if (isIE){
		text 	  = escape(text);
	}
	custom	  = Math.round(textWidth[id]);//*displayFactor);
	custom 	 += "/" + Math.round(textHeight[id]);//*displayFactor);
	custom 	 += "/72";
	custom 	 += "/" + textFont[id];
	custom 	 += "/" + Math.round(parseFloat(textSize[id])*displayFactor*pixelFactor);
	custom 	 += "/" + textColor[id];
	custom 	 += "/" + textOrient[id];
	custom 	 += "/" + textVerticalOrient[id];
	custom 	 += "/" + text;
	
	textText[id] = text;

	requestTextBoxImageData(field,custom);

	/* now save values for subsequent post */
	$("image_text_form_field_" + id + "_font").value = textFont[id];
	$("image_text_form_field_" + id + "_size").value = Math.round(parseFloat(textSize[id]));
	$("image_text_form_field_" + id + "_color").value = textColor[id];
	if (isIE){
		text = unescape(text);
	}
	$("image_text_form_field_" + id + "_text").value = unescape(text);
		
	closeTextEdit(id);
	return false;
}


function requestTextBoxImageData(field,custom)
{
	
	//start request for check
	if (imageReq.readyState == 4 || imageReq.readyState == 0) {
		imageReq.open("GET", '/photoeditor/createtext.php?args=1/' + custom, true);
		imageReq.onreadystatechange = new Function('fx', 'setTextBoxImageData("'+field+'")');
		imageReq.send(null);
	}

if (isIE)
	{

		var _IEBackground  	= "/photoeditor/createtext.php?args=0/" + custom + ".png";

		set_ie_background(field, _IEBackground);
	}
	else
	{
		var _background	 	= "url('/photoeditor/createtext.php?args=0/" + custom + ".png') no-repeat";

		$(field).style.background = _background;
	}
}

function setTextBoxImageData(field)
{
	if (imageReq.readyState == 4) 
	{
		if($('outside_div').style.display == 'block')
		{
			if(imageReq.responseText == 'bad')
			{
				var posLeft = $(field).style.left;
				posLeft.replace(/px/, "");
				var posLeftInt = parseInt(posLeft);
				$('change_textbox_warning_outside').style.left = (posLeftInt - 330) + "px";
				$('change_textbox_warning_outside').style.top = $(field).style.top;
				$('change_textbox_warning_outside').style.display = 'block';
				showTextWarning(true, field);
			}else
			{
				showTextWarning(false, field);
			}
		}else
		{
			if(imageReq.responseText == 'bad')
			{
				var posLeft = $(field).style.left;
				posLeft.replace(/px/, "");
				var posLeftInt = parseInt(posLeft);
				$('change_textbox_warning_inside').style.left = (posLeftInt - 330) + "px";
				$('change_textbox_warning_inside').style.top = $(field).style.top;
				$('change_textbox_warning_inside').style.display = 'block';
				showTextWarning(true, field);
			}else
			{
				showTextWarning(false, field);
			}
		}
	}
}

function showTextWarning(show, field)
{
	if(show)
	{
		$(field).className = "change_box_text_field_red";
		$('warning_'+field).style.display = "block";
	}else
	{
		if(showHelp)
		{
			$(field).className = "change_box_text_field_grey";
			$('warning_'+field).style.display = "none";
		}else
		{
			$(field).className = "change_box_text_field";
			$('warning_'+field).style.display = "none";
		}
	}
}

function closeChangeTextboxWarning()
{
	if($('change_textbox_warning_inside'))
	{
		$('change_textbox_warning_inside').style.display = 'none';
	}
	if($('change_textbox_warning_outside'))
	{
		$('change_textbox_warning_outside').style.display = 'none';
	}
}

function moveChangeTextboxWarning()
{
	if($('change_textbox_warning_inside').style.display == 'block')
	{
		normalMove($('change_textbox_warning_inside'));
	}else
	{
		normalMove($('change_textbox_warning_outside'));
	}
}

function openPhotoEdit(elem){
	mydisplayFactor=0;

	if(!inlayIsDisplayed){
		mydisplayFactor = displayFactor;
	} else {
		mydisplayFactor = inlayDisplayFactor;
	}
	var photoChanged = false;

	elem = $(elem);
	
	if(image[elem.id] == null){
		image[elem.id] = initImageArray(elem.id);
	}
	if(!image[elem.id]["newBackgroundImg"]){
		openPhotoUpload(elem.id);return false;
	}
	
	//check for dropped image
	resetYPosition($("photo_edit"), 100, true);
	$("photo_edit").style.visibility 		= "visible";
	$("photo_upload_background").style.visibility = "visible";
	savedImageArray = saveImageArray(image[elem.id]);
	
	$("photo_edit_photo_img").src 		= image[elem.id]["newBackgroundImg"];
	
	var elemWidth 	= elem.style.width.replace(/px/, "");
	var elemWidthInt = parseInt(elemWidth);
	var elemHeight 	= elem.style.height.replace(/px/, "");
	var elemHeightInt = parseInt(elemHeight);
	$("photo_edit_photo_img").style.width 	= Math.round(parseFloat(image[elem.id]["width"])*mydisplayFactor) + "px";
	$("photo_edit_photo_img").style.height	= Math.round(parseFloat(image[elem.id]["height"])*mydisplayFactor)+ "px";//image[elem.id]["savedWidth"] == 0 ? elem.style.height : Math.round(parseInt(image[elem.id]["savedWidth"]) * image[elem.id]["ratio"]);
	$("photo_edit_photo_img").style.left 	= Math.round(parseFloat(image[elem.id]["holdX"])*mydisplayFactor) + "px";
	$("photo_edit_photo_img").style.top 	= Math.round(parseFloat(image[elem.id]["holdY"])*mydisplayFactor) + "px";
	
	$("photo_edit_photo").style.width 		= Math.round(parseFloat(image[elem.id]["width"])*mydisplayFactor) + "px";
	$("photo_edit_photo").style.height 		= Math.round(parseFloat(image[elem.id]["height"])*mydisplayFactor)+ "px";
	$("photo_edit_photo").style.left 		= Math.round(parseFloat(image[elem.id]["holdX"])*mydisplayFactor) + "px";
	$("photo_edit_photo").style.top 		= Math.round(parseFloat(image[elem.id]["holdY"])*mydisplayFactor) + "px";
  	 
	if(((Math.round(parseFloat(image[elem.id]["width"])*mydisplayFactor) + Math.round(parseFloat(image[elem.id]["holdX"])*mydisplayFactor) ) <0 ) || 
	   ((Math.round(parseFloat(image[elem.id]["height"])*mydisplayFactor) + Math.round(parseFloat(image[elem.id]["holdY"])*mydisplayFactor) ) <0 ))
	{
		$("photo_edit_photo_img").style.left 		= 0 + "px";
		$("photo_edit_photo_img").style.top 		= 0 + "px";
		$("photo_edit_photo").style.left 		= 0 + "px";
		$("photo_edit_photo").style.top 		= 0 + "px";
	} 

	$("photo_edit_photo_container").style.width 	= Math.round(parseFloat(elem.style.width)) + "px";
	$("photo_edit_photo_container").style.height 	= Math.round(parseFloat(elem.style.height)) + "px";
	
	imageFieldId= elem.id.replace(/image_field_/, "");
	origWidth  	= elem.style.width.replace(/px/, "");
	origHeight 	= elem.style.height.replace(/px/, "");
	origWidth	= parseInt(origWidth);
	origHeight	= parseInt(origHeight);
	
	image[elem.id]["ratio"]		= origHeight / origWidth;
		
	return false;
}

function closePhotoEdit(){
	$("photo_edit").style.visibility = "hidden";
	$("photo_upload_background").style.visibility = "hidden";
	image["image_field_"+imageFieldId] = saveImageArray(savedImageArray);	
	return false;
}

function openPhotoUpload(id){
	resetYPosition($("photo_upload"), 250, true);
	$("photo_upload").style.visibility = "visible";
	$("photo_upload_background").style.visibility = "visible";
	photoUploadImageFieldId = id;
	return false;
}

function uploadFotoAutomatic(id){
	setPhotoUploadRefresh(id);
	document.photo_upload_form.submit();
}

function closePhotoUpload(){
	$("photo_upload").style.visibility = "hidden";
	$("photo_upload_background").style.visibility = "hidden";
	setPhotoUploadRefresh('');
	return false;
}

function applyPhotoUpload(itemwidth, itemheight){
	$("photo_upload").style.visibility = "hidden";
	$("photo_upload_background").style.visibility = "hidden";
	
	/* prepare for auto-set image */ 	
	var uploaded 	= parseInt($("count_uploaded").value);
	var element		= $("photo_upload_output_area_" + uploaded);
	if(element){
		pickedPic = element.style.background;
		photoUploadImageFieldId = photoUploadImageFieldId.replace(/image_field_/, "");
		hold = true;
	
		isElementDropped(photoUploadImageFieldId,itemwidth, itemheight);
	}
	setPhotoUploadRefresh('');
	
	return false;
}

function setPhotoUploadRefresh(id){
	top.document.getElementById('upload_meter_iframe').src 				= "/photoeditor/upload_meter.php?upload_id=" + id;
	top.document.getElementById('upload_meter_update_iframe').src 		= "/photoeditor/upload_meter_update.php?upload_id=" + id;
}

function styleEditor()
{
	if(top.document.getElementById("count_uploaded").value == "0")
	{
		top.document.getElementById("trUpload1").style.visibility = "visible";
		top.document.getElementById("trUpload2").style.visibility = "hidden";
		top.document.getElementById("trUpload3").style.visibility = "hidden";
				
		top.document.getElementById("trUpload1").style.display = "block";
		top.document.getElementById("trUpload2").style.display = "none";
		top.document.getElementById("trUpload3").style.display = "none";
		
	}else{
		top.document.getElementById("trUpload3").style.visibility = "visible";
		top.document.getElementById("trUpload2").style.visibility = "visible";
		top.document.getElementById("trUpload1").style.visibility = "hidden";
		top.document.getElementById("trUpload3").style.display = "block";
		top.document.getElementById("trUpload2").style.display = "block";
		top.document.getElementById("trUpload1").style.display = "none";
	}
	
}

var userimagesDir = '';
function setUserimagesDir(toSet)
{
	userimagesDir = toSet;
}

function createPhotoDiv(name, width, height){
	
	var uploaded = parseInt(top.document.getElementById("count_uploaded").value) + 1 ;
	
	top.document.getElementById("change_box_photo_collection_" + uploaded + "_text").style.display = "block";
	
	// creating innerHTML for change.tpl "uploaded photos"-section
	var hiddenOut 				= document.createElement("div");
		hiddenOut.style.position 	= "absolute";
		hiddenOut.style.visibility 	= "hidden";
		hiddenOut.id 			= "hidden_" + name;
		hiddenOut.style.width 		= width + "px";
		hiddenOut.style.height 		= height + "px";

	var out					= top.document.getElementById("change_box_photo_collection_" + uploaded);
		out.style.background		= 'url(/photoeditor/getPhoto.php?fn=thumb_'+name+') no-repeat';
		out.innerHTML 			= hiddenOut.innerHTML; //no appendChild because of IE
		
	var hiddenProperty1 			= top.document.createElement('input');
		hiddenProperty1.type 		= "hidden";
		hiddenProperty1.id 		= hiddenOut.id + "_width";
		hiddenProperty1.value 		= hiddenOut.style.width;
	var hiddenProperty2 			= top.document.createElement('input');
		hiddenProperty2.type 		= "hidden";
		hiddenProperty2.id 		= hiddenOut.id + "_height";
		hiddenProperty2.value 		= hiddenOut.style.height;
	
	top.document.getElementById("photo_upload_form").appendChild(hiddenProperty1);
	top.document.getElementById("photo_upload_form").appendChild(hiddenProperty2);

	// creating innerHTML for change_upload_photos.tpl "uploaded photos"-section	
	var out1				= top.document.getElementById("photo_upload_output_area_" + uploaded);
		out1.style.background		= 'url(/photoeditor/getPhoto.php?fn=thumb_'+name+') no-repeat';

	var out3 				= top.document.getElementById("photo_upload_delete_" + uploaded);
		out3.innerHTML 			= "<a href='#'>Bild<br\/>l&ouml;schen<\/a>";
	
	top.document.getElementById("photo_upload_border_area_" + uploaded).style.backgroundColor 	= "#ffffff";
	top.document.getElementById("photo_upload_border_area_" + uploaded).style.borderWidth 		= "1px";
	
	// save to post for writing in session
	top.document.getElementById("hidden_change_box_photo_collection_name_" + uploaded).value 	= name;
	top.document.getElementById("hidden_change_box_photo_collection_width_" + uploaded).value 	= width;
	top.document.getElementById("hidden_change_box_photo_collection_height_" + uploaded).value 	= height;
	
	setPhotoUploadRefresh('stop_refresh');
	
	top.document.getElementById("count_uploaded").value = uploaded;
	styleEditor();
}
	

function isElementDropped(id, itemwidth, itemheight){
	var elem = document.getElementById("image_field_"+id);
	if (hold && pickedPic){
		if(image[elem.id] == null){
			image[elem.id] = initImageArray(elem.id);
		}
		image[elem.id]["mode"] = 'standard';
		image[elem.id]["rotate"] = 0; 
		
		image[elem.id]["pickedPicHr"] = pickedPic.replace(/.*thumb_(.*)\).*/, "$1");
		image[elem.id]["pickedPicHr"] =image[elem.id]["pickedPicHr"].replace(/"/,"");

		var widthString = "hidden_"+image[elem.id]["pickedPicHr"]+"_width";	

		var heightString = "hidden_"+image[elem.id]["pickedPicHr"]+"_height";	 
		var myimg = image[elem.id]["pickedPicHr"];
		widthString  = widthString.replace(/"/,"");
		heightString  = heightString.replace(/"/,"");
		myimg = myimg.replace(/"/,"");
	
		image[elem.id]["width"] = top.document.getElementById(widthString).value;
		image[elem.id]["height"] = top.document.getElementById(heightString).value;
				
		var swidth = parseFloat(top.document.getElementById(widthString).value)  * displayFactor;
		var sheight = parseFloat(top.document.getElementById(heightString).value)  * displayFactor;
		
		newBackground = "url(/photoeditor/createphoto.php?args=";
		newBackground += swidth;
		newBackground += "/";
		newBackground += sheight;
		newBackground += "/0/0/0/" + mode + "/";
		newBackground += myimg;
		newBackground += ") no-repeat";
		image[elem.id]["newBackground"] = newBackground;
		newBackgroundImg = "/photoeditor/createphoto.php?args=";
		newBackgroundImg += parseFloat(top.document.getElementById(widthString).value) * displayFactor;
		newBackgroundImg += "/";
		newBackgroundImg += parseFloat(top.document.getElementById(heightString).value) * displayFactor;
		newBackgroundImg += "/0/0/" + image[elem.id]["rotate"] + "/" + image[elem.id]["mode"] + "/";
		newBackgroundImg += myimg;
		newBackgroundImg += "";
		image[elem.id]["newBackgroundImg"] = newBackgroundImg;
		elem.style.background = image[elem.id]["newBackground"];
		
		/* display the edit photo button when user hovers */
		$('image_field_edit_button_' + id).style.background = "url('/images/buttons/bearbeiten.gif') no-repeat";
		
		/* now save values for subsequent post */
		$("image_form_field_" + id + "_width").value = parseFloat(top.document.getElementById(widthString).value);
		$("image_form_field_" + id + "_height").value = parseFloat(top.document.getElementById(heightString).value);
		$("image_form_field_" + id + "_top").value = 0;
		$("image_form_field_" + id + "_left").value = 0;
		$("image_form_field_" + id + "_rotation").value = 0;
		$("image_form_field_" + id + "_mode").value = "standard";
		$("image_form_field_" + id + "_zoomFactor").value = 0;
		$("image_form_field_" + id + "_name").value = myimg;
		
		hold = false;
		$("fotofeldText_" + id).style.visibility = "hidden";
		
		//bildqualität berechnen und ampel anzeigen
		getImageQuality(swidth,sheight,myimg, id, itemwidth, itemheight);
	}
}
var inlayIsDisplayed = false;

function applyPhotoEdit(itemwidth, itemheight){
	mydisplayFactor=0;

	if(!inlayIsDisplayed){
		mydisplayFactor = displayFactor;
	} else {
		mydisplayFactor = inlayDisplayFactor;
	}
	var obj 	= $("photo_edit_photo");
	var objImg 	= $("photo_edit_photo_img");
	var target 	= $("image_field_"+imageFieldId);
	image["image_field_"+imageFieldId]["holdX"] 		= parseFloat(obj.style.left) / mydisplayFactor;
	image["image_field_"+imageFieldId]["holdY"] 		= parseFloat(obj.style.top) / mydisplayFactor;
	image["image_field_"+imageFieldId]["height"] 		= parseFloat(obj.style.height) / mydisplayFactor;
	image["image_field_"+imageFieldId]["width"]			= parseFloat(obj.style.width) / mydisplayFactor;
	var first 	= objImg.style.width;
	var second 	= objImg.style.height;
/*	if (image[target.id]["rotate"] % 360 == 90 || image[target.id]["rotate"] % 360 == 270){
		first 	= objImg.style.height;
		second 	= objImg.style.width;
	}*/
	
	var myimg = image[target.id]["pickedPicHr"];
	myimg = myimg.replace(/"/,"");	
	
	newBackground = "url(/photoeditor/createphoto.php?args=";
	newBackground += first;
	newBackground += "/";
	newBackground += second;
	newBackground += "/";
	newBackground += obj.style.left;
	newBackground += "/";
	newBackground += obj.style.top;
	newBackground += "/" + image[target.id]["rotate"] + "/";
	newBackground += image[target.id]["mode"] + "/";
	newBackground += myimg;
	newBackground += ") no-repeat";
	image[target.id]["newBackground"] = newBackground;
	
	target.style.background = image[target.id]["newBackground"];
	
		
	//savedWidth = objImg.style.width;
	//image[target.id]["savedWidth"] = savedWidth;
	
	var myimg = image[target.id]["pickedPicHr"];
	myimg = myimg.replace(/"/,'');
			
	/* now save values for subsequent post */
	$("image_form_field_" + imageFieldId + "_width").value = parseFloat(first) / mydisplayFactor;
	$("image_form_field_" + imageFieldId + "_height").value = parseFloat(second) / mydisplayFactor;
	$("image_form_field_" + imageFieldId + "_top").value = parseFloat(obj.style.top) / mydisplayFactor;
	$("image_form_field_" + imageFieldId + "_left").value = parseFloat(obj.style.left) / mydisplayFactor;
	$("image_form_field_" + imageFieldId + "_rotation").value = image[target.id]["rotate"];
	$("image_form_field_" + imageFieldId + "_mode").value = image[target.id]["mode"];
	$("image_form_field_" + imageFieldId + "_zoomFactor").value = image[target.id]["zoomFactor"];
	$("image_form_field_" + imageFieldId + "_name").value = myimg;
	
	savedImageArray = saveImageArray(image[target.id]);
	closePhotoEdit();
	
	
	//bildqualität berechnen und ampel anzeigen
	getImageQuality(first,second,image[target.id]["pickedPicHr"], imageFieldId,  itemwidth, itemheight);
}

function getImageQuality(width, height, image, targetID,  itemwidth, itemheight)
{
	var vars = 'stretchwidth='+width+'&stretchheight='+height+'&image='+image+'&itemwidth='+itemwidth+'&itemheight='+itemheight;
	
	if(r.readyState==4||r.readyState==0)
	{
		r.open("GET", '/ajx/getImageQuality.php?' + vars);
		r.onreadystatechange =
			function()
			{
				if(r.readyState==4)
				{
					var target = 'ampelContainer_' + targetID;
					var responseContent = r.responseText;
      				//alert(responseContent);

      				if(responseContent == 'good')
      				{
		      			$(target).innerHTML = '<img src="/images/all/ampel-gruen.gif">';
      				}
      				else if(responseContent	== 'average')
      				{
		      			$(target).innerHTML = '<img src="/images/all/ampel-gelb.gif">';
      				}
      				else if(responseContent == 'bad')
      				{
		      			$(target).innerHTML = '<img src="/images/all/ampel-rot.gif">';
      				}
      			}
			};
		r.send(null);
	}
	else
	{
		setTimeout("getImageQuality('"+width+"','"+height+"','"+image+"','"+targetID+"','"+itemwidth+"','"+itemheight+"')",1000);
	}
}

function moveImageX(distance){
	var obj = $("photo_edit_photo");
	var objImg = $("photo_edit_photo_img");
	var oldLeft	= obj.style.left.replace(/px/, "");
	var oldLeftInt = parseInt(oldLeft);
	var newLeftInt = oldLeftInt + distance;
	obj.style.left = newLeftInt + "px";
	objImg.style.left = newLeftInt + "px";
	return false;
}
function moveImageY(distance){
	var obj = $("photo_edit_photo");
	var objImg = $("photo_edit_photo_img");
	var oldTop	= obj.style.top.replace(/px/, "");
	var oldTopInt = parseInt(oldTop);
	var newTopInt = oldTopInt + distance;
	obj.style.top = newTopInt + "px";
	objImg.style.top = newTopInt + "px";
	return false;
}


function zoomImage(factor){
	var objImg 		= $("photo_edit_photo_img");
	var obj 		= $("photo_edit_photo");
	var oldWidth 	= objImg.style.width.replace(/px/, "");
	var oldWidthInt = parseInt(oldWidth);
	var oldHeight 	= objImg.style.height.replace(/px/, "");
	var oldHeightInt = parseInt(oldHeight);
	
	image["image_field_"+imageFieldId]["zoomFactor"] = parseInt(image["image_field_"+imageFieldId]["zoomFactor"]) + parseInt(factor);
	objImg.style.width = (oldWidthInt + Math.round((oldWidthInt*factor/100))) + "px";
	objImg.style.height = (oldHeightInt + Math.round((oldHeightInt*factor/100))) + "px";	
	obj.style.width = (oldWidthInt + Math.round((oldWidthInt*factor/100))) + "px";
	obj.style.height = (oldHeightInt + Math.round((oldHeightInt*factor/100))) + "px";
	
	return false;
}

/*function zoomImage(factor){
	var obj = $("photo_edit_photo_img");
	var oldWidth 	= obj.width.replace(/px/, "");
	var oldWidthInt = parseInt(oldWidth);
	var oldHeight 	= obj.height.replace(/px/, "");
	var oldHeightInt = parseInt(oldHeight);
	image["image_field_"+imageFieldId]["zoomFactor"] = image["image_field_"+imageFieldId]["zoomFactor"] + factor;
	
	obj.style.width = oldWidthInt + Math.round(oldWidthInt*(factor/100));
	obj.style.height = oldHeightInt + Math.round(oldHeightInt*(factor/100));
	
	return false;
}*/

function rotateImage(degree){
	var obj 	= $("photo_edit_photo");
	var objImg 	= $("photo_edit_photo_img");
	
	image["image_field_"+imageFieldId]["rotate"] = parseInt(image["image_field_"+imageFieldId]["rotate"]) + parseInt(degree);
	image["image_field_"+imageFieldId]["ratio"] = 1 / image["image_field_"+imageFieldId]["ratio"];
	
	var hld				= objImg.style.width;
	objImg.style.width 	= objImg.style.height;
	obj.style.width 	= objImg.style.height;
	objImg.style.height	= hld;
	obj.style.height	= hld;
	
	//image["image_field_"+imageFieldId]["height"] = objImg.style.height / displayFactor;
	//image["image_field_"+imageFieldId]["width"] = objImg.style.width / displayFactor;
	
	newBackgroundImg = "/photoeditor/createphoto.php?args=";
	newBackgroundImg += objImg.style.width;
	newBackgroundImg += "/";
	newBackgroundImg += objImg.style.height;
	newBackgroundImg += "/";
	newBackgroundImg += "0/";
	newBackgroundImg += "0/";
	newBackgroundImg += image["image_field_"+imageFieldId]["rotate"] + "/";
	newBackgroundImg += image["image_field_"+imageFieldId]["mode"] + "/";
	newBackgroundImg += image["image_field_"+imageFieldId]["pickedPicHr"];
	newBackgroundImg += "";
	
	image["image_field_"+imageFieldId]["newBackgroundImg"] = newBackgroundImg;
	objImg.src 			= newBackgroundImg;
}

function colorImage(newMode){
	var objImg 	= $("photo_edit_photo_img");
	image["image_field_"+imageFieldId]["mode"] = newMode;
	newBackgroundImg = "/photoeditor/createphoto.php?args=";
	newBackgroundImg += objImg.style.width;
	newBackgroundImg += "/";
	newBackgroundImg += objImg.style.height;
	newBackgroundImg += "/";
	newBackgroundImg += "0/";
	newBackgroundImg += "0/";
	newBackgroundImg += image["image_field_"+imageFieldId]["rotate"] + "/";
	newBackgroundImg += image["image_field_"+imageFieldId]["mode"] + "/";
	newBackgroundImg += image["image_field_"+imageFieldId]["pickedPicHr"];
	newBackgroundImg += "";
	image["image_field_"+imageFieldId]["newBackgroundImg"] = newBackgroundImg;
	objImg.src = newBackgroundImg;
}

function deletePhotoDiv(divNumber){
    var uploaded 		= parseInt(top.$("count_uploaded").value) - 1 ;
    var out			= top.$("change_box_photo_collection_" + divNumber);
    out.style.background 	= "";
    out.innerHTML 		= "";

    top.$("photo_upload_border_area_" + divNumber).style.borderWidth 		= "0px";
    top.$("photo_upload_border_area_" + divNumber).style.backgroundColor 	= "#fafafa";

    top.$("change_box_photo_collection_" + (uploaded+1)+"_text").style.display 	= "none";

    var out1			= top.$("photo_upload_output_area_" + divNumber);
    out1.style.background 	= "";
    var out3 			= top.$("photo_upload_delete_" + divNumber)
    out3.innerHTML 		= "";

    // delete from post for writing in session
    if (top.document.getElementById("hidden_change_box_photo_collection_name_" + divNumber))
	top.document.getElementById("hidden_change_box_photo_collection_name_" + divNumber).value 		= "";
    if (top.document.getElementById("hidden_change_box_photo_collection_width_" + divNumber))
	top.document.getElementById("hidden_change_box_photo_collection_width_" + divNumber).value 		= "";
    if (top.document.getElementById("hidden_change_box_photo_collection_height_" + divNumber))
	top.document.getElementById("hidden_change_box_photo_collection_height_" + divNumber).value 		= "";

    top.$("count_uploaded").value = uploaded;
    
    rearrangeDivs(5);
    styleEditor();
}

function rearrangeDivs(count)
{
    for(var i=1;i<count;i++)
    {
	var out3 	= top.$("photo_upload_delete_" + i);
	var out3Old 	= top.$("photo_upload_delete_" + (i+1));
	
	if(out3.innerHTML == "" && out3Old.innerHTML != "")
	{
	    var out				= top.$("change_box_photo_collection_" + i);
	    var outOld				= top.$("change_box_photo_collection_" + (i+1));
	    out.style.background 		= outOld.style.background;
	    out.innerHTML 			= outOld.innerHTML;
	    outOld.style.background 		= "";
	    outOld.innerHTML 			= "";
	    var out1				= top.$("photo_upload_output_area_" + i);
	    var out1Old				= top.$("photo_upload_output_area_" + (i+1));
	    out1.style.background 		= out1Old.style.background;
	    out1Old.style.background		= "";
	    out3.innerHTML 			= out3Old.innerHTML;
	    out3Old.innerHTML 			= "";
	    top.$("photo_upload_border_area_" + i).style.borderWidth 		= "1px";
	    top.$("photo_upload_border_area_" + i).style.borderWidth 		= top.$("photo_upload_border_area_" + (i+1)).style.borderWidth;
	    top.$("photo_upload_border_area_" + (i+1)).style.borderWidth 	= "0px";
	    top.$("photo_upload_border_area_" + i).style.backgroundColor 	= top.$("photo_upload_border_area_" + (i+1)).style.backgroundColor;
	    top.$("photo_upload_border_area_" + (i+1)).style.backgroundColor 	= "#fafafa";
	    
	    top.$("hidden_change_box_photo_collection_name_"+i).value = top.$("hidden_change_box_photo_collection_name_"+(i+1)).value;
	    top.$("hidden_change_box_photo_collection_name_"+(i+1)).value = "";
	    top.$("hidden_change_box_photo_collection_width_"+i).value = top.$("hidden_change_box_photo_collection_width_"+(i+1)).value;
	    top.$("hidden_change_box_photo_collection_width_"+(i+1)).value = "";
	    top.$("hidden_change_box_photo_collection_height_"+i).value = top.$("hidden_change_box_photo_collection_height_"+(i+1)).value;
	    top.$("hidden_change_box_photo_collection_height_"+(i+1)).value = "";
	    
	    top.$("count_uploaded").value = i;

	}
    }
}

function initImageArray(id)
{
	var innerImage = new Array();
	innerImage["newBackground"] = false;
	innerImage["newBackgroundImg"] = false;
	innerImage["rotate"] = 0;
	//innerImage["savedWidth"] = 0;
	innerImage["zoomFactor"] = 0;
	innerImage["mode"] = "standard";
	innerImage["pickedPicHr"] = "";
	innerImage["ratio"] = 0;
	innerImage["holdX"] = 0;
	innerImage["holdY"] = 0;
	innerImage["height"] = 0;
	innerImage["width"] = 0;
	return innerImage;
}

// hmm das macht das komfortable array unkomfortabel
// du sprichst mit mir im quellcode? ; )
// hast geantwortet oder nich? :)

function saveImageArray(imageArray)
{
	var innerArray = new Array();
	innerArray["newBackground"] = imageArray["newBackground"];
	innerArray["newBackgroundImg"] = imageArray["newBackgroundImg"];
	innerArray["rotate"] = imageArray["rotate"];
	//innerArray["savedWidth"] = imageArray["savedWidth"];
	innerArray["zoomFactor"] = imageArray["zoomFactor"];
	innerArray["mode"] = imageArray["mode"];
	innerArray["pickedPicHr"] = imageArray["pickedPicHr"];
	innerArray["ratio"] =	imageArray["ratio"];
	innerArray["holdX"] = imageArray["holdX"];
	innerArray["holdY"] = imageArray["holdY"];
	innerArray["height"] = imageArray["height"];
	innerArray["width"] = imageArray["width"];
	return innerArray;
}

function switchFrontAndInside(front, frontDivWidth, inlayDivWidth){
    if(front){
	if(insideInitiatedCounter >= insideTextfields){
	    frontSide = true; 
	    $('outside_div').style.display = 'block';
	    $('inlay_div').style.display = 'none'; 
	    $('inside_cropper').style.display = 'none'; 
	    $('outside_cropper').style.display = 'block';
	    $('widthSetter').style.width = frontDivWidth+'px';
	    //$('change_layout_table_head').style.display ='none';
	    //$('change_layout_table').style.display ='none';
	    //$('change_layout_table_bottom').style.display ='none';
	    $('front_button').style.border = '#3f2e09 1px solid';
	    $('inside_button').style.border = '#FFFFFF 1px solid';
	    $('front_button_text').style.textDecoration = 'underline';
	    $('inside_button_text').style.textDecoration = '';
	    inlayIsDisplayed = false;
	    //hide chooser on front if inlaycount > 1
	    if(scitem.item.inlay_cards_composed.length > 1){
		$("change_cards_wrapper").className = "change_box_inner";
		$('inlay_chooser_wrapper').style.display = 'none';   
	    }		
	}
    }else{
	if(frontSideInitiatedCounter >= frontSideTextfields){
	    frontSide = false; 
	    $('inlay_div').style.display = 'block'; 
	    $('outside_div').style.display = 'none'; 
	    $('inside_cropper').style.display = 'block'; 			
	    $('outside_cropper').style.display = 'none'; 
	    $('widthSetter').style.width = inlayDivWidth+'px';
	    //$('change_layout_table_head').style.display ='block';
	    //$('change_layout_table').style.display ='block';
	    //$('change_layout_table_bottom').style.display ='block';
	    $('front_button').style.border = '#FFFFFF 1px solid';
	    $('inside_button').style.border = '#3f2e09 1px solid';
	    $('front_button_text').style.textDecoration = '';
	    $('inside_button_text').style.textDecoration = 'underline';
	    //show chooser on inlay if inlaycount > 1
	    if(scitem.item.inlay_cards_composed.length > 1){
		$("change_cards_wrapper").className = "change_box_inner_with_inlay";
		$('inlay_chooser_wrapper').style.display = 'block';
	    }
	    inlayIsDisplayed = true;
	    initHiddenTextFieldsDone = false;
	    initHiddenTextFields();
	}
    }
}

function findPosX(obj){
	var curleft = 0;
	if(obj.offsetParent){
		while(1){
			curleft += obj.offsetLeft;
			
			if(!obj.offsetParent){
				
				break;
			}
			obj = obj.offsetParent;
		}
	}else if(obj.x){
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj){
	var curtop = 0;
	if(obj.offsetParent){
		while(1){
			curtop += obj.offsetTop;
			if(!obj.offsetParent){
				break;
			}
			obj = obj.offsetParent;
		}
	} else if(obj.y){
		curtop += obj.y;
	}
	
	return curtop;
}

//paginator
function setPageField(page){
	if(page < parseInt($('pages').value) && page >= 0){
		$('pageNumber').value = page;
	}else{
		$('pageNumber').value = 0;
	}

}

function switchPageNumber(increase){
	var newPage = 0;
	if(increase){
		newPage = parseInt($('pageNumber').value)+1;
		if(newPage >= parseInt($('pages').value)){
			newPage = parseInt($('pages').value)-1;
		}
	}else{
		newPage = parseInt($('pageNumber').value)-1;
		if(newPage < 0){
			newPage = 0;
		}
	}
	if(parseInt($('pageNumber').value) != newPage){
		setPageField(newPage);
		narrowCardsSubmit();
	}

}

function setCardsPerPage(){
	$('cardsPerPage').value = $('cardsPerPageSelection').value;
}

//envelope
function setEnvelopeIdAndPrice(){
	var oldId = $('envelope_id').value;
	var newId = $('envelope_id_selection').value;
	$('envelope_id').value = newId;
	$('envelope_single_price').value = $('envelope_price_'+newId);	
	$('price_'+oldId).style.display = 'none';
	if($('envelope_price_'+oldId)){
		$('envelope_price_'+oldId).style.display = 'none';
	}
	$('envelope_add_price_'+oldId).style.display = 'none';
	$('price_'+newId).style.display = 'inline';
	if($('envelope_price_'+oldId)){
		$('envelope_price_'+newId).style.display = 'block';
	}
	$('envelope_add_price_'+newId).style.display = 'block';
	$('envelope_image').src = imgSrcArray[newId];
	changeEnvelopeSumPrices();
}

function setEnvelopeQuantity(){
	$('envelope_quantity').value = $('envelope_quantity_selection').value;
	$('envelope_quantity_div').innerHTML = $('envelope_quantity_selection').value;
	changeEnvelopeSumPrices();
}

function changeEnvelopeSumPrices(){
	var id = $('envelope_id_selection').value;
	
	
	if ($('envelope_price_'+id)){

		var newEnvPrice = 0;
		
		if("," == ".")
		{
			var newEnvPrice 		= parseFloat(cutPreCurrencyString(($('envelope_price_'+id).innerHTML).replace(/\,/,"")));
		} else  {
			var newEnvPrice 		= parseFloat(cutPreCurrencyString(($('envelope_price_'+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
		}
		
		var envQuantity 		= parseInt($('quantity').innerHTML);
	}else{
		var newEnvPrice 		= 0;
		var envQuantity 		= 0;
	}
	
	var newEnvAddPrice
	
	if("," == ".")
	{
		newEnvAddPrice = parseFloat(cutPreCurrencyString(($('envelope_add_price_'+id).innerHTML).replace(/\,/,"")));
	} else  {
		newEnvAddPrice = parseFloat(cutPreCurrencyString(($('envelope_add_price_'+id).innerHTML).replace(/\./,'').replace(/\,/,".")));
	}
	 		
	var envAddQuantity 		= parseInt($('envelope_quantity_selection').value);
	var newEnvSumPrice 		= newEnvPrice*envQuantity;
	var newEnvAddSumPrice 	= newEnvAddPrice*envAddQuantity;
	var newSumTotalPrice 	= newEnvAddSumPrice+newEnvSumPrice;
	var mwst 				= (newSumTotalPrice / 119) * 19;
	var newEnvSumPriceString			=  newEnvSumPrice.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var newEnvAddSumPriceString			=  newEnvAddSumPrice.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var newSumTotalPriceString			=  newSumTotalPrice.toFixed(2).toString().replace(/\./, ",") + " &euro;";
	var mwstString						= mwst.toFixed(2).toString().replace(/\./, ",");
	
	if($('envelope_price_total')){
		$('envelope_price_total').innerHTML = newEnvSumPriceString;
	}

	if($('envelope_add_price_total')){
		$('envelope_add_price_total').innerHTML = newEnvAddSumPriceString;
	}
	$('sum_env_total').innerHTML = newSumTotalPriceString;
	//$('sum_env_mwst').innerHTML = mwstString; //not used anymore, no such field
}

function setAddressLabelQuantity(){
        var str = $('address_label_quantity_selection').value.split("_");

        var volume              = parseFloat(str[0]);
        var single_price        = parseFloat(str[1]);
        var price_sum           = parseFloat(str[2]);
        var price_mwst          = price_sum / 119 * 19;

        $('address_label_quantity_div').innerHTML = volume;
        //$('address_label_single_price').innerHTML =  single_price.toFixed(2).toString().replace(/\./, ",") + " &euro;";
        //$('address_label_price_total').innerHTML =  price_sum.toFixed(2).toString().replace(/\./, ",") + " &euro;";
        //$('sum_address_label_mwst').innerHTML =  price_mwst.toFixed(2).toString().replace(/\./, ",") + " &euro;";
        //$('sum_address_label_total').innerHTML =  price_sum.toFixed(2).toString().replace(/\./, ",") + " &euro;";
        $('address_label_volume').value = volume; 
}


function destinationCountryChanged(doQM)
{













	
	if($('shipping_country_id').value != '48')
	{
		$('dhl_normal').checked = true;
		$('dhl_express_container').style.color = '#BBBBBB';
		$('dhl_express').disabled = true;
	}
	else
	{
		$('dhl_express_container').style.color = '#000000';
		$('dhl_express').disabled = false;
	}

	
	// country id may change instantly
	//if the user has saved express as shipping_type in his session, the next call returns wrong values 
	//getPostageFromSCByCountryId($('shipping_country_id').value);
	
	//so we need this call
	getPostageFromSCByCountryIdAndShippingType($('shipping_country_id').value, false);
	$('postage_duration_close').innerHTML = ")";
	if(doQM == 1)
	{
		switch($('shipping_country_id').value){

		case "48": 		$('postage_duration').innerHTML = "nach 2-3 Werktagen (DHL: "
						break;
		default: 		$('postage_duration').innerHTML = "DHL: ";
						$('postage_duration_close').innerHTML = "";	
		}		
	} else {
		switch($('shipping_country_id').value){

		case "48": 		$('postage_duration').innerHTML = "nach 1-2 Werktagen (DHL: "
						break;
		default: 		$('postage_duration').innerHTML = "DHL: ";
						$('postage_duration_close').innerHTML = "";	
		}	
	}
}

function destinationCountryChangedInSC()
{
	if($('shipping_country_id').value != '48')
	{
		$('dhl_possible').innerHTML = "";
	}
	else
	{
		$('dhl_possible').innerHTML = "(DHL Express möglich: 14,99 &euro;)<br /><br />";
	}
	
	// country id may change instantly
	//if the user has saved express as shipping_type in his session, the next call returns wrong values 
	//getPostageFromSCByCountryId($('shipping_country_id').value);
	
	//so we need this call
	getPostageFromSCByCountryIdAndShippingType($('shipping_country_id').value, true);
	
	switch($('shipping_country_id').value){
	case "192": 	$('postage_duration').innerHTML = "nach 1-2 Werktagen";
					break;
	case "48": 		$('postage_duration').innerHTML = "nach 1-2 Werktagen";
					break;
	case "165": 	$('postage_duration').innerHTML = "nach 1-2 Werktagen";
					break;
	default: 		$('postage_duration').innerHTML = "nach 3-10 Werktagen";	
	}
}

function doesPopUnderCookieExist()
{
	if(false == getCookie('wunderkarten_vc', true))
	{
		return false;
	}
	return true;
}
var toShow, pagelink, browser;
function showVoucher()
{		
	if(document.removeEventListener)
	{
		document.removeEventListener('click', showVoucher, false);
	}
	else if(document.detachEvent)
	{
		document.detachEvent('onclick', showVoucher);
	}
	
	toShow = (toShow != true) ? false : true;
	
	if(toShow && !doesPopUnderCookieExist())
	{	
		var popParams = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=600,height=530,top=300,left=300';
		
		if(browser.name == 'MSIE' && browser.version < 9)
		{
			//opening the old way
			var punder=window.open(pagelink, '_blank', popParams);
			punder.blur();
			window.focus();
			return;
		}
		
		var _parent = self;
		if(top != self)
		{
			try
			{
				if (top.document.location.toString())
				{
					_parent = top;
				}
			}
			catch(err){}
		}
		
	    //create pop-up from parent context
	    var punder = _parent.window.open(pagelink, '_blank', popParams);
	   	if(punder)
	   	{
	   		punder.blur();

   			//popunder for e.g. ff4+, chrome, ie9
   			punder.init = function(e)
   			{
   				with(e)
   				{
   					(function()
   					{
   						if (typeof window.mozPaintCount != 'undefined')
   						{
   							var x = window.open('about:blank');
   							x.close();
   						}
   						try
   						{
   							opener.window.focus();
   						}
   						catch(err){}
   					})();
   				}
   			};
   			punder.params = {url: pagelink};
   			punder.init(punder);
		}
	}
}
if(document.addEventListener)
{
	document.addEventListener('click', showVoucher, false);
}
else if(document.attachEvent)
{
	document.attachEvent('onclick', showVoucher);
}

var clickedBlocked = false;	
function startMoveThumbs(direction)
{
	
	var containerPos = parseInt(document.getElementById("affine_thumb_container").style.left.replace(/px/, ""));
	var containerWidth = parseInt(document.getElementById("affine_thumb_container").style.width.replace(/px/, ""));
	var stopPos = 330 - containerWidth;
	if(direction && containerPos > stopPos && !clickedBlocked){
		clickedBlocked = true;
		thumbsMover = window.setTimeout("moveThumbs(5,"+direction+")",1);
	}else if(!direction && containerPos < 0 && !clickedBlocked){
		clickedBlocked = true;
		thumbsMover = window.setTimeout("moveThumbs(5,"+direction+")",1);
	}
	
}
function moveThumbs(speed,direction){
	
	var thumbsize = 110;
	if(counter+speed >thumbsize)
	{
		counter = thumbsize;
	}
	else
	{
		counter = counter+speed;
	}
	if(direction)
	{
		document.getElementById("affine_thumb_container").style.left = (parseInt(document.getElementById("affine_thumb_container").style.left.replace(/px/, "")) - parseInt(speed))+ "px";;
	}else
	{
		document.getElementById("affine_thumb_container").style.left = (parseInt(document.getElementById("affine_thumb_container").style.left.replace(/px/, "")) + parseInt(speed))+ "px";;
	}
	
	if(counter < thumbsize){ 
		window.setTimeout("moveThumbs("+speed+","+direction+")", 10);
	}else{
		counter = 0;
		clickedBlocked = false;
	}
}

function switchColor(cardId,quantity,newId,newImage,newLink,newThumb,newName)
{
	
	for(var i = 0;i<quantity;i++)
	{
		
		document.getElementById("card_color_"+cardId+"_"+i).style.border = "1px solid #503017"; 
	}
	$("card_color_"+cardId+"_"+newId).style.border = "2px solid #503017"; 
	$("hidden_card_link_"+cardId).value = newLink; 
	$("hidden_card_thumb_medium_"+cardId).value = 'http://static-1.wunderkarten.de/live/cards/'+newThumb;
	$("card_link_text_"+cardId).href = "/product/"+newLink; 
	$("card_link_"+cardId).href = "/product/"+newLink; 
	$("card_image_"+cardId).src = 'http://static-1.wunderkarten.de/live/cards/'+newImage;
	$("card_link_text_"+cardId).innerHTML = newName;
	if($("card_link_eyecatcher_"+cardId))
	{
		$("card_link_eyecatcher_"+cardId).href = "/product/"+newLink; 
	}
}
function kategorieGoto(id)
{
	goto("/product/"+document.getElementById("hidden_card_link_"+id).value); 
}

function openKategorieVorschau(title, id)
{
	openVorschau(title, document.getElementById("hidden_card_thumb_medium_"+id).value, "/product/"+document.getElementById("hidden_card_link_"+id).value, '', document.getElementById("hidden_card_size_"+id).value, '')
}

function showFB(fb)
{
	document.getElementById('showKlassik').style.display = 'none';
	document.getElementById('showMini').style.display = 'none';	
	document.getElementById('showPremium').style.display = 'none';
	document.getElementById(fb).style.display = 'block';
}

var automaticSwitch = null;

function startFading()
{
	automaticSwitch = window.setTimeout("fadeTeaserImages(4)",3000);
}

var currentPicID = 2;
var oldID = 1;
var currentCategory = 'Babygirl';
var counter = 0;

function fadeTeaserImages(speed)
{
	window.clearTimeout(automaticSwitch);

	if(counter+speed >100)
	{
		counter = 100;
	}
	else
	{
		counter = counter+speed;
	}
	//IE opacity
	if(isIE)
	{
		$("beispiel"+currentCategory+currentPicID).style.filter = "Alpha(opacity="+counter+")";
		$("beispiel"+currentCategory+oldID).style.filter = "Alpha(opacity="+(100 - counter)+")";
	}
	else
	{
	//FF opacity
		$("beispiel"+currentCategory+currentPicID).style.opacity = (1/100 * counter);
		$("beispiel"+currentCategory+oldID).style.opacity = (1/100 * (100 - counter));	
	}
	if(counter <100){ 
		window.setTimeout("fadeTeaserImages("+speed+")", 1);
	}else{
		counter=0; 
		$("beispiel"+currentCategory+currentPicID).style.zIndex = 1;
		$("beispiel"+currentCategory+oldID).style.zIndex = 0;
		
		if(currentPicID == 4)
		{
			currentPicID = 1
			oldID = 4;
		}
		else
		{
			oldID = currentPicID;
			currentPicID++;
		}
		startFading();
	}
}

function changeCategory(which)
{
	$("beispiel"+currentCategory+currentPicID).style.opacity = 0;
	$("beispiel"+currentCategory+oldID).style.opacity = 0;
	$("beispiel"+currentCategory+currentPicID).style.zIndex = 0;
	$("beispiel"+currentCategory+oldID).style.zIndex = 0;
	
	if(which == 'Babygirl')
	{
		currentCategory = which;
	}
	else if(which == 'Reise')
	{
		currentCategory = which;
	}
	else if(which == 'Hochzeit')
	{
		currentCategory = which;
	}
	
	currentPicID = 2;
	oldID = 1;
	counter = 0;
	$("beispiel"+currentCategory+oldID).style.opacity = 1;
}	
	//startFading();


var csv_creation_dayNumber = 0;

function launch_csv_creation(dayOfTimeInterval) {
	// Paramter aus Formular übernehmen
	start_date = document.getElementById('start_date').value;
	end_date = document.getElementById('end_date').value;
	creationMethod = document.getElementById('creation_method').value;
	document.getElementById('csv_create_button').disabled=true;
	document.getElementById('csv_show_button').disabled=true;
	document.getElementById('csv_delete_button').disabled=true;
	if (csv_creation_dayNumber == 0) {
		document.getElementById('csv_creation_status_output').innerHTML = "Informationen werden gesammelt (das kann einige Sekunden dauern)...";
	}
	var myAjax = new Ajax.Request(
			"/ajx/createcsv.php?action=create_csv&start_date="+start_date+"&end_date="+end_date+"&method="+creationMethod+"&pd="+dayOfTimeInterval,
			{ method: 'get', onComplete: show_csv_creation_status }
	);
}

function show_csv_creation_status(originalRequest) {
	document.getElementById('csv_creation_status_output').innerHTML = originalRequest.responseText;
	if (originalRequest.responseText == "-1") {
		// Alle Daten sollten gesammelt und die Finaldatei fertig erstellt sein.
		csv_creation_dayNumber = 0;
		document.getElementById('csv_create_button').disabled=false;
		document.getElementById('csv_show_button').disabled=false;
		document.getElementById('csv_delete_button').disabled=false;
		document.getElementById('csv_creation_status_output').innerHTML = "Statistiken erstellt.<br />CSV kann nun geöffnet werden.";
	} else {
		// Generierung des nächsten Tages anstossen
		document.getElementById('csv_create_button').disabled=true;
		document.getElementById('csv_show_button').disabled=true;
		document.getElementById('csv_delete_button').disabled=true;
		csv_creation_dayNumber++;
		document.getElementById('csv_creation_status_output').innerHTML = "Erstelle Statistiken für Tag "+csv_creation_dayNumber+" von "+originalRequest.responseText;
		launch_csv_creation(csv_creation_dayNumber);
	}
}

function launch_csv_deletion() {
	// Paramter aus Formular übernehmen
	document.getElementById('csv_creation_status_output').innerHTML = "CSVs werden gelöscht...";
	var myAjax = new Ajax.Request(
			"/ajx/createcsv.php?action=delete_csv_and_temp",
			{ method: 'get', onComplete: show_csv_deletion_status }
	);
}

function show_csv_deletion_status(originalRequest) {
	document.getElementById('csv_creation_status_output').innerHTML = originalRequest.responseText;
}

function glossyOptionTriggered(productTypeID, UID, glossyOptionBox)
{	
	var checked = glossyOptionBox.checked;

	if(checked)
	{
		$('glossy_'+UID).value = 'j';
		
		var myAjax = new Ajax.Request(
				'/ajx/getOptionPrice.php?prtid=' + productTypeID,
				{ method: 'get', onComplete: applyOptionPrice}
		);
		
		myAjax.uid 		= UID;
		myAjax.applyTo	= 'Shoppingcart'
	}
	else
	{
		$('glossy_'+UID).value = 'n';
		updateShoppingCart(''+UID, $('select_quantity_'+UID));
	}
}

function loadGlossyOptionPrice(productTypeID, UID)
{
	var myAjax = new Ajax.Request(
			'/ajx/getOptionPrice.php?prtid=' + productTypeID,
			{ method: 'get', onComplete: applyOptionPrice}
	);
	
	myAjax.uid 		= UID;
	myAjax.applyTo	= 'CheckboxDescription'
}

function applyOptionPrice(response)
{
	var UID 	= response.request.uid;
	var applyTo = response.request.applyTo;
	
	if(applyTo == 'Shoppingcart')
	{
		updateShoppingCart(''+UID, $('select_quantity_'+UID), response.responseText);
	}
	else if(applyTo == 'CheckboxDescription')
	{
		$('glossy_single_' + UID).innerHTML = response.responseText;
	}
}

function productPreviewSwitch(tabImageId,tabImageSrc,http,imageId,product)
{
	$(product+"_tab_baby").src = http+'images/fb/tab_baby_1.jpg';
	$(product+"_tab_hochzeit").src = http+'images/fb/tab_hochzeit_1.jpg';
	$(product+"_tab_reise").src = http+'images/fb/tab_reise_1.jpg';
	$(product+"_tab_familie").src = http+'images/fb/tab_familie_1.jpg';
	
	$(tabImageId).src = http+tabImageSrc;
		
	$(product+"_img_baby").style.display = 'none';
	$(product+"_img_hochzeit").style.display = 'none';
	$(product+"_img_reise").style.display = 'none';
	$(product+"_img_familie").style.display = 'none';
	
	$(imageId).style.display = 'inline';
}

function productPreviewSwitchKalender(tabImageId,tabImageSrc,http,imageId,product)
{
	$("kalender_tab_fruehling").src = http+'images/fb/fruehling_1.jpg';
	$("kalender_tab_sommer").src = http+'images/fb/sommer_1.jpg';
	$("kalender_tab_herbst").src = http+'images/fb/herbst_1.jpg';
	$("kalender_tab_winter").src = http+'images/fb/winter_1.jpg';
	
	$(tabImageId).src = http+tabImageSrc;
		
	$("kalender_img_fruehling").style.display = 'none';
	$("kalender_img_sommer").style.display = 'none';
	$("kalender_img_herbst").style.display = 'none';
	$("kalender_img_winter").style.display = 'none';
	
	$(imageId).style.display = 'inline';
}

function toggleCustomerType(type)
{
	if(type == 'person')
	{
		if($('birthdayDiv') != null && $('setBirthdayInput') != null)
		{
			$('birthdayDiv').style.display		= 'block';
			$('setBirthdayInput').value			= '1';
		}
		
		if($('companyDataDiv') != null && $('setCompanyDataInput') != null)
		{
			$('companyDataDiv').style.display	= 'none';
			$('setCompanyDataInput').value		= '0';
		}
	}
	else if(type == 'company')
	{
		if($('birthdayDiv') != null && $('setBirthdayInput') != null)
		{
			$('birthdayDiv').style.display		= 'none';
			$('setBirthdayInput').value			= '0';
		}
		
		if($('companyDataDiv') != null && $('setCompanyDataInput') != null)
		{
			$('companyDataDiv').style.display	= 'block';
			$('setCompanyDataInput').value		= '1';
		}
	}
}

function setExtraChargePayment(newCharge)
{
	if($('total_content_ink_voucher') != null)
	{
		var curTotal	= 0;
		var curSub		= parseFloat(cutPreCurrencyString(($('subtotal_content').innerHTML).replace(/\./,'').replace(/\,/,'').replace(/[^0-9]/,'')));
		
		if($('mwst_content') != null)
		{
			var curShipping	= parseFloat(cutPreCurrencyString(($('mwst_content').innerHTML).replace(/\./,'').replace(/\,/,'').replace(/[^0-9]/,'')));
		}
		else
		{
			var curShipping = 0;
		}
		
		var curVoucher = 0;
		if($('voucher_total_content') != null)
		{
			var curVoucher = parseFloat(cutPreCurrencyString(($('voucher_total_content').innerHTML).replace(/\./,'').replace(/\,/,'').replace(/[^0-9]/,'')));
		}
		
		if(isNaN(curVoucher))
		{
			curVoucher = 0;
		}
		
		curTotal = curSub + curShipping + newCharge - curVoucher;
		
		$('total_content_ink_voucher').innerHTML =  parseFloat(curTotal/100).toFixed(2).toString().replace(/\./,",") + " &euro;";
	}
	
	if($('extra_charge_content') != null)
	{
		$('extra_charge_content').innerHTML =  parseFloat(newCharge/100).toFixed(2).toString().replace(/\./,",") + " &euro;";
	}
}

var extraChargeToLoadOnView = 0;
function setLoadExtraChargeOnView(toLoad)
{
	extraChargeToLoadOnView = toLoad;
}

function loadExtraCharge()
{
	if(extraChargeToLoadOnView > 0)
	{
		setExtraChargePayment(extraChargeToLoadOnView);
		extraChargeToLoadOnView = 0;
	}
}

function cutPreCurrencyString(currentString)
{
	var myreturn = currentString.replace(/[^0-9.]*/g,"");
	return myreturn;
}
/**
 * webtrekkConfig
 * 
 * globale webtrekk konfiguration
 * global webtrekk config
 * @type Object
 */
var webtrekkConfig = {
	trackId : "648299458831411",
	trackDomain : "ecards01.webtrekk.net",

	domain : "www.wunderkarten.de",
	cookie : "1",
	contentId : ""
};
/** end webtrekkConfig**/

function loadMagnifier(loadingText, xOffset, width, preloadImages, loaderVisibility)
{
	var options = {	zoomType: 'reverse',	//standard, reverse, drag, innerzoom
			zoomWidth: width,
			zoomHeight: 400,
			xOffset: xOffset,
			yOffset: 0,
			position:'right',		//top, right, bottom, left
			preloadImages: preloadImages,
			preloadText: loadingText,
			title: false,			
			lens:true,
			imageOpacity: 0.3,
			showEffect: 'show',	//show, fadein
			hideEffect: 'hide',	//hide, fadeout
			fadeinSpeed: 'fast',	//slow, fast, number
			fadeoutSpeed: 'fast',	//slow, fast, number
			loaderVisibility: loaderVisibility,	//visible, hidden
			alwaysOn:false
	};  
	jQuery('.magnify').jqzoom(options);
}

function previewLoadComplete(which)
{
	var loader = which + '_loader';
	$(loader).style.display	= 'none';
	$(which).style.display	= 'block';
}

function alertStatus()
{
	alert('working');
}
