function goto(url) 
{
	document.location.href = document.getElementsByTagName('base')[0].href + url;
}

function enableZipcodeLookup(source, target)
{
	if($(source) && $(target))
	{				
		$(source).observe('change', function(event) {
			new Ajax.Request('/de/privatpersonen/preis_und_online_abschluss/ajax=getCity', {
			 	method: 'post',
				parameters: { zipcode: $(source).value },
				onSuccess: function(transport) {
					if(transport.responseText != '') $(target).value = transport.responseText;
				}
			});
		});
	}
}

Array.prototype.removeByValue = function(value)
{
	if(value)
	{
		var counter = 0;
		var array = this;
		this.each(function(element) {
			if(element == value) array.splice(counter, 1);		
		
			counter++;
		});
	}
}

/* acronym */
function acronym (word, popupId)
{
	myLightWindow.activateWindow({
		title: word,
		href: "#" + popupId,
		type: 'inline'
	});	
}

/* DAS */
var activeQuestionObject 	= null;
var questionIds 			= Array ();
var questionIdsIndexes 		= Array ();
var additions = [];
var groups = [];
var myLightWindow;
var previous_costs = 0;
var popup_lower_costs = false;
var skip_questions = Array ();

function DasTip(tip)
{
	Tip(tip, WIDTH, 200, PADDING, 10, BGCOLOR, '#FEFFED', BORDERCOLOR, '#E4E393', DELAY, 200);
}

function checkLength(self, maxLen)
{
	if(self.value.length >= maxLen) 
	{		
		self.value = self.value.substring(0, maxLen);
	}
	else 
	{
		$(self.parentNode).select("span.counter")[0].update(maxLen - self.value.length - 1);
	}
}

/* CUSTOM QUESTION FUNCTION */
function questionCheckerForPrivateTrafficSixAndSeven(action)
{
	var questionSix = getAnswerByQuestion($('question_6'));
	var questionSeven = getAnswerByQuestion($('question_7'));
	
	if(questionSix == 2 && questionSeven == 2) 
	{
		if(action == 'submit') 
		{
			myLightWindow.activateWindow({
				href: '#popup-keine-kombinierte-versicherung',
				title: locale_warning,
				type: 'inline'
			});
		}
		return false;
	}
	else return true;
}

/* DAS MODULE */

function submitForm(self)
{
	var form = self.parentNode.parentNode.parentNode;
	var popup = form.parentNode;

	new Ajax.Updater(
		popup, 
		form.action,
		{ parameters: form.serialize(true) }
	);
}

function calculateDiscount(value)
{
	return (value - (value * phpDiscounts[currentDiscount]));
}

function initQuestionButtons ()
{
	var questions = $$("div.question");
	
	for (var i = 0; i < questions.length; i++)
	{
		questions[i].select("input.weiter-button")[0].observe('click', weiterButtonMouseClick);
		questions[i].select("input[type=radio]").each(function (element) { 
			element.observe('click', makeClickableNext); 
		});
		
		if(hasValues(questions[i])) 
		{
			makeInActive(questions[i]);
		}
		
		questionIds[questions[i].id] = i;
		questionIdsIndexes[i] = questions[i].id;
		
		if (i == 0) activeQuestionObject = questions[i];
	}
	
	$('mod-das-footer').select("input.zusatz_checkbox[type=checkbox]").each(function (element) { 
		element.observe('click', changeAddition); 
	});
	
	$('price').observe('change', changePrice); 
	$('group').observe('change', changeGroup); 
	$('student').observe('click', changeDiscount); 
	
	$('mod-das-submit').enable();
}

function changeAddition(event)
{
	var previous_costs = 0;
	additions.each(function(addition) {
		previous_costs += calculateDiscount(parseFloat(phpAdditions[addition]['price'][currentGroup]));
	});
	
	var addition = getRealId(Event.element(event).id);
	
	additions.removeByValue(addition);
	if(Event.element(event).checked)
	{
		additions[additions.length] = addition;
	}
	
	calculateCosts(false);
	
	var new_costs = 0;
	additions.each(function(addition) {
		new_costs += calculateDiscount(parseFloat(phpAdditions[addition]['price'][currentGroup]));
	});
	if (!popup_lower_costs && new_costs < previous_costs)
	{
		//popup_lower_costs = true;
		myLightWindow.activateWindow({
			href: '#popup-auswahl-angepasst',
			title: locale_warning,
			type: 'inline'
		});
	}
}

function changePrice(event)
{
	var previous_costs = calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][currentGroup]));
	
	currentPrice = Event.element(event).value;
	calculateCosts();
	
	var new_costs = calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][currentGroup]));
	if (!popup_lower_costs && new_costs < previous_costs)
	{
		//popup_lower_costs = true;
		myLightWindow.activateWindow({
			href: '#popup-auswahl-angepasst',
			title: locale_warning,
			type: 'inline'
		});
	}
}

function changeGroup(event)
{
	var previous_costs = calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][currentGroup]));
	
	currentGroup = Event.element(event).value;
	calculateCosts();
	
	if(currentGroup == 1) $('basic-warning').show();
	else $('basic-warning').hide();
	
	var new_costs = calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][currentGroup]));
	if (!popup_lower_costs && new_costs < previous_costs)
	{
		//popup_lower_costs = true;
		myLightWindow.activateWindow({
			href: '#popup-auswahl-angepasst',
			title: locale_warning,
			type: 'inline'
		});
	}
}

function changeDiscount(event)
{
	currentDiscount = (Event.element(event).checked ? 'student' : 'default');
		
	if(currentDiscount == 'student')
	{
		$('discount-student').show();
		$('discount-student-disabled').hide();
	}
	else 
	{
		$('discount-student').hide();
		$('discount-student-disabled').show();
	}
	
	//$('discount').update(phpDiscounts[currentDiscount] * 100);
	
	calculateCosts();
}

function getAnswerByQuestion(questionObj)
{
	var answer;
	
	inputObjs = questionObj.select("input");
	for (var i = 0; i < inputObjs.length; i++)
	{
		if (inputObjs[i].type != "submit")
		{
			if (inputObjs[i].checked)
			{
				answer = inputObjs[i].value;
			}
		}
	}
	
	return answer;
}

function parseCustomJavascriptForQuestion(questionObj, action)
{
	var id = getRealId(questionObj.id);
	var answer;
	
	var result = true;
	
	var answer = getAnswerByQuestion(questionObj);
	if (answer > 0)
	{
		if(phpQuestions[id]['answers'][answer]['javascript'])
		{
			eval('result = ' + phpQuestions[id]['answers'][answer]['javascript'] + '("' + action + '");');
		}
		
		if(action == "submit" && phpQuestions[id]['answers'][answer]['popup'])
		{
			myLightWindow.activateWindow({
				href: phpQuestions[id]['answers'][answer]['popup']['id'],
				title: phpQuestions[id]['answers'][answer]['popup']['title'],
				type: phpQuestions[id]['answers'][answer]['popup']['type'],
				customDeactivateFunction: phpQuestions[id]['answers'][answer]['popup']['deactivate']
			});
		}
				
		if(phpQuestions[id]['answers'][answer]['stop'] == 1) result = false;
	}
	
	return result;
}


function parseQuestion(question)
{
	var id = getRealId(question);
	var obj = $(question);
	
	var result = true;
	
	var answer = getAnswerByQuestion(obj);
	if (answer > 0)
	{
		groups[id] = null;
		
		if(phpQuestions[id]['answers'][answer]['redirect'])
		{
			document.location.href = document.getElementsByTagName('base')[0].href + phpQuestions[id]['answers'][answer]['redirect'];
		}
		
		if(phpQuestions[id]['answers'][answer]['discount'])
		{
			currentDiscount = phpQuestions[id]['answers'][answer]['discount'];
			
			if(currentDiscount == 'student')
			{
				$('discount-student').show();
				$('discount-student-disabled').hide();
				$('student').checked = true;
			}
			else 
			{
				$('discount-student').hide();
				$('discount-student-disabled').show();
				$('student').checked = false;
			}
			
			//$('discount').update(phpDiscounts[currentDiscount] * 100);
		}
		
		activeQuestionObject.select("span.question-answer")[0].update(phpQuestions[id]['answers'][answer]['title']);
		
		//additions.removeByValue(phpQuestions[id]['answers'][answer]['addition']);
		if(phpQuestions[id]['answers'][answer]['addition'] > 0)
		{
			additions[additions.length] = phpQuestions[id]['answers'][answer]['addition'];
		}
		else if(phpQuestions[id]['answers'][answer]['remove_addition'] > 0)
		{
			additions.removeByValue(phpQuestions[id]['answers'][answer]['remove_addition']);
			$('zusatz_' + phpQuestions[id]['answers'][answer]['remove_addition']).checked = false;
		}
		
		if(phpQuestions[id]['answers'][answer]['price'] > 0)
		{
			currentPrice = phpQuestions[id]['answers'][answer]['price'];
		}
		
		if(phpQuestions[id]['answers'][answer]['group'] > 0)
		{		
			groups[id] = phpQuestions[id]['answers'][answer]['group'];
		}
			
		first = true;
		for (i in groups) 
		{ 
			if (groups[i] > 0) 
			{
				if(first) currentGroup = groups[i];
				else
				{
					if(groups[i] > currentGroup) currentGroup = groups[i];
				}
				first = false;
			}
		}
		
		if(currentGroup == 1) $('basic-warning').show();
		else $('basic-warning').hide();
		
		if(phpQuestions[id]['answers'][answer]['popup'])
		{
			myLightWindow.activateWindow({
				href: phpQuestions[id]['answers'][answer]['popup']['id'],
				title: phpQuestions[id]['answers'][answer]['popup']['title'],
				type: phpQuestions[id]['answers'][answer]['popup']['type'],
				customDeactivateFunction: phpQuestions[id]['answers'][answer]['popup']['deactivate']
			});
		}
		
		if(phpQuestions[id]['answers'][answer]['stop'] == 1) result = false;
			
		if(phpQuestions[id]['answers'][answer]['skip'])
		{
			skip_questions[phpQuestions[id]['answers'][answer]['skip']['question']] = true;
			
			$('question_' + phpQuestions[id]['answers'][answer]['skip']['question']).addClassName ("question-done");
			$('question_' + phpQuestions[id]['answers'][answer]['skip']['question']).select("h2")[0].observe('mouseover', questionMouseOver);
			$('question_' + phpQuestions[id]['answers'][answer]['skip']['question']).select("h2")[0].observe('mouseout', questionMouseOut);
			$('question_' + phpQuestions[id]['answers'][answer]['skip']['question']).select("h2")[0].observe('click', questionMouseClick);
			$('question_' + phpQuestions[id]['answers'][answer]['skip']['question']).select("span.question-answer")[0].update(
				phpQuestions[phpQuestions[id]['answers'][answer]['skip']['question']]['answers'][phpQuestions[id]['answers'][answer]['skip']['answer']]['title']
			);
			$('question_' + phpQuestions[id]['answers'][answer]['skip']['question'] + '_' + phpQuestions[id]['answers'][answer]['skip']['answer']).checked = true;
		}
		
		calculateCosts();
	}
	
	return result;
}

function calculateCosts(allow_addition_check)
{
	var costs = 0;
	
	if(allow_addition_check == null) allow_addition_check = true;
		
	$('price').selectedIndex = currentPrice - 1;
	
	$('group').descendants().each(function (item) {
		item.remove();
	});
	
	// CALCULATE BASE
	costs = calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][currentGroup]));
	
	$('group').insert('<option value="1">' + phpGroups[1]['title'] + ' (CHF ' + commaFormatted(currencyFormatted(calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][1])))) + ' ' + locale_yearly + ')</option>');
	$('group').insert('<option value="2">' + phpGroups[2]['title'] + ' (CHF ' + commaFormatted(currencyFormatted(calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][2])))) + ' ' + locale_yearly + ')</option>');
	$('group').insert('<option value="3">' + phpGroups[3]['title'] + ' (CHF ' + commaFormatted(currencyFormatted(calculateDiscount(parseFloat(phpPrices[currentPrice]['price'][3])))) + ' ' + locale_yearly + ')</option>');
	$('group').selectedIndex = currentGroup - 1;
		
	$$('input.zusatz_checkbox').each(function (item) {
		if(allow_addition_check) item.checked = false;
		
		var addition = getRealId(item.id);
		$(item.id + '_price').update(commaFormatted(currencyFormatted(calculateDiscount(parseFloat(phpAdditions[addition]['price'][currentGroup])))));
	});
		
	// CALCULATE ADDITIONS
	additions.each(function(addition) {
		costs += calculateDiscount(parseFloat(phpAdditions[addition]['price'][currentGroup]));
		
		if(allow_addition_check) $('zusatz_' + addition).checked = true;
	});
	
	$('mod-das-group').update(phpGroups[currentGroup]['title']);
	$('mod-das-costs').update(commaFormatted(currencyFormatted(costs)));
	
	if(previous_costs != costs) 
	{
		new Effect.Highlight('mod-das-footer-right', { 
			startcolor: '#72b941',
			endcolor: '#418512',
			restorecolor: '#418512'
		});	
	}
	
	previous_costs = costs;
}

function weiterButtonMouseClick (e)
{
	var element = e.element();
	
	if (hasValues(activeQuestionObject) && parseCustomJavascriptForQuestion(activeQuestionObject, 'submit')) makeActiveNext();
}

function questionMouseOver (e)
{
	var element = e.element();
	element.addClassName("mouseover");
}

function questionMouseOut (e)
{
	var element = e.element();
	element.removeClassName("mouseover");
}

function questionMouseClick (e)
{
	var element = e.element();		
	
	if(element.hasClassName('question-answer')) element = element.parentNode;
	
	if(element.parentNode.id) 
	{
		if(hasValues(element.parentNode))
		{
			if(!element.parentNode.hasClassName('question-active'))
			{
				parseQuestion(activeQuestionObject.id);
				makeActive (element.parentNode, true);
			}
		}
		else 
		{
			parseQuestion(activeQuestionObject.id);
			makeActive (element.parentNode);
		}
	}
}

function makeActive (obj, force)
{
	if (force || obj != activeQuestionObject)
	{
		if (activeQuestionObject && obj != activeQuestionObject) makeInActive (activeQuestionObject);
	
		activeQuestionObject = obj;	
	
		obj.addClassName("question-active");

		if(obj.select("div.question-text")[0].id) Effect.SlideDown(obj.select("div.question-text")[0].id, { duration: 0.5 });	
	}
}

function makeClickableNext ()
{
	var active_id = activeQuestionObject.id;
	var active_id_index = questionIds[active_id];
	
	active_id_index++;
		
	if (hasValues(activeQuestionObject) && parseCustomJavascriptForQuestion(activeQuestionObject, 'change') && active_id_index < questionIdsIndexes.length)
	{
		$(questionIdsIndexes[active_id_index]).select("h2")[0].observe('click', questionMouseClick);
		$(questionIdsIndexes[active_id_index]).select("h2")[0].observe('mouseover', questionMouseOver);
		$(questionIdsIndexes[active_id_index]).select("h2")[0].observe('mouseout', questionMouseOut);
	}
}

function makeClickableOrder()
{
	//$("mod-das-submit").enable();
}

function makeActiveNext (force)
{
	var active_id = activeQuestionObject.id;
	var active_id_index = questionIds[active_id];
	
	active_id_index++;
	
	if(force || parseQuestion(active_id))
	{	
		if(force) calculateCosts();

		if (active_id_index >= questionIdsIndexes.length)
		{
			makeInActive (activeQuestionObject);
			makeClickableOrder();
			
			activeQuestionObject = null;
		}
		else
		{
			var question_id = getRealId(questionIdsIndexes[active_id_index]);
			
			if(skip_questions[question_id]) active_id_index++;

			makeActive ($(questionIdsIndexes[active_id_index]));
		}
	}
}

function getRealId (htmlId)
{
	htmlId = htmlId.split("_");
	if (htmlId[1]) return htmlId[1];
	else return false;
}

function hasValues (obj)
{
	inputObjs = obj.select("input");
	var hasValues = false;
	
	for (var i = 0; i < inputObjs.length; i++)
	{
		if (inputObjs[i].type != "submit")
		{
			if (inputObjs[i].checked)
			{
				hasValues = true;
			}
		}
	}
	
	return hasValues;
}

function makeInActive (obj)
{
	if (hasValues(obj)) 
	{
		obj.addClassName ("question-done");
		obj.select("h2")[0].observe('mouseover', questionMouseOver);
		obj.select("h2")[0].observe('mouseout', questionMouseOut);
		obj.select("h2")[0].observe('click', questionMouseClick);
		
		var id = getRealId(obj.id);
		var answer = getAnswerByQuestion(obj);
		obj.select("span.question-answer")[0].update(phpQuestions[id]['answers'][answer]['title']);
	}
	
	obj.removeClassName("question-active");
	if(obj.select("div.question-text")[0].id && obj.select("div.question-text")[0].visible()) Effect.SlideUp(obj.select("div.question-text")[0].id, { duration: 0.2 });
}

function checkAllQuestions ()
{
	var completed = true;
	
	$$("div.question").each(function(element) {
		if(!hasValues(element)) completed = false;
	});

	return completed;
}

function currencyFormatted (amount)	
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

function commaFormatted (amount) 
{
	var delimiter = "."; // replace comma if desired
	var a = amount.split('.',2);
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	//else if (d == '00') { amount = n + '.-'; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}