/*****************************************/
/** Usable Forms 2.0, November 2005     **/
/** Written by ppk, www.quirksmode.org  **/
/** Instructions for use on my site     **/
/**                                     **/
/** You may use or change this script   **/
/** only when this copyright notice     **/
/** is intact.                          **/
/**                                     **/
/** If you extend the script, please    **/
/** add a short description and your    **/
/** name below.                         **/
/*****************************************/


/************************* start configurator calculator*******************************/
function kaufm(x){
  var k = (Math.round(x * 100) / 100).toString();
  k += (k.indexOf('.') == -1)? '.00' : '00';
  var p = k.indexOf('.');
  return k.substring(0, p) + ',' + k.substring(p+1, p+3);
}

function isANumber(n){
	var s = "" + n;
	var ziffern = "0123456789.,";
	for (var i=0; i<s.length; i++)
		if (ziffern.indexOf(s.charAt(i))==-1)
			return false;
	return true;
}

function calc_volume() {
	var widthCalc = document.getElementsByName("width")[0].value;
	widthCalc = widthCalc.replace(",",".");
	var lengthCalc = document.getElementsByName("length")[0].value;
	lengthCalc = lengthCalc.replace(",",".");
	var heightCalc = 1;
	
	/*
	if(document.getElementsByName("height")[0]){
		var heightCalc = document.getElementsByName("height")[0].value;
		heightCalc = heightCalc.replace(",",".");
	}
	else{
		var heightCalc=1;
	}
	*/
	if(!isANumber(widthCalc) || !isANumber(heightCalc) || !isANumber(lengthCalc)){
		return;
	}
	var qty = parseFloat(document.getElementsByName("products_qty")[0].value);	
	var price = getPrice(qty); 
	var attrib_sum_before = 0.0; var attrib_sum_after = 0.0;

	// attribute prices
	var tmpmaxattr = document.getElementById('attrib_range');
	if(tmpmaxattr != null && tmpmaxattr != undefined){
		var maxattr = tmpmaxattr.value;
		maxattr = maxattr.split("|");
	}
	else
		var maxattr = 2;
	for (var i = 0; i <= (maxattr.length - 2); i++){
		var tmpIndex = "id[" + maxattr[i] + "]";
		var z = document.getElementsByName(tmpIndex);
		var id;
		for(var j=0; j< z.length; j++){
			var item = z[j];
			if(item.type == "radio" && item.checked){
				id = item.value;
			}
			if(item.type == "select-one"){
				id = item.options[item.selectedIndex].value;
			}
		}
		var tmpCalcMode=document.getElementsByName('calc'+tmpIndex)[0].value; 
		
		if(tmpCalcMode != undefined){
			if(tmpCalcMode == "before") attrib_sum_before = attrib_sum_before + lookupPrice(id);
			if(tmpCalcMode == "after") attrib_sum_after = attrib_sum_after + lookupPrice(id);
		}
	}
	var volume = widthCalc * lengthCalc * heightCalc;
	document.getElementsByName("calcresult")[0].value= kaufm(volume);
	var price_before= parseFloat(price) + attrib_sum_before;
	document.getElementsByName("price")[0].value = kaufm(price_before);
	
	// DIATOM Internet & Medien GmbH - 04.06.2010
	//document.getElementsByName("calcprice")[0].value= kaufm((volume * price_before) + attrib_sum_after);
	check_price_new = ((volume * price_before) + attrib_sum_after);
	if( check_price_new < price_before ) {
	   document.getElementsByName("calcprice")[0].value = kaufm(price_before);
	} else {
	   document.getElementsByName("calcprice")[0].value = kaufm((volume * price_before) + attrib_sum_after);
	}
	// DIATOM Internet & Medien GmbH - 04.06.2010
	
	// DIATOM Internet & Medien GmbH - 10.06.2010
	calc_rastprice(attrib_sum_after);
	// DIATOM Internet & Medien GmbH - 10.06.2010

}

// DIATOM Internet & Medien GmbH - 10.06.2010
function calc_rastprice(attrib_sum_after) {

    rasterprice = document.getElementById("rasterpricelist").value;
    if( rasterprice == "" ) return;
    
    var widthCalc = document.getElementsByName("width")[0].value;
	widthCalc = widthCalc.replace(",",".");
	var lengthCalc = document.getElementsByName("length")[0].value;
	lengthCalc = lengthCalc.replace(",",".");
    
    i           = 0;
    rastWList   = new Array();
    rastHList   = new Array();
    rastOut     = new Array();
    rastLSpal   = new Array();
    
    rastLZeil   = rasterprice.split("\n");
    if( rastLZeil != "" ) {
        for(var k = 0; k < rastLZeil.length; k++) {
            rastLSpal[k] = rastLZeil[k].split(";");
            if( rastLSpal[k] != "" ) {
                for(var k2 = 0; k2 < rastLSpal[k].length; k2++) {
                    if( k != 0 && k2 != 0 ) {
                        v2 = rastLSpal[k][k2].replace(/\s/g, "");
                        if( v2 != '' ) {
                            rastOut[i]              = new Array();
                            rastOut[i]['height']    = rastLSpal[k][0];
                            rastOut[i]['width']     = rastLSpal[0][k2];
                            rastOut[i]['price']     = v2;
                            i++;
                        }
                    }
                }
            }
        } 
    }
    
    if( rastOut != "" ) {
        getRastHeight  = lengthCalc * 1000;
        getRastWidth   = widthCalc * 1000;
        rastPrice      = 0;
        curHeight      = 0;
        lastHeight     = 0;
        lastWidth      = 0;
        for(var k = 0; k < rastOut.length; k++) {
            if( getRastHeight <= rastOut[k]['height'] ) {
                if( getRastWidth <= rastOut[k]['width'] ) {
                    rastPrice = rastOut[k]['price'];
                    break;
                }
            }
            if( rastOut[k]['height'] > curHeight ) {
                lastHeight = rastOut[k]['height'];
            }
            curHeight      = rastOut[k]['height'];
            lastWidth      = rastOut[k]['width'];
        }
        if( rastPrice != 0 ) {
            rastPrice = parseInt(rastPrice) + parseInt(attrib_sum_after);
            document.getElementsByName("calcprice2")[0].value = kaufm(rastPrice);/* Total Price with all options*/
			
			
			rastPrice1 = parseInt(rastPrice) - parseInt(attrib_sum_after);/*Price without options*/
			
			document.getElementsByName("calcprice_int")[0].value = kaufm(rastPrice1);/*Price without options*/
			document.getElementsByName("calcprice_int1")[0].value = kaufm(rastPrice);/*Price with motor options*/
						
			/* Option insekenschutzkasten*/			
			if(document.getElementsByName('id[88]')[0].checked == true){
	        document.getElementsByName("calcprice_int2")[0].value = kaufm(rastPrice);
            }
            else if(document.getElementsByName('id[88]')[1].checked == true){            			
			/*var option = document.getElementsById("priceid564").value;*/			
			price_int1 = rastPrice - 65,45; // mit option motor without insect option 57,99									
			document.getElementsByName("calcprice_int2")[0].value = kaufm(price_int1);			
			}
			/*  end Option rund kasten*/			
			
						
        }
    }
}
// DIATOM Internet & Medien GmbH - 10.06.2010

function calc_length() {
	var lengthCalc = document.getElementsByName("length")[0].value;

	lengthCalc = lengthCalc.replace(",",".");
	
	if(!isANumber(lengthCalc))
		return;

	var qty = parseFloat(document.getElementsByName("products_qty")[0].value);
	var price = getPrice(qty);
	var attrib_sum_before = 0.0; var attrib_sum_after = 0.0;

	// attribute prices
	var tmpmaxattr = document.getElementById('attrib_range');
	if(tmpmaxattr != null && tmpmaxattr != undefined)
		var maxattr = tmpmaxattr.value;
	for (var i = 1; i <= maxattr; i++){
		var tmpIndex = "id[" + i + "]";
		var z = document.getElementsByName(tmpIndex);
		var id;
		for(var j=0; j< z.length; j++){
			var item = z[j];
			if(item.type == "radio" && item.checked){
				id = item.value;
			}
			if(item.type == "select-one"){
				id = item.options[item.selectedIndex].value;
			}
		}
		var tmpCalcMode=document.getElementsByName("calc" + tmpIndex)[0].value; 
		if(tmpCalcMode != undefined){
			if(tmpCalcMode == "before") attrib_sum_before = attrib_sum_before + lookupPrice(id);
			if(tmpCalcMode == "after") attrib_sum_after = attrib_sum_after + lookupPrice(id);
		}
	}
	var volume = lengthCalc;
	var price_before= parseFloat(price) + attrib_sum_before;
	document.getElementsByName("price")[0].value = kaufm(price_before);
	document.getElementsByName("calcprice")[0].value= kaufm((volume * price_before) + attrib_sum_after);
}

function getPrice(qty){
	var staffel = document.getElementsByName("staffelid");
	var price = document.getElementsByName("std_price")[0].value;
	
	// staffelpreise
	if(staffel != null){
		for(var x=0; x<staffel.length; x++){
			var tmpstring = (staffel[x]).value.split(":");
			if(qty >= tmpstring[0])
				price = tmpstring[1];
		}
	}
	return price;	
}

function lookupPrice(id){
	var tmpIndex = "priceid" + id;
	var price = document.getElementById("priceid" + id);
	if(price != null){
		return parseFloat(price.value);
	}
	else{
		return 0.0;
	}
}

function convFloat(num){
	num = num.replace(".","");
	num = num.replace(",",".");
	return num;
}	

/************************end configurator calculator************************************/

/***  MOD RM 19-07-2010****************************************************************/

/* Sticky Tooltip script (v1.0)
* Created: Nov 25th, 2009. This notice must stay intact for usage 
* Author: Dynamic Drive at http://www.dynamicdrive.com/
* Visit http://www.dynamicdrive.com/ for full source code
*/


var tooltip={
	tooltipoffsets: [20, - 210], //additional x and y offset from mouse cursor for tooltips
	fadeinspeed: 500, //duration of fade effect in milliseconds
	rightclickstick: true, //sticky tooltip when user right clicks over the triggering element (apart from pressing "s" key) ?
	bordercolors: ["black", "darkred"], //border color of tooltip depending on sticky state
	notice1: ["Press \"s\"", "or right click", "to sticky box"], //customize tooltip status message
	notice2: "Click outside this box to hide it", //customize tooltip status message

	//***** NO NEED TO EDIT BEYOND HERE

	isdocked: false,

	positiontooltip:function($, $tooltip, e){
		var x=e.pageX+this.tooltipoffsets[0], y=e.pageY+this.tooltipoffsets[1]
		var tipw=$tooltip.outerWidth(), tiph=$tooltip.outerHeight(), 
		x=(x+tipw>$(document).scrollLeft()+$(window).width())? x-tipw-(tooltip.tooltipoffsets[0]*2) : x
		y=(y+tiph>$(document).scrollTop()+$(window).height())? $(document).scrollTop()+$(window).height()-tiph-10 : y
		$tooltip.css({left:x, top:y})
	},
	
	showbox:function($, $tooltip, e){
		$tooltip.fadeIn(this.fadeinspeed)
		this.positiontooltip($, $tooltip, e)
	},

	hidebox:function($, $tooltip){
		if (!this.isdocked){
			$tooltip.stop(false, true).hide()
			$tooltip.css({borderColor:'black'}).find('.status:eq(0)').css({background:this.bordercolors[0]}).html(this.notice1)
		}
	},

	docktooltip:function($, $tooltip, e){
		this.isdocked=true
		$tooltip.css({borderColor:'darkred'}).find('.status:eq(0)').css({background:this.bordercolors[1]}).html(this.notice2)
	},


	init:function(targetselector, tipid){
		jQuery(document).ready(function($){
			var $targets=$(targetselector)
			var $tooltip=$('#'+tipid).appendTo(document.body)
			if ($targets.length==0)
				return
			var $alltips=$tooltip.find('div.atip')
			if (!tooltip.rightclickstick)
				tooltip.notice1[1]=''
			tooltip.notice1=tooltip.notice1.join(' ')
			tooltip.hidebox($, $tooltip)
			$targets.bind('mouseenter', function(e){
				$alltips.hide().filter('#'+$(this).attr('data-tooltip')).show()
				tooltip.showbox($, $tooltip, e)
			})
			$targets.bind('mouseleave', function(e){
				tooltip.hidebox($, $tooltip)
			})
			$targets.bind('mousemove', function(e){
				if (!tooltip.isdocked){
					tooltip.positiontooltip($, $tooltip, e)
				}
			})
			$tooltip.bind("mouseenter", function(){
				tooltip.hidebox($, $tooltip)
			})
			$tooltip.bind("click", function(e){
				e.stopPropagation()
			})
			$(this).bind("click", function(e){
				if (e.button==0){
					tooltip.isdocked=false
					tooltip.hidebox($, $tooltip)
				}
			})
			$(this).bind("contextmenu", function(e){
				if (tooltip.rightclickstick && $(e.target).parents().andSelf().filter(targetselector).length==1){ //if oncontextmenu over a target element
					tooltip.docktooltip($, $tooltip, e)
					return false
				}
			})
			$(this).bind('keypress', function(e){
				var keyunicode=e.charCode || e.keyCode
				if (keyunicode==115){ //if "s" key was pressed
					tooltip.docktooltip($, $tooltip, e)
				}
			})
		}) //end dom ready
	}
}

//stickytooltip.init("targetElementSelector", "tooltipcontainer")

tooltip.init("*[data-tooltip]", "tooltip")

/* EOF   MOD RM 19.07-2010***********************************************************/

var containerTag = 'TR';

var compatible = (
	document.getElementById && document.getElementsByTagName && document.createElement
	&&
	!(navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1)
	);

if (compatible)
{
	document.write('<style>.accessibility{display: none}</style>');
	var waitingRoom = document.createElement('div');
}

var hiddenFormFieldsPointers = new Object();

function prepareForm()
{
	if (!compatible) return;
	var marker = document.createElement(containerTag);
	marker.style.display = 'none';

	var x = document.getElementsByTagName('select');
	for (var i=0;i<x.length;i++)
		addEvent(x[i],'change',showHideFields)

	var x = document.getElementsByTagName(containerTag);
	var hiddenFields = new Array;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].getAttribute('rel'))
		{
			var y = getAllFormFields(x[i]);
			x[i].nestedRels = new Array();
			for (var j=0;j<y.length;j++)
			{
				var rel = y[j].getAttribute('rel');
				if (!rel || rel == 'none') continue;
				x[i].nestedRels.push(rel);
			}
			if (!x[i].nestedRels.length) x[i].nestedRels = null;
			hiddenFields.push(x[i]);
		}
	}

	while (hiddenFields.length)
	{
		var rel = hiddenFields[0].getAttribute('rel');
		if (!hiddenFormFieldsPointers[rel])
			hiddenFormFieldsPointers[rel] = new Array();
		var relIndex = hiddenFormFieldsPointers[rel].length;
		hiddenFormFieldsPointers[rel][relIndex] = hiddenFields[0];
		var newMarker = marker.cloneNode(true);
		newMarker.id = rel + relIndex;
		hiddenFields[0].parentNode.replaceChild(newMarker,hiddenFields[0]);
		waitingRoom.appendChild(hiddenFields.shift());
	}
	
	setDefaults();
	addEvent(document,'click',showHideFields);
}

function setDefaults()
{
	var y = document.getElementsByTagName('input');
	for (var i=0;i<y.length;i++)
	{
		if (y[i].checked && y[i].getAttribute('rel'))
			intoMainForm(y[i].getAttribute('rel'))
	}

	var z = document.getElementsByTagName('select');
	for (var i=0;i<z.length;i++)
	{
		if (z[i].options[z[i].selectedIndex].getAttribute('rel'))
			intoMainForm(z[i].options[z[i].selectedIndex].getAttribute('rel'))
	}

}

function showHideFields(e)
{
	if (!e) var e = window.event;
	var tg = e.target || e.srcElement;

	if (tg.nodeName == 'LABEL')
	{
		var relatedFieldName = tg.getAttribute('for') || tg.getAttribute('htmlFor');
		tg = document.getElementById(relatedFieldName);
	}
		
	if (
		!(tg.nodeName == 'SELECT' && e.type == 'change')
		&&
		!(tg.nodeName == 'INPUT' && tg.getAttribute('rel'))
	   ) return;

	var fieldsToBeInserted = tg.getAttribute('rel');

	if (tg.type == 'checkbox')
	{
		if (tg.checked)
			intoMainForm(fieldsToBeInserted);
		else
			intoWaitingRoom(fieldsToBeInserted);
	}
	else if (tg.type == 'radio')
	{
		removeOthers(tg.form[tg.name],fieldsToBeInserted)
		intoMainForm(fieldsToBeInserted);
	}
	else if (tg.type == 'select-one')
	{
		fieldsToBeInserted = tg.options[tg.selectedIndex].getAttribute('rel');
		removeOthers(tg.options,fieldsToBeInserted);
		intoMainForm(fieldsToBeInserted);
	}
}

function removeOthers(others,fieldsToBeInserted)
{
	for (var i=0;i<others.length;i++)
	{
		var show = others[i].getAttribute('rel');
		if (show == fieldsToBeInserted) continue;
		intoWaitingRoom(show);
	}
}

function intoWaitingRoom(relation)
{
	if (relation == 'none') return;
	var Elements = hiddenFormFieldsPointers[relation];
	for (var i=0;i<Elements.length;i++)
	{
		waitingRoom.appendChild(Elements[i]);
		if (Elements[i].nestedRels)
			for (var j=0;j<Elements[i].nestedRels.length;j++)
				intoWaitingRoom(Elements[i].nestedRels[j]);
	}
}

function intoMainForm(relation)
{
	if (relation == 'none') return;
	var Elements = hiddenFormFieldsPointers[relation];
	for (var i=0;i<Elements.length;i++)
	{
		var insertPoint = document.getElementById(relation+i);
		insertPoint.parentNode.insertBefore(Elements[i],insertPoint);
		if (Elements[i].nestedRels)
		{
			var fields = getAllFormFields(Elements[i]);
			for (var j=0;j<fields.length;j++)
			{
				if (!fields[j].getAttribute('rel')) continue;
				if (fields[j].checked || fields[j].selected) 
					intoMainForm(fields[j].getAttribute('rel'));
			}
		}
	}
}

function getAllFormFields(node)
{
	var allFormFields = new Array;
	var x = node.getElementsByTagName('input');
	for (var i=0;i<x.length;i++)
		allFormFields.push(x[i]);
	var y = node.getElementsByTagName('option');
	for (var i=0;i<y.length;i++)
		allFormFields.push(y[i]);
	return allFormFields;
}

/** ULTRA-SIMPLE EVENT ADDING **/

function addEvent(obj,type,fn)
{
	if (obj.addEventListener)
		obj.addEventListener(type,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent("on"+type,fn);
}

addEvent(window,"load",prepareForm);


/** PUSH AND SHIFT FOR IE5 **/

function Array_push() {
	var A_p = 0
	for (A_p = 0; A_p < arguments.length; A_p++) {
		this[this.length] = arguments[A_p]
	}
	return this.length
}

if (typeof Array.prototype.push == "undefined") {
	Array.prototype.push = Array_push
}

function Array_shift() {
	var A_s = 0
	var response = this[0]
	for (A_s = 0; A_s < this.length-1; A_s++) {
		this[A_s] = this[A_s + 1]
	}
	this.length--
	return response
}

if (typeof Array.prototype.shift == "undefined") {
	Array.prototype.shift = Array_shift
}


