/* 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;
}

//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;
}

function subscribeNL(email){
	if(validateEmail(email)){
		return true;
	}else{
		location.href = "/handledata.php?formname=insert_newsletter";
		return false;
	}
	
}

function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(email);
}

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;
}

function changeBackgroundColor(id, color){
	$(id).style.background = '#123456';
}

function openVorschau(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){
			if(!isIE7){
				if(!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 closeVorschau(){
	$("kategorie_vorschau").style.visibility = "";
}

/* 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(){
	logOCPV('isconv=0|pover=Signup');
	document.user_register.submit();
	return false;
}

function passwordForgottenSubmit(){
	document.pwd_forgotten.submit();
	return false;
}

function productSubmit(){
	document.product.submit();
	return false;
}

function submitPreview(){
	document.preview.submit();
	return false;
}

function personalize_form_submit(){
	document.personalize.submit();
	return false;
}

function change_form_submit(action){
	if(!action){
		document.change.submit();
	}else{
		$('action').value = action;
		document.change.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){
	var priceBefore						= parseFloat(($('price_content_' + id).innerHTML).replace(/\./,'').replace(/\,/,"."));
	if($('price_envelope_'+id)){
		var priceEnvelopeBefore 		= parseFloat(($('price_envelope_'+id).innerHTML.replace(/\./,'')).replace(/\,/,"."));
	}else{
		var priceEnvelopeBefore			= 0;
	}
	var priceAdditionalEnvelopeBefore 	= parseFloat(($('price_add_envelope_'+id).innerHTML).replace(/\./,'').replace(/\,/,"."));
	var totalBefore						= parseFloat(($('total_content').innerHTML).replace(/\./,'').replace(/\,/,"."));
	
	var percentage_reduction			= parseFloat(($('percentage_reduction').value).replace(/\./,'').replace(/\,/,"."));
	var absolute_reduction				= parseFloat(($('absolute_reduction').value).replace(/\./,'').replace(/\,/,"."));
	
	var	singlePrice						= obj.value; 
	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;
	}
	
	if($('single_price_envelope_'+id)){
		var envelopeSinglePrice				= parseFloat(($('single_price_envelope_'+id).innerHTML).replace(/\./,'').replace(/\,/,"."));
	}else{
		var envelopeSinglePrice				= 0;	
	}
	
	if($("price_envelope_"+id)){
		$("price_envelope_"+id).innerHTML 		= parseFloat(envelopeSinglePrice*quantity).toFixed(2).toString().replace(/\./, ",") + " &euro;";
	}
	
	var priceAdditionalEnvelopes 			= parseFloat(($("price_add_envelope_"+id).innerHTML).replace(/\./,'').replace(/\,/,"."));
	
	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 			= obj.value;
	var totalBefore						= parseFloat(($('total_content').innerHTML).replace(/\./,'').replace(/\,/,"."));
	var addPriceBefore					= parseFloat(($("price_add_envelope_"+id).innerHTML).replace(/\./,'').replace(/\,/,"."));
	var single_add_price 				= parseFloat(($('single_price_add_envelope_'+id).innerHTML).replace(/\./,'').replace(/\,/,"."));
	var percentage_reduction			= parseFloat(($('percentage_reduction').value).replace(/\./,'').replace(/\,/,"."));
	var absolute_reduction				= parseFloat(($('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 submitShoppingConfirm(){
	document.payment_data.submit();
}

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();
}

/* nav_hor */
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;
}

/* start ajax site search */

function prepareSearch(){
	var obj = $('header_search_input');
	if (obj.value == 'Suchbegriff eingeben' ) 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 r = getXmlHttpRequestObject();

function getPostage(card_count, card_type, product_type, country_id){
	//alert(country_id);
	//alert('/ajx/get_postage.php?card_count=' + card_count + '&card_type=' + card_type + '&product_type=' + product_type + '&country_id=' + country_id);
	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 displayNewPostage(){
	if (r.readyState == 4) {
		//alert(r.responseText);
		$('postage_price').innerHTML = (r.responseText / 100).toFixed(2).replace(/\./, ",") + " EUR";
	}
}

function showExampleSearch(text) {
	$('search_suggest_wrapper').style.visibility = 'visible';
	if (searchReq.readyState == 4 || searchReq.readyState == 0) {
		var str = escape(text);
		searchReq.open("GET", '/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("\n");
		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 += 'class="suggest_link">' + result + '</div>';
				ss.innerHTML += suggest;
			}
		}
	}
}

//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';
}

//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';
	
}

/* home teaser */
var chosenId = 0;
var oldId = 0; //id of flashteaser
var counter = 0;
inputAllowed = true;
var switchInputAllowed = false;
var automatikSwitch = null;
var automatikSwitchCounter = 0; //ja mit k

function startTeaserMenu(){
	inputAllowed = true;
	showHomeTeaser(teaserArray[0],true);
}
function stopTeaserMenu(){
	inputAllowed = true;
	 showHomeTeaser(0,false);

}

function showHomeTeaser(id,switcher)
{	
	if(inputAllowed){
		//getOldImageId();
		if(oldId != id){
			chosenId = id;
			setChosenLink();
			stopSwitcher();
			fadeImages(4,switcher);
		}
	}
}

function fadeImages(speed,switcher){
	inputAllowed = false;
	if(counter+speed >100){counter = 100;}else{	counter = counter+speed;}
	//IE opacity
	if(isIE){
	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+","+switcher+")", 1);
	}else{
		counter=0; 
		inputAllowed = true;
		switchInputAllowed = true;
		document.getElementById("teaser"+chosenId).style.zIndex = 1;
		document.getElementById("teaser"+oldId).style.zIndex = 0;
		stopSwitcher();
		if(foundFlashTeaser){
			if(switcher){
				automaticSwitcher(5)
				resetTeaserMovie();
			}else{
				startTeaserMovie();
				//inputAllowed = false;
				switchInputAllowed = false;
			}
		}else{
			if(switcher){
				automaticSwitcher(5)
				document.getElementById("gifTeaser").src = sourceStringJPG;
				window.clearTimeout(teaserGifTime);
			}else{
				teaserGifTimer(11,false);
				document.getElementById("gifTeaser").src = sourceStringGif;
				//inputAllowed = false;
				switchInputAllowed = false;
			}
		}
		oldId = chosenId;
	}

}
function setChosenLink(){

	if(document.getElementById(chosenId+"_link") != null){
		document.getElementById(chosenId+"_link").className = "activeLink";
	}
	if(document.getElementById(oldId+"_link") != null){
		document.getElementById(oldId+"_link").className = "inactiveLink";
	}
	
}

function switchmenu(side){
//	getOldImageId();
	if(switchInputAllowed)
	{
		if(inputAllowed){
			for(var i=0;i<teaserArray.length;i++)
			{
				if(teaserArray[i] == oldId){
					if(side == "left"){
						if(i-1 < 0){
							showHomeTeaser(teaserArray[teaserArray.length-1],true);
						}else{			
							showHomeTeaser(teaserArray[i-1],true);
						}
					}else{
						if(i+1 > teaserArray.length-1){
							showHomeTeaser(teaserArray[0],true);
						}else{			
							showHomeTeaser(teaserArray[i+1],true);
						}
					}
				}
			}
		}
	}	
}
function stopSwitcher(){

	firstCall = true;
	if(automatikSwitch != null){
		window.clearTimeout(automatikSwitch);
	}
	
}

function automaticSwitcher(timeSec)
{
	if(!firstCall){
		if(automatikSwitchCounter == 3){
			automatikSwitchCounter = 0;
			stopTeaserMenu();
		}
		else
		{
			switchmenu("right");
			automatikSwitchCounter++;
		}
	}
	firstCall = false;
	automatikSwitch = window.setTimeout("automaticSwitcher("+timeSec+")", timeSec*1000);
}
function teaserGifTimer(timeSec,stop)
{

	if(!stop)
	{	
		teaserGifTime = window.setTimeout("teaserGifTimer("+timeSec+",true)", timeSec*1000);
	}else{
		startTeaserMenu();
	}

}

/* externen  actionscriptfunktion */
function thisMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function startTeaserMovie() {
		var test = thisMovie("flashkarte84");
		test.startTeaserMovie();
}
function resetTeaserMovie(){
		var test = thisMovie("flashkarte84");
		test.resetTeaserMovie();

}

/* 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 + 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;
	if(card_type == 1 || card_type == 2){
		if(card_type == 1){
			c_value = document.product.quantity_1.value;
		} else {
			c_value = document.product.quantity_2.value;
		}
	}else{
		c_value = document.product.quantity_3.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 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();

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).style.border = "solid 1px #736F6E";
	}
}

function hideBorder(id){
	if($("image_text_field_"+id)){
		$("image_text_field_"+id).style.border = "0px";
	}
}

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);
	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 changeTextSizeList(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 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;
	var _background	 	= "url('/photoeditor/createtext.php?args=" + custom + ".png') no-repeat";
	var _IEBackground  	= "/photoeditor/createtext.php?args=" + custom + ".png";
	
	if (isIE){
		set_ie_background(field, _IEBackground);
	}else{
		$(field).style.background = _background;
	}
	
	/* 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 openPhotoEdit(elem){
	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"])*displayFactor) + "px";
	$("photo_edit_photo_img").style.height	= Math.round(parseFloat(image[elem.id]["height"])*displayFactor)+ "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"])*displayFactor) + "px";
	$("photo_edit_photo_img").style.top 	= Math.round(parseFloat(image[elem.id]["holdY"])*displayFactor) + "px";
	
	$("photo_edit_photo").style.width 		= Math.round(parseFloat(image[elem.id]["width"])*displayFactor) + "px";
	$("photo_edit_photo").style.height 		= Math.round(parseFloat(image[elem.id]["height"])*displayFactor)+ "px";
	$("photo_edit_photo").style.left 		= Math.round(parseFloat(image[elem.id]["holdX"])*displayFactor) + "px";
	$("photo_edit_photo").style.top 		= Math.round(parseFloat(image[elem.id]["holdY"])*displayFactor) + "px";
  	 
	if(((Math.round(parseFloat(image[elem.id]["width"])*displayFactor) + Math.round(parseFloat(image[elem.id]["holdX"])*displayFactor) ) <0 ) || 
	   ((Math.round(parseFloat(image[elem.id]["height"])*displayFactor) + Math.round(parseFloat(image[elem.id]["holdY"])*displayFactor) ) <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(){
	$("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);
	}
	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";
	}
	
}

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(../../../cards/userimages/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(../../../cards/userimages/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('');
	
	top.document.getElementById("count_uploaded").value 		= uploaded;
	styleEditor();
}
	

function isElementDropped(id){
	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);
	}
}

function applyPhotoEdit(){
	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) / displayFactor;
	image["image_field_"+imageFieldId]["holdY"] 		= parseFloat(obj.style.top) / displayFactor;
	image["image_field_"+imageFieldId]["height"] 		= parseFloat(obj.style.height) / displayFactor;
	image["image_field_"+imageFieldId]["width"]			= parseFloat(obj.style.width) / displayFactor;
	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) / displayFactor;
	$("image_form_field_" + imageFieldId + "_height").value = parseFloat(second) / displayFactor;
	$("image_form_field_" + imageFieldId + "_top").value = parseFloat(obj.style.top) / displayFactor;
	$("image_form_field_" + imageFieldId + "_left").value = parseFloat(obj.style.left) / displayFactor;
	$("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);
}

function getImageQuality(width, height, image, targetID)
{
	var vars = 'stretchwidth='+width+'&stretchheight='+height+'&image='+image;
	
	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/ampel-gruen.gif">';
      				}
      				else if(responseContent	== 'average')
      				{
		      			$(target).innerHTML = '<img src="/images/ampel-gelb.gif">';
      				}
      				else if(responseContent == 'bad')
      				{
		      			$(target).innerHTML = '<img src="/images/ampel-rot.gif">';
      				}
      			}
			};
		r.send(null);
	}
	else
	{
		setTimeout("getImageQuality('"+width+"','"+height+"','"+image+"','"+targetID+"')",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_" + uploaded))
		top.document.getElementById("hidden_change_box_photo_collection_name_" + uploaded).value 		= "";
	if (top.document.getElementById("hidden_change_box_photo_collection_width_" + uploaded))
		top.document.getElementById("hidden_change_box_photo_collection_width_" + uploaded).value 		= "";
	if (top.document.getElementById("hidden_change_box_photo_collection_height_" + uploaded))
		top.document.getElementById("hidden_change_box_photo_collection_height_" + uploaded).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.$("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){
	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';
			$('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 = '';
		}
	}else{
		if(frontSideInitiatedCounter >= frontSideTextfields){
			initHiddenTextFields(); 
			frontSide = false; 
			$('inlay_div').style.display = 'block'; 
			$('outside_div').style.display = 'none'; 
			$('inside_cropper').style.display = 'block'; 
			$('outside_cropper').style.display = 'none'; 
			$('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';
		}
	}
}

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;
	$('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 		= parseFloat(($('envelope_price_'+id).innerHTML).replace(/\./,'').replace(/\,/,"."));
		var envQuantity 		= parseInt($('quantity').innerHTML);
	}else{
		var newEnvPrice 		= 0;
		var envQuantity 		= 0;
	}
	
	var newEnvAddPrice 		= parseFloat(($('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()
{
	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
	getPostageFromSCByCountryId($('shipping_country_id').value);
	
	switch($('shipping_country_id').value){
	case "192": 	$('postage_duration').innerHTML = "nach 3-4 Werktagen (DHL: ";
					break;
	case "48": 		$('postage_duration').innerHTML = "nach 3-4 Werktagen (DHL: ";
					break;
	case "165": 	$('postage_duration').innerHTML = "nach 3-4 Werktagen (DHL: ";
					break;
	default: 		$('postage_duration').innerHTML = "nach 3-10 Werktagen (DHL: ";	
	}
}

var toShow, pagelink;

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 == true)
	{	
		var fenster=window.open(pagelink, '_blank', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=600,height=530,top=300,left=300');
		fenster.blur();
		window.focus();
	}
}

if(document.addEventListener)
{
	document.addEventListener('click', showVoucher, false);
}
else if(document.attachEvent)
{
	document.attachEvent('onclick', showVoucher);
}