/*jslint evil: true, undef: false */
/*global $,log,app,style,svc,ml,confmodell,modeldisplayCtrl,layoutManager */
/*global stat,fabrikat,stat_log_cc3_exit,stat_log_cc3,tb_show */
/*global behaviourFn*/

function behaviour(action, param){
	var fn = behaviourFn(action);
	fn(param);
}

// Actions automatische mit Elementen verbinden
function behaviourFn(action){
	var expr = '', camelize = false;

	if (action.charAt(6) !== '_' && action.charAt(6) !== '-') {
		expr = action;
	} else {
		for(var i=0; i<action.length; i++) {
			if(action.charAt(i) === '_' || action.charAt(i) === '-') {
				camelize = true;
				continue;
			}

			if(camelize) {
				expr += action.charAt(i).toUpperCase();
				camelize = false;
			} else {
				expr += action.charAt(i).toLowerCase();
			}
		}
	}
	var fn = eval('(typeof ' + expr + ' === "function")?' + expr + ':null');
	if (fn) {
		return fn;
	} else {
		if (typeof console !== "undefined") {
			console.log("Error in behaviourFn('" + action + "'): No function with name " + expr + " alvailable.");
		}
		return function(){};
	}
}

// globale Variablen
var state = {};
state.criteriaActive = false;
state.ansicht = 'pre-init';
var $listenansicht = false;

var modellbildMgr = null;

var modellData = [];
var newOpt = {};
var actAustVar = '';
var text_reset = '';

var marke_login = '';

var porsche_merkliste = false;

// initialization code
function cc3Initialize(options) {
    $('[id^=action]').click(function(){behaviour(this.id);});
    if(options.updateModellData)
    {
		$.getJSON(svc.modellData, function(json) {
			modellData = json;
			$.getJSON(svc.modellCrit, function(crit) {
				cbModellCritOnLoad(crit);
				cc3Startup();
			});
		});
    } else {
    	cc3Startup();
    }

	state.ansicht = 'init';

	// statische Info-Links laden
	$("#header_box").load(svc.statlinks, function() {
		// statistics
		$('#action_show_legal_info').click(function(){stat_log_cc3_exit(stat.text_legal_info);});
		$('#action_show_imprint_info').click(function(){stat_log_cc3_exit(stat.text_imprint_info);});
	});
}

// actions
function actionPrint() {
	print();

	// statistics
	stat_log_cc3_exit(stat.text_print);
}

//Aktion: Cabrio Verdeck oeffnen (Audi)
function actionOpenCabrio() {
	modeldisplayCtrl.setCabrioRoofOpen(true);
}

// Aktion: Cabrio Verdeck schliessen (Audi)
function actionClosedCabrio() {
	modeldisplayCtrl.setCabrioRoofOpen(false);
}

//Aktion: Cabrio Verdeck oeffnen (Audi, grosses Bild)
function actionOpenCabrio2() {
	modeldisplayCtrl.setCabrioRoofOpen(true);
}

// Aktion: Cabrio Verdeck schliessen (Audi, grosses Bild)
function actionClosedCabrio2() {
	modeldisplayCtrl.setCabrioRoofOpen(false);
}

// Aktion: Unterseite mit der Serienausstattung laden
function actionSerie() {
	showWait();
	$("#nav_back_serie").addClass('enabled');
	$("#nav_back_serie").unbind().bind('click',function(){
		$("#modell_serie_big").addClass('remove_it');
		$("#rundherum").removeClass('hide_it');
		$("#navigation").removeClass('hide_it');
		$("#modell_serie_text").children().remove();	// remove HTML-content (does not need be rendered if not visible, will be reloaded again anyway)
		if (style.isPorsche) {
			$("#layercdr").removeClass('hide_it');
		}
		layoutManager.resetState();
		layoutManager.doLayout();
		layoutManager.updateInfoSize();
	});
	var callserie = getConfiguratorURL("cc3serie.txt");
	$.get(callserie, function(data) {
		$("#modell_serie_text").html(data);
	});
	$("#rundherum").addClass('hide_it');
	$("#navigation").addClass('hide_it');
	$("#modell_serie_big").removeClass('remove_it').removeClass("ausvgl");

    // statistics
    stat_log_cc3(stat.step_serie, false);
}

// Aktion: fuer Porsche Lightbox mit gewaehlten Ausstattungen und Farben anzeigen
function actionShowGewaehlteAusstattungen() {
	var callshowaust = getConfiguratorURL("cc3farbeaust.htm");
	var lightboxParams = 'TB_iframe=true';
	callshowaust += lightboxParams;
	tb_show(null, callshowaust, false); // lightbox - direct invocation	
}

// Aktion: Unterseite mit der Ausstattungsvergleich laden
function actionAusstattungVgl() {
	showWait();
	$("#nav_back_serie").addClass('enabled');
	$("#nav_back_serie").unbind().bind('click', backClickAusstattungVgl);
	if (actAustVar !== '') {	
		loadAusstattungVgl('AUV=' + actAustVar);
	} else if ($("input:radio[name='modellcode']:checked").val()) {
		var modellInfo = getModellInfo(confmodell.modellcode);
		confmodell.setAusstattungsvar(modellInfo.av);
		loadAusstattungVgl('AUV=' + confmodell.ausstattungsvar);
	} else { 
		loadAusstattungVgl();
	}
	$("#rundherum").addClass('hide_it');
	$("#navigation").addClass('hide_it');
	$("#modell_serie_big").removeClass('remove_it').addClass("ausvgl");

    // statistics
    stat_log_cc3(stat.step_ausvgl, false);
}

function loadAusstattungVgl(ausvglParams) {
	var callausvgl = svc.austvgl_link;
	callausvgl = callausvgl.replace('$imofab$', confmodell.fabrikat);
	callausvgl = callausvgl.replace('$imoimg$', confmodell.modellgruppe);
	if (ausvglParams)
	{	callausvgl += '?' + ausvglParams + '&STYLE=' + style.value + '&FAB=' + fabrikat;
	}
	else
	{	callausvgl += '?STYLE=' + style.value + '&FAB=' + fabrikat;
	}
	$.get(callausvgl, function(data) {
		$("#modell_serie_text").html(data);
	});
}

function backClickAusstattungVgl() {
	$("#modell_serie_big").addClass('remove_it');
	$("#rundherum").removeClass('hide_it');
	$("#navigation").removeClass('hide_it');
	$("#modell_serie_text").children().remove();	// remove HTML-content (does not need be rendered if not visible)
	layoutManager.resetState();
	layoutManager.doLayout();
	layoutManager.updateInfoSize();
}

// Aktion: Car Configurator neu starten
function actionNewConf() {
	if(style.isPorsche) {
		location.href = porsche_link;
	}
	else {
		var newconf = svc.cc3Base;
		if (login_ticket) {
			newconf = newconf + "&ticket=" + login_ticket;
		}
		location.href = newconf;
	}
}

// Aktion: Angebot drucken (PDF)
function actionAngebotPrint() {
	var callshowaust = getConfiguratorURL("cc3angebotausdruck.htm");
	var lightboxParams = 'TB_iframe=true&height=270&width=350&modal=true';
	callshowaust += lightboxParams;
	tb_show(null, callshowaust, false);
}

function actionAusvglpdfPrint(URL){
	var pdfWin = openWindow(URL, 'pdfDruck', 'resizable=yes,scrollbars=no,width=950,height=650,screenX=50,screenY=50');
	pdfWin.window.focus();
}

function actionChoicePrint(picture, serie, maus, technicaldata){
	var pdfURL = getAngebotPrintURL(svc.nwapp, getPbvSessionURL());
	// + ... showpicture + showserie + showmaus + technicaldata
	pdfURL += "%26showpicture%3D"+picture+"%26showserie%3D"+serie+"%26showmaus%3D"+maus+"%26showtechnicaldata%3D"+technicaldata;
	var pdfWin = openWindow(pdfURL, 'pdfDruck', 'resizable=yes,scrollbars=no,width=950,height=650,screenX=50,screenY=50');
	pdfWin.window.focus();

	// statistics
	stat_log_cc3_exit(stat.text_print_pdf);
}

// URL fuer Angebot drucken (PDF)
function getAngebotPrintURL(nwappURL, pbvSessURL) {
	var xhtml2pdfURL = '';
	if (pbvSessURL !== '')
	{	// Finanzierungs-Infos wurden abgespeichert
		xhtml2pdfURL = pbvSessURL + '&FRAME=cc3pdf.xml';
	}
	else
	{	// cc3angebot.txt: keine speziellen Finanzierungs-Infos vorhanden
		xhtml2pdfURL = getConfiguratorURL("cc3pdf.xml");
	}
	return nwappURL + '?SVC=XHTML2PDF&XMLURL=' + escape(xhtml2pdfURL);
}

function actionPictureBig() {
	modeldisplayCtrl.changeDisplayBig();
}

// Aktion: Ansicht Trichter Bilder laden
function actionContentBildansicht() {
	$listenansicht = false;
	$("#content").load(svc.modellBildansicht, null, cbModellBildOnLoad);
	state.ansicht = 'bild';
	if (style.isSkoda)
	{
		$("#navigation").show();
		$("#subnavigation").hide();
	}
	else
	{	$("#navigation").hide();
	}

	// statistics - reset values
	confmodell.setModellgruppe('');
	confmodell.setBezeichnung('');

    // statistics
    stat_log_cc3(stat.step_einstieg_modelle);

    // twyn Statistik
    if (twyn && !style.isLnf) {
		writeTwynStatistic("Startseite_carC", true);
	}
}

// Aktion: Ansicht Trichter Liste laden
function actionContentListenansicht() {
	showWait();
	$("#content").load(svc.modellListenansicht, null, cbModellListeOnLoad);
	state.ansicht = 'liste';
	updateNavButtons();

	// statistics
	stat_log_cc3(stat.step_einstieg_liste);
}


// Aktion: Ansicht laden Trichter Modellgruppe gewaehlt
function actionContentModellansicht(mgn, fromListe) {
	showWait();
	state.ansicht = 'modell';
	$("#info_text_picture").removeClass('remove_it');

	var modellgruppe = getModelgruppe(mgn);
	confmodell.setModellgruppe(mgn);
	confmodell.setFabrikat(modellgruppe.fab);
	$("#content").load(svc.modellListenansichtMgn.replace('%mgn%', mgn).replace('%fab%', confmodell.fabrikat), null, cbModellListeOnLoad);

	var sliderMinValue;
	var sliderMaxValue;

	newOpt = [];

	for(var s in sliders) {
		var slider = sliders[s];
		var actStepping;
		switch(slider.name) {
			case "imoprsb":
				mgMinValue = (Math.floor(modellgruppe.imoprsb[0]/1000)*1000);
				mgMaxValue = (Math.ceil(modellgruppe.imoprsb[1]/1000)*1000);
				actStepping = (country === "hu") ? 50000 : 500;
				break;
			case "itdvb3":
				mgMinValue = (Math.floor(modellgruppe.itdvb3[0]));
				mgMaxValue = (Math.ceil(modellgruppe.itdvb3[1]));
				actStepping = 0.1;
				break;
			case "imokw":
				mgMinValue = (Math.floor(modellgruppe.imokw[0]/10)*10);
				mgMaxValue = (Math.ceil(modellgruppe.imokw[1]/10)*10);
				actStepping = 5;
				break;
			case "imops":
				mgMinValue = (Math.floor(modellgruppe.imops[0]/10)*10);
				mgMaxValue = (Math.ceil(modellgruppe.imops[1]/10)*10);
				actStepping = 5;
				break;
			default:
				break;
		}
		var sliderValues = $(slider.selector).slider('values');
		sliderValues[1] += slider.step;

		if (sliderValues[0] > mgMinValue && !fromListe) {
			sliderMinValue = sliderValues[0];
		} else {
			sliderMinValue = mgMinValue;
		}

		if (sliderValues[1] < mgMaxValue && !fromListe) {
			sliderMaxValue = sliderValues[1];
		} else {
			sliderMaxValue = mgMaxValue;
		}

		newOpt.push({
			name: slider.name,
			minValue: mgMinValue,
			maxValue: mgMaxValue,
			min: sliderMinValue,
			max: sliderMaxValue,
			step: actStepping
		});
	}
	// Kriterien (Checkboxen) aktualisieren
	updateCheckboxes(modellgruppe);
	// Slider nicht aktualisieren wenn nur ein Modell vorhanden, weil min, max Wert bei einem Modell
	// nicht umzusetzen sind
	if (modellgruppe.modelle.length > 1) {
		// Slider-Grenzen neu definieren
		sliderReconfigure(newOpt);
	}
	// Dropdow-LNF aktualisieren
	if (fabrikat === 'L') {
		updateDropDown(modellgruppe);
	}
	// Modelliste neu-laden
	actionUpdateFromCriteria();
	// Nagivations-Buttons aktualisieren
	updateNavButtons();
	
	// Zurueck zur Einstiegsseite fuer VU ausblenden
	if (app.isVU) { 
		$("#nav_back").addClass('hide_it'); 
	}

	confmodell.setBezeichnung(getModelgruppeBez());
	updateHeadline();
	// statistics 
	stat_log_cc3(stat.step_modellgruppe);

	// twyn Statistik
	if (twyn && !style.isLnf) {
		writeTwynStatistic("Modellauswahl_carC", false, confmodell.bezeichnung);
	}
}

// Aktion: Kriterien zurueck setzen
function actionResetCriteria() {
	if (state.ansicht === 'liste')
	{
		showWait();
		$('#criteria').html('');
		$.getJSON(svc.modellCrit, cbModellCritOnLoad);
		actionContentListenansicht();
		resetCheckboxes();
		filterListenansicht(extractModellCriteria());
	}
	else if (state.ansicht === 'modell')
	{
		// Werte auf den Ursprung ruecksetzen
		sliderReconfigure(newOpt);
		resetCheckboxes();
		filterModellansicht(extractModellCriteria(),confmodell.modellgruppe);
	}
	else if (state.ansicht === 'bild') {
		actionReset();
	}
}

// Aktion: Car Configurator neu starten
function actionReset() {
	actionNewConf();
}

// Aktion Ansicht aktualisieren - je nach State
function actionUpdateFromCriteria() {
	state.criteriaActive = true;
	// get criteria
	var criteria = extractModellCriteria();
	// apply filter
	if (state.ansicht === 'bild'){
		filterBildansicht(criteria);
	}
	else if (state.ansicht === 'liste') {
		showWaitDiv();
		filterListenansicht(criteria);
	}
	else if (state.ansicht === 'modell') {
		filterModellansicht(criteria, confmodell.modellgruppe);
		addModellPicture();
		modeldisplayCtrl.setup();
	}
}

function updateHeadline(){
	if (style.isGA) {
		return;
	}
	
	// Headline Image
	if(style.isAudi){
		if(app.isShowroom) {
			return;
		}
		
		if (state.ansicht === 'bild' || state.ansicht === 'liste') {
			$("#headline_image").attr('src', svc.stat_images_lang + "header.gif");
		} else { 
			$("#headline_image").attr('src', svc.stat_images_lang + "header_cc.gif");
		}
	} else {
		$("#headline_image_rendered_text").attr('src',(svc.headline_link + ml.cc3Fab_text_cc));				
	}
	
	// Headline Image Zusatz
	if(confmodell.bezeichnung){
		if (style.isSeat) {
			loadHeadlineImageZusatzSeat();
		} else {
			loadTextFromLanguageRessource('cc3.your', function(jsonText) {
				$("#headline_image_zusatz").attr('src',(svc.headline_link + jsonText + " " + confmodell.bezeichnung + "."));
				$("#headline_image_zusatz").show();
			});
		}
	} else {
		if (style.isSeat) {
			$("#headline_image_zusatz").hide();
		} else {
			$("#headline_image_zusatz_seat").hide();
		}
	}
}

function loadHeadlineImageZusatzSeat(){
	loadTextFromLanguageRessource('cc3.your', function (jsonText) {
		$("#headline_image_zusatz_seat").attr('src',(svc.headline_link + escape(jsonText) + " " + escape(confmodell.bezeichnung) + "."));
		$("#headline_image_zusatz_seat").show();
	});
}

//Aktion: Modell-Bild anzeigen 
function addModellPicture() {
	if (app.isShowroom || style.isPorsche) {
		return;
	}
	
	// Info-Bild verstecken
	$("#info_picture").hide();
	
	// Box gross machen 
	$("#info_box").addClass('big');
	$(".info").addClass('big');
	$(".info_header").addClass('big');
	$(".info_box").addClass('big');	
	
	// Modellbild anzeigen
	$("#info_header_big-div").show();
}

// Aktion: Modell-Bild entladen 
function removeModellPicture() {
	// Modellbild verstecken
	$("#info_header_big-div").hide();	
	
	// Box klein machen
	$("#info_box").removeClass('big');
	$(".info").removeClass('big');
	$(".info_header").removeClass('big');
	$(".info_box").removeClass('big');	
	
	// Info-Bild anzeigen
	$("#info_picture").show();	
}

// Aktion: Update nach Auswaehlen mit Dropdown-Box - Ausstattungsvariante
function actionContentAuswahlOnChange(value) {
	showWait();
	actAustVar = value;
	// Filter zuruecksetzen wenn der erste Eintrag ausgewaehlt wurde
	if (value === '') {
		$("#content_main thead").removeClass('remove_it');
		$("#content_main tbody").removeClass('remove_it');
		// Update der Modell-Liste durchfuehren, Ueberschriften ausblenden
		filterModellansicht(extractModellCriteria(),confmodell.modellgruppe);
	}
	else
	{
		var head, body;
		if (state.ansicht === 'liste') {
			head = '#head_mg_' + value;
			body = '#body_mg_' + value;
		} else if (state.ansicht === 'modell') {
			head = '#head_av_' + value;
			body = '#body_av_' + value;
		}
		$("#content_main thead").hide();
		$("#content_main tbody").hide();
		// Ersetzen von Sonderzeichen die Probleme mit den JQuery Selektoren bereiten!
		head = replaceWeirdChars(head);
		body = replaceWeirdChars(body);
		$(head).show();
		$(body).show();
		$(".modell_list_header").show();
		// vorher gewaehlten Radio-Button deaktivieren
		$("input:radio[name='modellcode']").attr('checked','');
		// Bild bei Ausstattungvariante Vorselektion sofort anzeigen
		var idhelp = "body_av_"+value;
		var radiohelp= "#"+ $("tbody[id="+idhelp+"] input:first").attr("id");
		$(radiohelp).click();
	}
	layoutManager.updateInfoSize();
	hideWait();
}

// Aktion: Update nach Auswaehlen mit Dropdown-Box - Modellgruppe
function actionContentAuswahlMgOnChange(mgn) {
	showWait();
	// zuruecksetzen der Ausstattungsvariante, da ja eine neue Modellgruppe gewaehlt wird
	actAustVar = '';
	if (mgn === '') {
		updateHeadline();
		removeModellPicture();
		
		$('#criteria').html('');
	    reinitialiseId();
		$.getJSON(svc.modellCrit, cbModellCritOnLoad);
		actionContentListenansicht();
	}
	else {
		state.ansicht = 'modell';
		confmodell.setModellgruppe(mgn);
		confmodell.setBezeichnung($('#select_modell option:selected').text());
		actionContentModellansicht(mgn,true);
		$listenansicht = true;
		
		updateHeadline();
		addModellPicture();
		modeldisplayCtrl.refresh();
		
	}
	layoutManager.updateInfoSize();
	hideWait();
}

// Lightbox-Optionen zu Aufruf ergaenzen
function updateLinkLegalInfo() {
	$old_link = ($("#action_show_legal_info").attr("href"));
	$new_link = svc.rechtliches_cc + "?" + $old_link;
	$("#action_show_legal_info").attr("href", $new_link);
}


// baue Standard-Kriterien
function cbModellCritOnLoad(jsonCriteria) {
	buildModellCriteriaPanel(jsonCriteria, actionUpdateFromCriteria);
    state.criteriaActive = false;
}

// Trichter Bilder mit Event versehen
function cbModellBildOnLoad() {
	$('#content_info [id^=action]').click(function(){behaviour(this.id);});
	$("#content_main td").click(function(){
		if (!$(this).hasClass('overlay') && !$(this).hasClass('modell_bild_no-modell'))
		{
			// keine Aktion ausloesen bei Modellgruppen, die im Showroom nicht vorhanden sind 
			if (app.isShowroom && !mgnAvailable($(this).attr('id').substring(3))) {
				return;
			}
			else {
				confmodell.setModellgruppe(this.id.substring(3));
				confmodell.setBezeichnung(getModelgruppeBez());
				behaviour('actionContentModellansicht', confmodell.modellgruppe, false);
			}
		}
	});
	if (state.criteriaActive)
	{	actionUpdateFromCriteria();
	}
}

// Trichter Liste mit Events versehen
function cbModellListeOnLoad() {
	$('#content_info [id^=action]').click(function(){behaviour(this.id);});
	$('.infobox').hover(showInfobox, hideInfobox);
	$("#content_info select[name=auv]").change(function(){actionContentAuswahlOnChange(this.value);});

	if (state.ansicht === 'liste')
	{
		$("#content_info select[name=modellgruppen]").change(function(){actionContentAuswahlMgOnChange(this.value);});
	}

	if (actAustVar !== '') {
			$("#content_info select[name=auv]").selectOptions(actAustVar, true);
	}

	if (state.criteriaActive) {
		actionUpdateFromCriteria();
	}
	hideWait();
}

// Modellcode einfuegen
function set_modellcode(link, code)
{
	link = link.replace(/MODELL=[a-zA-Z0-9]{0,8}/, "MODELL=" + code);
	return link;
}

// Lightbox mit Bitte-Warten anzeigen
function showWait() {
	if(gui_locked) {
		return;
	}
	tb_show(null,"#TB_inline?height=190&width=280&inlineId=working",false);
}

// Lightbox mit Bitte-Warten ausblenden
function hideWait() {
	if(gui_locked) {
		return;
	}
	layoutManager.doLayout();
	tb_remove();
}

// Div mit Bitte-Warten anzeigen
function showWaitDiv()
{
	// Position abhaengig vom linken Rand von '#rundherum' (wichtig fuer Skoda / SEAT bei Fullscreen)
	var $_working = $("#working");
	$_working.css('left', ($("#rundherum").position().left + 235) +'px');

	$_working.show();
}

// Div mit Bitte-Warten ausblenden
function hideWaitDiv()
{
	$("#working").hide();
}

// Standard-URL generieren
function getBaseConfiguratorURL (resource)
{
	return svc.cfgapp + resource + "?MODELL=" + confmodell.modellcode + "&FAB=" + confmodell.fabrikat;
}

function getBaseConfiguratorURLdefaultModel (model, resource)
{
	return svc.cfgapp + resource + "?MODELL=" + model + "&FAB=" + confmodell.fabrikat;
}

// URL fuer CFG-SVC mit Parametern modellcode, farbe, polster, maus generieren
function getConfiguratorURL (resource)
{
	if (app.isVU) {
		return svc.cfgapp + resource + 
			"?MODELL=" + confmodell.modellcode +
			"&F=" 	+ confmodell.farbe + 
			"&P=" 	+ confmodell.polster + 
			"&P0=" + 
			"&M=" 	+ confmodell.mehrausstattungen + 
			"&FAB=" 	+ confmodell.fabrikat + 
			"&APP=VU";
	} else if (app.isShowroom) {
		return svc.cfgapp + resource + 
			"?MODELL=" + confmodell.modellcode +
			"&F=" 	+ confmodell.farbe +
			"&P=" 	+ confmodell.polster +
			"&M=" 	+ confmodell.mehrausstattungen +
			"&FAB=" 	+ confmodell.fabrikat +
			"&APP=SHOWROOM";
	} else {
		return svc.cfgapp + resource + 
			"?MODELL=" + confmodell.modellcode +
			"&F=" 	+ confmodell.farbe +
			"&P=" 	+ confmodell.polster +
			"&M=" 	+ confmodell.mehrausstattungen +
			"&FAB=" 	+ confmodell.fabrikat;
	}
}

// Templating Engine verwenden mit Uebergabe Template
function getTemplateURL (resource)
{
	if (app.isShowroom) {
		return svc.template_url + "?APP=SHOWROOM" + "&FILE=" +resource;
	} else {
		return svc.template_url + "?FILE=" +resource;
	}
}

function get_uri(farbcode, polcode, mnrcode)
{
	uri = '';
	delim = '&';
	if (farbcode) {
		uri = uri + delim + "F=" + farbcode;
	}
	if (polcode) {
		uri = uri + delim + "P=" + polcode;
	}
	uri = uri + delim + "M=" + mnrcode;
	return uri;
}

// Daten zur Modellgruppe aus Liste auslesen
// @param mg	'060'
// @returns		JSON Objekt: Basis-Infos zur Modellgruppe, Liste aller ihrer Modelle
function getModelgruppe(mg)
{
	for (i in modellData) {
		if (modellData[i].mg === mg) {
			return modellData[i];
		}
	}
}

// @param mg	'060'
// @returns 	'Golf Neu'
function getModelgruppeBez()
{
	return getModelgruppe(confmodell.modellgruppe).modelle[0].imoimgb;
}

// Ausstattungsvariante aus Liste auslesen
// @param modcode	Modellcode: '3C51C7B4'
// @returns			JSON Objekt: {imoimg: '229', imoimgb: 'Passat Variant', avb: 'Comfortline Business', fab: 'V'},
//					"null" wenn nichts fuer "modcode" gefunden wurde
function getModellInfo(modcode)
{
	for (i in modellData) {
		for (j in modellData[i].modelle) {
			if (modellData[i].modelle[j].modell === modcode) {
				var resultJSON = {
					imoimg: modellData[i].modelle[j].id,		// '229'
					imoimgb: modellData[i].modelle[j].imoimgb,	// 'Passat Variant'
					avb: modellData[i].modelle[j].avb,			// 'Comfortline Business'
					fab: modellData[i].modelle[j].fab,			// 'V'
					av: modellData[i].modelle[j].av				// 'Comfort'
				};
				return resultJSON;
			}
		}
	}
	return null;
}

// Fabrikat aus JSON-Objekt auslesen
function getFab()
{
	return modellData[0].fab;
}

// Inhalt je nach gewaehlter Kategorie laden
function updateMausKat(kat)
{
	if (kat === 'ALLE')
	{
		var callmaus_alle = getConfiguratorURL("cc3mausalle.txt");
		$.get(callmaus_alle + "&KAT=ALLE", function(data) {
			$("#content").html(data);
			$("#rundherum").scrollTop(0);
		});
	}
	else if (kat === 'START')
	{
		var callmaus_start = getConfiguratorURL("cc3mausStart.txt");
		$.get(callmaus_start + "&KAT=START", function(data) {
			$("#content").html(data);
			$("#rundherum").scrollTop(0);
		});
	}
	else if (kat === 'AKTIONEN')
	{
		var callmaus_aktionen = getConfiguratorURL("cc3mausAktionen.txt");
		$.get(callmaus_aktionen + "&KAT=AKTIONEN", function(data) {
			$("#content").html(data);
			$("#rundherum").scrollTop(0);
		});
	}
	else if (kat === 'PREF')
	{
		var callmaus_pref = getConfiguratorURL("cc3mausBeliebte.txt");
		$.get(callmaus_pref + "&KAT=PREF", function(data) {
			$("#content").html(data);
			$("#rundherum").scrollTop(0);
		});
	}
	else
	{
		var callmaus_kat = getConfiguratorURL("cc3mauskat.txt");
		$.get(callmaus_kat + "&KAT=" + kat, function(data) {
			$("#content").html(data);
			$("#rundherum").scrollTop(0);
		});
	}
}

// infobox
function showInfobox(e){
	var infobox = $(this);
	var elm = infobox.children('.infotext');
	var pos = infobox.position();

	elm.css('left', (pos.left + 5) + 'px');
	elm.css('top', (pos.top - 40) + 'px');
	elm.fadeIn('normal');
}

function hideInfobox(e){
	var elm = $(this).children('.infotext');
	elm.fadeOut('normal');
}

function showImageDivStoff() {
	var image_div = $(this).next();

	// horizontal position
	var pos = $(this).position();
	if (style.isSeat || style.isVw || style.isLnf || style.isGA) {
		image_div.css('left', (pos.left - 325) + 'px');
	}
	else {
		image_div.css('left', (pos.left - 260) + 'px');
	}

	// vertical position
	centerHoverImageVertically(image_div);

	image_div.css('z-index', '10');
	image_div.fadeIn('normal');
}

function showImageDivRaeder() {
	var image_div = $(this).next();

	// horizontal position
	var pos = $(this).position();
	image_div.css('left', (pos.left - 280) + 'px');

	// vertical position
	centerHoverImageVertically(image_div);

	image_div.css('z-index', '10');
	image_div.fadeIn('normal');
}

function showImageDivMaus() {
	var image_div = $(this).next();

	// horizontal position
	var pos = $(this).position();
	image_div.css('left', (pos.left - 300) + 'px');

	// vertical position
	centerHoverImageVertically(image_div);

	image_div.css('z-index', '10');
	image_div.fadeIn('normal');
}

// Zentriert "image_div" vertikal im sichtbaren Bereich von #rundherum
function centerHoverImageVertically(image_div) {
	var verticalCenter = Math.floor($('#rundherum').height() / 2) + $('#rundherum').attr('scrollTop');

	var borderTop = parseInt(image_div.css('border-top-width'), 10);
	var borderBottom = parseInt(image_div.css('border-bottom-width'), 10);
	var imageDivCenter = Math.floor((image_div.height() + borderTop + borderBottom) / 2);

	image_div.css('top', (verticalCenter - imageDivCenter) + 'px');
}

function hideImageDiv(){
	var image_div = $(this).next();
	image_div.fadeOut('normal');
}

// XML mit aktueller Konfiguration erstellen
function actionCreateXml() {
	location.href = getConfiguratorURL('cc3result.xml') + "&APP=VU";
}

function actionCloseVu() {
	window.close();
}

function addAngebotnrToCookie(modell, motor, antrieb, tueren, preis, nr){
	var cookie_value = $.cookie("anrlist");
	var angebotnr_list;
	if(cookie_value) {
		angebotnr_list = $.parseJSON(cookie_value);
	} else {
		angebotnr_list = [];
	}
	var new_list = [{fzg: [modell, motor, antrieb, tueren, preis], nr:nr, datum: getDateString()}];
	for(var i = 0; i < angebotnr_list.length; i++) {
		if(angebotnr_list[i].nr !== nr) {
			new_list.push(angebotnr_list[i]);
		}
		
		if(new_list.length >= 5) {
			break;
		}
	}

	cookie_value = $.toJSON(new_list);
	$.cookie("anrlist", cookie_value, {expires: 500, path: '/'});
}

function getAngebotnrlistFromCookie(){
	var cookie_value = $.cookie("anrlist");
	var angebotnr_list;
	if(cookie_value) {
		angebotnr_list = $.parseJSON(cookie_value);
	} else {
		angebotnr_list = [];
	}
	return angebotnr_list;
}

function actionCreateAudicode() {
	log("actionCreateAudicode");
	create_angebotnr(function(nr){
		log("actionCreateAudicode", nr);
		$("#angebotnr").text(nr);
		addAngebotnrToCookie(confmodell.bezeichnungKurz, confmodell.motor, confmodell.antrieb, confmodell.tueren, confmodell.preis, nr);
		$("#audicode").fadeIn();
		
	});
}

function actionEnterAudicode() {
	log("actionEnterAudicode");
	
	sendconfig = false;
	enteraudicode = true;
	createdvd = false;
	loadOnlineKeyboard(300,1200);
}

function actionRecentAudicode() {
	log("actionRecentAudicode");
	var callshowangebotnr = getTemplateURL("cc3/angebotsnr.htm");
	var lightboxParams = 'TB_iframe=true&modal=true&height=500&width=830';
	callshowangebotnr += lightboxParams;
	tb_show(null, callshowangebotnr, false); // lightbox - direct invocation
}

function callAudiCode(angebotnr, onError) {
	retrieve_angebotnr(angebotnr, function(valid, url, fab) {
		if (valid && fab === 'A') {
			window.location.href = url;
		} else {
			onError();
		}
	});
}