/**
 * --------------------------------
 * - UsedCars Modules autobild.de -
 * --------------------------------
 * Requires jQuery>= 1.1.2 to be includen beforehand.
 * 
 * There can be only one instance of each module-type per page (understand this! Its important. Really.)
 * 
 * For AUBI-ID dependent calls there must be a global variable AUBIID defined prior to the first AJAX call.
 * Also if the user is logged into the system, the ir-userid (irui, aka. userlogonname) must be set.
 * 
 *  <script type="text/javascript">
 *	// <![CDATA[
 *		var AUBIID = "1;2;3;4";
 * 		var IRUI = "fschumacher";
 *	// ]]>
 *	</script>
 * 
 * Implementation:
 * ---------------
 * 
 * For a new element choose a new unique id, a selector and a basename for the functions
 * Create "prepare_functionname", "success_functionname" and "fail_functionname" (fail_* is optional) methods.
 * prepare_*: Returns Object with (at least):
 * 			  1. "modulselector": Selector for DIV
 * 			  2. "url": URL to get the data from
 * success_*: Modify the DOM here (append .rtemp() to last jQuery call)
 * fail_*   : What should happen, if request (token or data) fails? Defaults to "failnotice()"
 * finally_*: Called after success_* (Defaults to finallygeneral())
 * 
 * prepare_* returns an object of configuration variables:
 * {
 * 		url: "url of data request"
 * 		modulselector: "jQuery selector for module contents",
 * 		tokenparams: {
 * 			Parameters for token request
 * 		},
 * 		dataparams: {
 * 			Parameters for data request
 * 		}
 * 
 * }
 * 
 * prepare_* can return false (boolean) to avoid execution of success_*
 * 
 * The return value of prepare_* can have an "options" element with the following values (all optional):
 * options: {
 * 		next: "htmlelement" (For all actions, that replace HTML, choose not the selector but the selector+next HTML element Tag)
 * 		loading_wrap: "HTML" (Wrap the loading.indicator in "HTML". Tags are Auto-closed at the end)
 * 		loadingindicator: ("IMAGEPATH" Overrides global loading image with custom one.) or false if none wanted
 * 		loadingselector: "SELECTOR" (selects this custom selector INSIDE the module-selector for replacing with loading-indicator)
 * 		notokenreuse: true (Do not reuse token, even if possible)
 * 		skiptosuccess: true (Do not use a token request at all, skip to success_*)
 * }
 * 
 * Call Trace Example:
 * -------------------
 * 
 * init()
 * 	-> prepare_*()
 * 	-> new Updater().process()
 * 		-> Updater.get_token()
 * 			-> Updater.get_token_ok()
 * 			-> Updater.get_data()
 * 				-> Updater.get_data_ok()
 * 					-> success_*()
 * 					-> finally_*()
 * When a timeout or error occur: fail_*()
 * 			
 * Additional documentation:
 * -------------------------
 * 
 * See extras/Boersenschnittstellen und AJAX Module.doc (Module xx numbers correspond to that documentation)
 * 
 * TODOS:
 * ------
 * 
 * Statistic:
 * ----------
 * Date: $LastChangedDate: 2008-08-29 12:27:49 +0200 (Fr, 29 Aug 2008) $
 * Revision: $LastChangedRevision: 11590 $
 * 
 */
// Do not load more than once
if(typeof window.AUBIUC == "undefined") {

	// The big bad voodoo daddy:
	var AUBIUC = {
		version: "2.0", // Version of this JS
		kwtops: 1.35962, // kW to PS factor
		cssfilename: "http://i.auto-bild.de/api/uc.css", // CSS to be includes when processing. (LIVE: http://api.autobild.de/usedcars/css/uc.css, LOCAL: css/uc.css
		ajaxloadingimage: "http://www.autobild.de/api/ajax-loading-white.gif", // URL of AJAX-loading image
		mpar: [{}], // This is temporary storage, do not trust.
		aubiid: "", // Global AUBIID
		irui: "", // Global logged in user id
		gwidone: false, // Flag if GWI registering of events is already done or not
		initdone: false, // Init loop done
		watchjsontimer: 5000, // Call watchdog every n milliseconds
		databaseurl: "http://ws-vip.motoso.easynet.de/autobild-api/json/", // Base URL for DATA requests 
		gwbbaseurl: "http://automarkt.autobild.de/autobild/gebraucht/", // BaseURL of "autobild.de Automarkt" (used all over the place)
		regged_cleanup: false, // Is the registering of DOM cleanup done?
		// Timer
		inflight: {}, // Stack for inflight requests
		inflightcount: 0, // Absolute number of current inflight requests
		timeoutsec: 15, // Timeout default in seconds
		
		// Runtime Variables
		working: null, // For reload scenario: Working set of modules
		
		// Texts
		texts: {
			noted: "Dieses Inserat wurde gemerkt",
			timeout: "Dieser Inhalt kann zur Zeit nicht angezeigt werden.",
			offer_for: "Angebote zu",
			passendegwb_checkstring: "inserat-S", // This string is searched for inside "Passende Gebrauchtwagen" to define if JSONP request is needed
			no_searches: "Sie haben aktuell keine Suchen im Automarkt gespeichert. Nutzen Sie unseren Service und lassen Sie sich per E-Mail ueber neue passende Inserate informieren!",
			no_car_ad: "Sie haben bisher keine eigenen Inserate im <a href=\"http://automarkt.autobild.de/\">Automarkt</a>.",
			no_noted_cars: "Sie haben der Merkliste aktuell keine Inserate zugefuegt.",
			noted_all_sold: "Ihre gemerkten Fahrzeuge wurden inzwischen durch die Anbieter verkauft.",
			no_viewed_cars: "Sie haben sich bislang noch keine Inserate angesehen.",
			no_exec_searches: "Sie haben bislang noch keine Suche ausgefuehrt."
		},
		
		// For non AUBIID request, take one of these
		// Main makes on german market
		dummyaubiids: [ 2, 3, 4, 11, 24, 27, 28, 30, 32, 36, 38],
		
		// All modules
		// jquery speedrating: #,div.class,.class (fast->slow)
		modules: [ 
		{ id: "tipp_ada",        selector: "div.teaser-XXL-tipp"                    }, // Module 01
		{ id: "ada_3er",         selector: ".mod-inserate1 .mod-body"               }, // Module 02
		{ id: "nwklink",         selector: "#funktionslinks_nwk"                    }, // Module 05
		{ id: "gwblink",         selector: "#funktionslinks_gwb"                    }, // Module 05
		{ id: "ada_1er",         selector: "div.mod-inserate4 .mod-contents"        }, // Module 06
		{ id: "fahrzeugsuche",   selector: "#frm-fahrzeugsuche1"                    }, // Module 07/08
		{ id: "ada_6er",         selector: "div.mod-inserate3"                      }, // Module 10
		{ id: "mautom",          selector: "#mein-automarkt"                        }, // Module 13
		{ id: "mautominfo",      selector: "#never"                                 }, // Module 13
		{ id: "gespsuchen",      selector: "#gespeicherte-suchen table.t2 tbody"    }, // Module 14
		{ id: "gemerkteinslist", selector: "#gemerkte-fz .uc-notedcars"             }, // Module 15
		{ id: "meinefahrzeuge",  selector: "#uc-meine-fahrzeuge"                    }, // Module 16
		{ id: "mwunschkfz",      selector: "#uc-meine-wunschfahrzeuge"              }, // Module 16
		{ id: "gemerkteins",     selector: "div.mod-gemerkt .mod-content .mod-body" }, // Module 20
		{ id: "meinesuchen",     selector: "div.uc-suchenmeine .mod-body"           }, // Module 21
		{ id: "angesehen",       selector: "div.mod-angesehen .mod-body"            }, // Module 22
		{ id: "zuletztgesucht",  selector: "div.uc-suchenzuletzt .mod-body"         }, // Module 23
		{ id: "passendegwb",     selector: "div.uc-passendegwb"                     }, // Module 24
		{ id: "ins2x3",          selector: "div.mod-inserate2 .mod-body"            }  // Module 27
		],
		
		/*
		 * Initialize Objects and run updater
		 * Pass an array of modules
		 */
		init: function(elements, parameter) {
			
			// Init jQuery Extensions
			if(!this.initdone) {
				this.init_jq_ext();
				this.initdone = true;
			}
			
			// remove updaterstack (possible IE DOM Leak)
			if(isu(this.updaterstack)) {
				this.updaterstack = [{}];
			}
			
			// If there is no storage, create one
			// This is persistant between init() calls
			if(isu(this.modulstorage)) {
				this.modulstorage = { };
			}
			
			// Is the global AUBIID set?
			if(typeof AUBIID != "undefined") {
				this.aubiid = AUBIID;
			} 
			else {
				// Quick fix for api-server not responding without a numeric aubiid
				// Generate random aubiid, make only
				this.aubiid = this.dummyaubiids[Math.floor(Math.random()*this.dummyaubiids.length)];
			}
			
			// Is the global "InterRed User ID" (irui) set?
			// IR sets IRUI to 0 meaning "no IRUI"
			if(typeof IRUI != "undefined" && IRUI != "0") {
				this.irui = IRUI;
			}
			
			// Parameter
			this.parameter = parameter || {};
			
			// Execute GWI event registring
			// DELETE
			if(!this.gwidone) {
				this.gwieventregister();
				this.gwidone = true;
			}
			
			// Register UNLOAD to clean up the DOM
			if(!this.regged_cleanup) {
				$(window).unload(function() { AUBIUC.cleanup(); });
				this.regged_cleanup = true;
			}
			
			// Which array should we work on?
			this.working = null;
			if(!isu(elements)) {
				this.working = elements;
			}
			else {
				this.working = this.modules;
			}
			
			// Search for parsable modules in this page and
			// execute the corresponding function
			for (var i = 0, ol = this.working.length; i < ol; i++) {
				// Only if there IS a match OR run is forced
				if($(this.working[i].selector).length > 0 || !isu(this.parameter.force)) {
					
					// Parameter for later calls
					this.mpar[i] = {};
					// Call prepare_ method for this selector
					this.mpar[i] = eval("this.prepare_"+this.working[i].id+"(\""+this.working[i].selector+"\")");
					
					// AUTO start JSONP request?
					if(this.mpar[i] !== false) {
						this.mpar[i].functionname = this.working[i].id;
						this.mpar[i].id = this.working[i].id;
						this.mpar[i].options = this.mpar[i].options || {};
						this.mpar[i].tokenparams = this.mpar[i].tokenparams || {};
						
						// Create a new Updater "thread" and start it
						this.updaterstack[i] = new Updater(i);
						this.updaterstack[i].process();
					}
				}
			}
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 01: "Tipp des Tages" - Prepare
		 */
		prepare_tipp_ada: function(modulselector) {
			// Modify Moduleselector to only include variable contents
			return ({
				modulselector: modulselector+" .inserat-S", // Modify selector name
				url: "vehicle", // URL of JSON-Data API (after /usedcars/json/)
				tokenparams: { // Parameters for token call
					count: 1 // How many cars to fetch...
				},
				options: {
					aubiidlevel: 1
				}
				// Parameters for data calls (not needed here otherwise "dataparams: { ... }"
				// Options not needed, otherwise options: { ... }
			});
		},
		
		/*
		 * Module 01: "Tipp des Tages" - Success
		 */
		success_tipp_ada: function(data) {
			var usi=data.usi;
			var c = [];
			
			// No cars in data?
			if(isu(data.cars)) {
				$(this.mpar[usi].modulselector).empty().rtemp();
				return;
			}
			
			// HTML
			c[c.length] = "<div class=\"inserat-img\">";
			c[c.length] = 	"<img src=\""+this.motosoimageurl(data.cars[0].image_ref)+"\" alt=\""+data.cars[0].make+" "+data.cars[0].model+"\" title=\"\" />";
			c[c.length] = "</div>";
			c[c.length] = "<div class=\"inserat-data\">";
			c[c.length] = 	"<ul>";
			c[c.length] = 		"<li>"+data.cars[0].make+"</li>";
			c[c.length] = 		"<li>"+data.cars[0].model+"</li>";
			
			if (data.cars[0].mileage > 0) {
				c[c.length] = 		"<li>"+this.formatnumber(data.cars[0].mileage)+" km</li>";
			}
		
			if (data.cars[0].power_kw > 0) {
				c[c.length] = 		"<li>"+data.cars[0].power_kw+" kW ("+this.convertpower(data.cars[0].power_kw)+" PS)</li>";
			}
			
			if (data.cars[0].initial_registration_date.month > 0 && data.cars[0].initial_registration_date.year > 0) {
				c[c.length] = 		"<li>EZ "+this.twodig(data.cars[0].initial_registration_date.month)+"/"+data.cars[0].initial_registration_date.year+"</li>";
			} else if (data.cars[0].initial_registration_date.year > 0) {
				c[c.length] = 		"<li>EZ "+data.cars[0].initial_registration_date.year+"</li>";
			}
			
			if (data.cars[0].price > 0) {
				c[c.length] = 		"<li>&euro; "+this.formatnumber(data.cars[0].price)+"</li>";
			}
			
			c[c.length] = 	"</ul>";
			c[c.length] = "</div>";
			
			var sel = $(this.mpar[usi].modulselector);

			// Replace HTML
			sel
			.empty()
			.prepend(c.join(""))
			.css("cursor","pointer")
			.rtemp();
			
			// Attach onclick
			sel.click(function() {
				AUBIUC.go(data.cars[0].id);
			});
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 02: "Aus dem Automarkt" (3er) - Prepare
		 */
		prepare_ada_3er: function(modulselector) {
			// Return Variables
			return ({
				modulselector: modulselector,
				url: "vehicle",
				options: {
					notokenreuse: true
				},
				tokenparams: {
					count: 3 // Min. of 3 cars
				},
				dataparams: {
					count: 3  // Return 3 cars
				}
			});
		},
		
		/*
		 * Module 02: "Aus dem Automarkt" (3er) - Success
		 */
		success_ada_3er: function(data) {
			var usi=data.usi;
			var c = [];
			
			for(var i=0, ol = data.cars.length; i < ol && i < 3;i++) {
				c[c.length] = "<div class=\"inserat-S2 uc-islink\" id=\"mod-inserate1-inserat"+(i+1)+"\" onclick=\"AUBIUC.go('"+data.cars[i].id+"')\">";
				c[c.length] = 	"<div class=\"inserat-img\">";
				c[c.length] = 		"<img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" />";
				c[c.length] = 	"</div>";
				c[c.length] = 	"<div class=\"inserat-data\">";
				c[c.length] = 		"<div class=\"inserat-data-hersteller\">"+data.cars[i].make+"</div>";
				c[c.length] = 		"<div class=\"inserat-data-modell\" title=\""+data.cars[i].model+"\">"+data.cars[i].model+"</div>";
				c[c.length] = 		"<div class=\"inserat-data-km\">"+this.formatnumber(data.cars[i].mileage)+" km</div>";
				c[c.length] = 		"<div class=\"inserat-data-leistung\">"+data.cars[i].power_kw+" kW ("+this.convertpower(data.cars[i].power_kw)+" PS)</div>";
				c[c.length] = 		"<div class=\"inserat-data-preis\">EUR "+this.formatnumber(data.cars[i].price)+"</div>";
				c[c.length] = 	"</div>";
				c[c.length] = "</div>";
			}
			
			$(this.mpar[usi].modulselector)
			.empty()
			.prepend(c.join(""))
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 05: "Neuwagenkonfigurator Link" - Prepare
		 */
		prepare_nwklink: function(ms) {
			// Bind click to NWK Link
			$(ms).click(function() {
				window.location.href = "http://wli-de.eurotax.com/wli/dede/entry/entry_frameless.php?koop_id=1D3C899CDF";	
			});
			
			// No success function call neccessary, returning false
			return false;	
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 05: "Gebrauchtwagenboerse Link" - Prepare
		 */
		prepare_gwblink: function(ms) {
			// Bind click to GWB Link
			$(ms).click(function() {
				// Extract Make and Model:
				var aubiid = AUBIUC.aubiid.split(";");
				var uri = AUBIUC.gwbbaseurl+"suchen_start.php?aubiid="+aubiid[0];	
				if(!isu(aubiid[1])) {
					uri += ";"+aubiid[1];
				}
				window.location.href= uri;
			});
			
			// No success neccessary, returning false
			return false;	
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 06: "Aus dem Automarkt" (1er) - Prepare
		 */
		prepare_ada_1er: function(modulselector) {
			var moduleid = "ada_1er";
			// Check if there is a "nextid" in storage
			var start = 0;
			var current_modul = this.storageload(moduleid);
			if(current_modul == null) {
				start = 0;
				this.storagesave(moduleid,"current_car",start);
			}
			else {
				start = current_modul.current_car; 
			}
			return ({
				modulselector: modulselector, // Modify selector name
				url: "vehicle", // URL of JSON-Data API
				tokenparams: {  
					count: 1,
					hits: 200
				},
				dataparams: {
					start: start,
					count: 1
				}
			});
		},
		
		/*
		 * Module 06: "Aus dem Automarkt" (1er) - Success
		 */
		success_ada_1er: function(data) {
			var usi=data.usi;
			var c = [];
			var moduleid = "ada_1er";
			
			// Data retured ok?
			if(isu(data.cars)) {
				this.failnotice(usi);
				return;
			}
			
			// Previous and next Car:
			var hits = this.storageload("ada_1er","token").hits; 
			var current_car = this.storageload(moduleid,"current_car");
			var previous_car = (current_car < 1)?null:(current_car-1);
			var next_car = (current_car == (hits-1))?null:(current_car+1);

			// Search for ID in cookie
			var cars = $.cookieget("uc_note_cars").split("-");
			$.each(cars, function (index, car) {
				if(parseInt(car,16) == data.cars[0].id) {
					cars = false;
				}					
			});
			
			// HTML
			c[c.length] = "<div class=\"mod-intro\">";
			c[c.length] = 	"<div class=\"mod-intro-content\">";
			c[c.length] = 		"<div class=\"browse-prev-"+((previous_car!==null)?"on":"off")+"\"><a href=\"javascript:void(0);\" title=\"zur&uuml;ck\" onclick=\"AUBIUC.prevcar('"+moduleid+"',"+previous_car+")\"><span>zur&uuml;ck</span></a></div>";
			c[c.length] = 		"<div class=\"browse-text\"><a href=\""+data.cars[0].id+"\">Inserat "+(current_car+1)+" von "+hits+"</a></div>";
			c[c.length] = 		"<div class=\"browse-next-"+((next_car!==null)?"on":"off")+"\"><a href=\"javascript:void(0);\" title=\"vorw&auml;rts\" onclick=\"AUBIUC.nextcar('"+moduleid+"',"+next_car+")\"><span>vorw&auml;rts</span></a></div>";
			c[c.length] = 	"</div>";
			c[c.length] = "</div>";
			c[c.length] = "<div class=\"mod-body\">";
			c[c.length] = 	"<div class=\"inserat-S uc-islink\" onclick=\"AUBIUC.go('"+data.cars[0].id+"')\">";
			c[c.length] = 		"<div class=\"inserat-img\">";
			c[c.length] = 			"<img src=\""+this.motosoimageurl(data.cars[0].image_ref)+"\" width=\"90\" height=\"68\" alt=\""+data.cars[0].make+" "+data.cars[0].model+"\" title=\"\" />";
			c[c.length] = 		"</div>";
			c[c.length] = 		"<div class=\"inserat-data\">";
			c[c.length] = 			"<ul>";
			c[c.length] = 				"<li>"+data.cars[0].make+"</li>";
			c[c.length] = 				"<li title=\""+data.cars[0].model+"\">"+data.cars[0].model+"</li>";
			c[c.length] = 				"<li>"+this.formatnumber(data.cars[0].mileage)+" km</li>";
			c[c.length] = 				"<li>"+data.cars[0].color+"</li>";
			c[c.length] = 				"<li>EZ "+this.twodig(data.cars[0].initial_registration_date.month)+"/"+data.cars[0].initial_registration_date.year+"</li>";
			c[c.length] = 				"<li>&euro; "+this.formatnumber(data.cars[0].price)+"</li>";
			c[c.length] = 			"</ul>";
			c[c.length] = 		"</div>";
			c[c.length] = 	"</div>";
			c[c.length] = 	"<ul class=\"linklist\">";
			c[c.length] = 		"<li><a href=\"javascript:void(0)\" onclick=\"AUBIUC.notecar("+data.cars[0].id+",'ada_1er')\" class=\"cmd cmd-savelisting\">Inserat merken</a></li>";
			c[c.length] = 		"<li><a href=\""+AUBIUC.gwbbaseurl+"meine_gemerkten_inserate.php?aktion=anzeigen\">Zu meinen gemerkten Inseraten</a></li>";
			c[c.length] = 	"</ul>";
			c[c.length] = "</div>";
			
			// Replace
			var sel = $(this.mpar[usi].modulselector);
			sel
			.empty()
			.prepend(c.join(""))
			.rtemp();
			
			// Already noted? 
			// When "cars" is "false"!
			if(!cars) {
		 		// Change HTML to display note-message
		 		$("a.cmd-savelisting",sel)
		 		// Unbind "click" event
		 		.unbind("click").removeAttr("href")
		 		// Remove Class
		 		.removeClass("cmd-savelisting")
		 		// Add Notice Icon
		 		.addClass("uc-notice")
		 		// Clear content
		 		.empty()
		 		// Add Notice text
		 		.prepend(this.texts.noted);
			}
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 07: "Fahrzeugsuche" - Prepare
		 */
		prepare_fahrzeugsuche: function(modulselector) {
			var moduleid = "fahrzeugsuche";
			
			// Attach submit listener:
			$("#btn_fzsuche_submit").click(function() {
				$("#frm-fahrzeugsuche1").submit();
			});
			
			// Attach to "zur Detailsuche"
			// "Detailsuche" with filled in values. Do not start the search
			$("#frm-fahrzeugsuche1-dsuche").click(function() {
				$("#nogo").val("1");
				$("#frm-fahrzeugsuche1").submit();
				return false;
			});
			
			// Attach submit listener ("Inserat") (Module 08)
			$("#frm-inserat #btn_fzsuche_submit").click(function() {
				$("#frm-inserat").submit();
			});
			$("#frm-inserat2 #btn_fzsuche_submit").click(function() {
				$("#frm-inserat2").submit();
			});
			
			
			// Register reset function for reset-values button
			$("#frm-fahrzeugsuche1-reset").click(function() {
				document.getElementById("frm-fahrzeugsuche1").reset();
				$("#frm-fahrzeugsuche1 .highlight-input").each(function() {
					$(this).removeClass("notempty");
				});
				$("#fzsuche-data_marke").removeClass("notempty");
				$("#fzsuche-data_modell").removeClass("notempty");
				$("#fzsuche-data_variante").removeClass("notempty");
			});
			
			return ({
				modulselector: modulselector,
				url: "make",
				options: {
					loadingindicator: false // No loading sign
				}
			});
		},
		
		/*
		 * Module 07: "Fahrzeugsuche" - Success
		 * Is only call once when make-data is ready
		 */
		success_fahrzeugsuche: function(data) {
			var usi=data.usi;
			var moduleid = "fahrzeugsuche";
			
			var sel = $("#fzsuche-data_marke");
			var content = [ "<option value=\"\"></option>" ];
		
			$.each(data.makes, function(i,e) {
				content[content.length] = "<option value=\""+e.id+"\">"+e.make+"</option>";
			});
			sel.empty().append(content.join(""));
			
			// Select element zero
			document.getElementById("fzsuche-data_marke").selectedIndex = 0;
			document.getElementById("fzsuche-data_modell").selectedIndex = 0;
			document.getElementById("fzsuche-data_variante").selectedIndex = 0;
			
			// Register onchange listeners
			$("#fzsuche-data_marke").unbind("change").bind("change", {}, AUBIUC.fzsuche);
			$("#fzsuche-data_modell").unbind("change").bind("change", {}, AUBIUC.fzsuche);
			$("#fzsuche-data_variante").unbind("change").bind("change", {}, AUBIUC.fzsuche);
		},
		
		/*
		 *  Module 07: "Fahrzeugsuche" - Custom fail handlers
		 */
		fail_fahrzeugsuche: function(usi) {
			$(this.mpar[usi].modulselector)
			.empty()
			.append("<div class=\"uc-timeout\" style=\"height: 361px;\">"+this.texts.timeout+"</div>")
			.rtemp();
		},
		
		/*
		 * Module 07: "Fahrzeugsuche" - onchange-listener for fzsuche
		 * fzsuche found with "#frm-fahrzeugsuche1"
		 */
		fzsuche: function(evt) {
			var reload = [];
			var selected = "";
			
			// Yellow BG-color
			var notempty = function(id) {
				var s = $("#fzsuche-data_"+id);
				if($(":selected",s).val() != "") {
					s.addClass("notempty");
				}
				else {
					s.removeClass("notempty");
				}
			};
			
			// Clear field
			var clearselect = function(id) {
				$("#fzsuche-data_"+id)
				.empty()
				.append("<option value=\"\"></option>")
				.removeClass("notempty");
			};
			
			// Call to model list
			if(!isu(evt.models) && evt.models.length > 0) {
				// Fill in values
				var content = [ "<option value=\"\"></option>" ];
		
				$.each(evt.models, function(i,e) {
					content[content.length] = "<option value=\""+e.id+"\">"+e.model+"</option>";
				});
				$("#fzsuche-data_modell").empty().append(content.join("")).removeClass("notempty");
				document.getElementById("fzsuche-data_modell").selectedIndex = 0;

				delete evt; 
				return;
			}
			// Call to type list
			else if(!isu(evt.types) && evt.types.length > 0) {
				// Fill in values
				var content = [ "<option value=\"\"></option>" ];
		
				$.each(evt.types, function(i,e) {
					content[content.length] = "<option value=\""+e.id+"\">"+e.type+"</option>";
				});
				
				// Set content
				$("#fzsuche-data_variante")
				.empty()
				.append(content.join(""))
				.removeClass("notempty");
				
				// Set selected
				document.getElementById("fzsuche-data_variante").selectedIndex = 0;
				
				delete evt; 
				return;
			}
			
			// return if DATA JSONP listener call
			if(isu(evt.target)) {
				return true;
			}
			
			// Get ID
			var id = evt.target.id.replace(/fzsuche-data_/,"");
			selected = $("#fzsuche-data_"+id+" :selected").val();
			
			// Bad-teeth-yellow:
			notempty(id);
					
			switch(id) {
				case "marke":
					// Reload model
					clearselect("modell");
					clearselect("variante");
					if(selected != "") {
						$.getJSONP(AUBIUC.databaseurl+"model?callback={callback}&usi=0&make="+$("#fzsuche-data_marke :selected").val(), AUBIUC.fzsuche, { ident: -1 });
					}
					// Clear selects
					break;
				case "modell":
					// Clear select
					clearselect("variante");
					// Reload types
					if(selected != "") {
						$.getJSONP(AUBIUC.databaseurl+"type?callback={callback}&usi=0&model="+$("#fzsuche-data_modell :selected").val(), AUBIUC.fzsuche, { ident: -1 });
					}
					break;
			}
			
			delete evt;
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 10: "Aus dem Automarkt" (6er) - Prepare
		 */
		prepare_ada_6er: function(modulselector) {
			// Return Variables
			return ({
				modulselector: modulselector+"/.mod-content/.mod-body",
				url: "vehicle",
				options: {
					notokenreuse: true
				},
				tokenparams: {  
					count: 6
				},
				dataparams: {  
					count: 6
				}
			});
		},
		
		/*
		 * Module 10: "Aus dem Automarkt" (6er) - Success
		 */
		success_ada_6er: function(data) {
			var usi=data.usi;
			var sel = $(this.mpar[usi].modulselector)
			var c = [];
			
			for(var i=0, ol = data.cars.length; i < ol && i < 6;i++) {
				c[c.length] = "<div class=\"inserat-S2 uc-islink\" id=\"mod-inserate3-inserat"+(i+1)+"\" onclick=\"AUBIUC.go('"+data.cars[i].id+"')\">";
				c[c.length] = 	"<div class=\"inserat-img\">";
				c[c.length] = 		"<img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" />";
				c[c.length] = 	"</div>";
				c[c.length] = 	"<div class=\"inserat-data\">";
				c[c.length] = 		"<div class=\"inserat-data-hersteller\">"+data.cars[i].make+"</div>";
				c[c.length] = 		"<div class=\"inserat-data-modell\" title=\""+data.cars[i].model+"\">"+data.cars[i].model+"</div>";
				c[c.length] = 		"<div class=\"inserat-data-km\">"+this.formatnumber(data.cars[i].mileage)+" km</div>";
				c[c.length] = 		"<div class=\"inserat-data-leistung\">"+data.cars[i].power_kw+" kW ("+this.convertpower(data.cars[i].power_kw)+" PS)</div>";
				c[c.length] = 		"<div class=\"inserat-data-preis\">EUR "+this.formatnumber(data.cars[i].price)+"</div>";
				c[c.length] = 	"</div>";
				c[c.length] = "</div>";
			}
			
			// Replace
			sel.empty().prepend(c.join(""));
			
			// Change Title:
			$("span",sel.parent().parent())
			.empty()
			.prepend(this.texts.offer_for+" "+data.cars[0].make+" "+data.cars[0].model);
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 13: "Mein Automarkt" (Anzeige mit Skala) - Prepare
		 */
		prepare_mautom: function(modulselector) {
			var moduleid = "mautom";
			
			// Only if valid IRUI!
			if(isu(AUBIUC.irui) || AUBIUC.irui == "") return false;
			
			// Check if there is a "nextid" in storage
			var start = 0;
			var current_modul = this.storageload(moduleid);
			if(current_modul == null) {
				start = 0;
				this.storagesave(moduleid,"current_car",start);
			}
			else {
				start = current_modul.current_car; 
			}
			
			return ({
				modulselector: modulselector,
				url: "vehicle",
				tokenparams: {
					count: 3,
					mode: 1,
					iruserid: AUBIUC.irui
				},
				dataparams: {
					count: 1,
					start: start,
					extended: 1
				}
			});
		},
		
		/*
		 * Module 13: "Mein Automarkt" (Anzeige mit Skala) - Success
		 */
		success_mautom: function(data) {
			var usi=data.usi;
			var moduleid = "mautom";
			var c = [];
			var sel = $(this.mpar[usi].modulselector);
			
			// If there is NO car, stop here
			if(isu(data.cars) || data.cars.length < 1 || data.hits == 0) {
				// Display Message!
				sel
				.rtemp()
				.empty()
				.prepend("<div class=\"uc-no-car-ad\">"+this.texts.no_car_ad+"</div>");
				
				return false;
			}
			
			// Define total number, current, next and previous car
			var hits = this.storageload(moduleid,"token").hits; 
			var current_car = this.storageload(moduleid,"current_car");
			var previous_car = (current_car < 1)?null:(current_car-1);
			var next_car = (current_car == (hits-1))?null:(current_car+1);
			var car = data.cars[0];
			
			c[c.length] = "<div class=\"datengruppe-titel\">";
			c[c.length] = 	"<div class=\"dt-multi\">";
			c[c.length] = 		"<div class=\"dt-label\" id=\"uc_car_label-"+car.id+"\">"+car.make+" "+car.model+"</div>";
			c[c.length] = 		"<div class=\"dt-funktionen\">";
			c[c.length] = 			"<div class=\"browse-prev-"+((previous_car!==null)?"on":"off")+"\"><a href=\"javascript:void(0);\" title=\"zur&uuml;ck\" onclick=\"AUBIUC.prevcar('"+moduleid+"',"+previous_car+")\"><span>zur&uuml;ck</span></a></div>";
			c[c.length] = 			"<div class=\"browse-text\"><a href=\""+data.cars[0].id+"\">Inserat "+(current_car+1)+" von "+hits+"</a></div>";
			c[c.length] = 			"<div class=\"browse-next-"+((next_car!==null)?"on":"off")+"\"><a href=\"javascript:void(0);\" title=\"vorw&auml;rts\" onclick=\"AUBIUC.nextcar('"+moduleid+"',"+next_car+")\"><span>vorw&auml;rts</span></a></div>";
			c[c.length] = 		"</div>";
			c[c.length] = 	"</div>";
			c[c.length] = "</div>";
			c[c.length] = "<div id=\"mein-automarkt-inserate\">";
			c[c.length] = 	"<div class=\"inserat-M\" id=\"mein-automarkt-inserat1\">";
			c[c.length] = 		"<div class=\"inserat-img\">";
			c[c.length] = 			"<a href=\""+car.id+"\"><img src=\""+this.motosoimageurl(car.image_ref)+"\" alt=\""+car.make+" "+car.model+"\" title=\"\" /></a>";
			c[c.length] = 		"</div>";
			c[c.length] = 		"<div class=\"inserat-data\">";
			c[c.length] = 			"<table>";
			c[c.length] = 				"<colgroup>";
			c[c.length] = 					"<col class=\"col1\" />";
			c[c.length] = 					"<col class=\"col2\" />";
			c[c.length] = 				"</colgroup>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>Inseriert am</td>";
			c[c.length] = 					"<td>"+this.twodig(car.entry_date.day)+"."+this.twodig(car.entry_date.month)+"."+car.entry_date.year+" "+this.twodig(car.entry_date.hour)+":"+this.twodig(car.entry_date.minute)+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>G&uuml;ltig bis</td>";
			c[c.length] = 					"<td>"+this.twodig(car.valid_thru_date.day)+"."+this.twodig(car.valid_thru_date.month)+"."+car.valid_thru_date.year+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>Km-Stand</td>";
			c[c.length] = 					"<td>"+this.formatnumber(car.mileage)+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>EZ</td>";
			c[c.length] = 					"<td>"+this.twodig(car.initial_registration_date.month)+"/"+new String(car.initial_registration_date.year).substr(2)+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>HU/AU</td>";
			c[c.length] = 					"<td>"+this.twodig(car.main_inspection_thru.month)+"/"+new String(car.main_inspection_thru.year).substr(2)+", "+this.twodig(car.exhaust_inspection_thru.month)+"/"+new String(car.exhaust_inspection_thru.year).substr(2)+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>Karosserie</td>";
			c[c.length] = 					"<td>"+car.body_type+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>Farbe</td>";
			c[c.length] = 					"<td>"+car.color+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 				"<tr>";
			c[c.length] = 					"<td>Ansichten</td>";
			c[c.length] = 					"<td>"+car.statistic.views+"</td>";
			c[c.length] = 				"</tr>";
			c[c.length] = 			"</table>";
			c[c.length] = 		"</div>";
			c[c.length] = 	"</div>";
			c[c.length] = 	"<div class=\"inserat-preisvergleich\">";
			c[c.length] = 		"<div id=\"preis-min\" class=\"uc-loading\">Min.<br />			unbekannt</div>";
			c[c.length] = 		"<div id=\"preis-max\" class=\"uc-loading\">Max.<br />			unbekannt</div>";
			c[c.length] = 		"<div id=\"preis-mein\" style=\"display: none;\"><span>Mein Preis<br />			EUR "+this.formatnumber(car.price)+"</span></div>";
			c[c.length] = 		"<div id=\"preis-schwacke\" style=\"display: none;\"><span>Schwacke-Preis<br />	EUR unbekannt</span></div>";
			c[c.length] = 	"</div>";
			c[c.length] = "</div>";
			c[c.length] = "<div class=\"listenende-links\">";
			c[c.length] = 	"<a href=\"http://automarkt.autobild.de/autobild/anbieten/anbieten_start.php?dienst_id="+car.id+"\" style=\"margin-right: 10px;\">Inserat bearbeiten</a>";
			c[c.length] = 	"<a id=\"uc_del-"+car.id+"\" class=\"uc_del_car\" href=\"javascript:void(0);\">Inserat loeschen</a>";
			c[c.length] = "</div>";
			
			// Save Car-ID
			this.storagesave(moduleid,"current_car_id",car.id);
			
			// Temporary save "mein Preis" for step 2:
			this.storagesave(moduleid,"current_car_price",car.price);
			
			// Fill DOM
			sel
			.empty()
			.prepend(c.join(""))
			.rtemp();
			
			// Attach delete click
			$("a.uc_del_car",sel).click(function() {
				var id = this.id.substring(this.id.lastIndexOf("-")+1);
				var labeltext = $.trim($("#uc_car_label-"+id).text());
				var conf = confirm("Wollen Sie Ihr Inserat \""+labeltext+"\" (Angebotsnummer: "+id+") aus dem Automarkt einfernen?");
				if(conf == true) {
					$.getJSONP("http://automarkt.autobild.de/autobild/anbieten/anbieten_start.php?loeschen="+id+"&dienst_id="+id+"&json=1", null, { ident: -1 });
					history.go(0);
				}
				return false;
			});
			
			
			// Call second part:
			this.reload("mautominfo", { force: true, aubiid: car.aubi_id });
		},
		
		/*
		 * Module 13: "Mein Automarkt" (Anzeige mit Skala) - Custom fail handler
		 */
		fail_mautom: function() {
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 13: "Mein Automarkt" (Anzeige mit Skala; Infoteil) - Prepare
		 */
		prepare_mautominfo: function(modulselector) {
			var moduleid = "mautominfo";

			// Use token of "mautom"!
			this.storagesave(moduleid,"token",this.storageload("mautom","token"));
			
			// Check if there is a "nextid" in storage
			var start = 0;
			var current_modul = this.storageload(moduleid);
			if(current_modul == null) {
				start = 0;
				this.storagesave(moduleid,"current_car",start);
			}
			else {
				start = current_modul.current_car; 
			}
			return ({
				modulselector: modulselector,
				url: "info",
				dataparams: {  
					aubiid: this.parameter.aubiid
				}
			});
		},
		
		/*
		 * Module 13: "Mein Automarkt" (Anzeige mit Skala; Infoteil) - Success
		 */
		success_mautominfo: function(data) {
			var usi=data.usi;
			var moduleid = "mautominfo";
			var pos = 0;
			var my_price = this.storageload("mautom","current_car_price"); 
			var left = { start: 50, end: 245 };
			
			// Load car from previous step
			var current_car_id = this.storageload("mautom","current_car_id"); 
			
			// 1. "Min Preis"
			$("#preis-min")
			.empty()
			.append("Min.<br />\t\t\t"+this.formatnumber(data.min_price));
			
			// 2. "Max Preis"
			$("#preis-max")
			.empty()
			.append("Max.<br />\t\t\t"+this.formatnumber(data.max_price));
			
			// Devide by zero possible
			if((data.max_price - data.min_price) <= 0) {
				data.min_price = 1;
			}
			
			// Calculate left position of "mein Preis" on scale
			// Size of <---> Scale is 371px!
			// Start "left" of scale is 50px;
			// End "left" is 245px;
			try {
				pos = (left.end - left.start) / ( data.max_price - data.min_price ) * ( my_price - data.min_price);
				pos = Math.floor(pos);
			} catch(e) {
				return;
			}
			
			// Draw scale
			if(pos >= 0 && pos <= left.end-left.start) {
				$("#preis-mein").css("left",(pos+left.start)+"px").show();
			}
		},
		
		/*
		 * Module 13: "Mein Automarkt" (Anzeige mit Skala; Infoteil) - Custom fail handler
		 */
		fail_mautominfo: function() {
			return;
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 14: "Gespeicherte Suchen" - Prepare
		 */
		prepare_gespsuchen: function(modulselector) {
			if(!isu(this.parameter) && !isu(this.parameter.id)) {
				try {
					// Delete a search
					var id = parseInt(this.parameter.id);
					// Request with "blind" mode
					$.getJSONP(AUBIUC.gwbbaseurl+"meine_suchen.php?aktion=entfernen&suche_id="+id+"&json=1", null, { ident: -1 });

					// Remove <div> with car
					$("#gespsuchen_"+id).remove();
					
					return false;
				} catch(e) { 
					// Cancel Update of element!
					return false; 
				}
				return false;
			}
			else {
				return ({
					modulselector: modulselector,
					url: "searches",
					options: {
						loading_wrap: "<tr><td>" // Wrap the loading indicator in ... Elements are auto. closes ("</td></tr>")
					},
					tokenparams: {
						count: 4
					},
					dataparams: {
						iruserid: AUBIUC.irui,
						mode: 1, // Status = 1 ("meine Suchen")
						count: 4
					}
				});
			}
		},
		
		/*
		 * Module 14: "Gespeicherte Suchen" - Success
		 */
		success_gespsuchen: function(data) {
			var usi=data.usi;
			var that = this;
			var content = [];
			
			// Are there searches to process?
			if(!isu(usi) && isu(data.searches) || data.searches.length == 0) {
				
				// No searches:
				$(this.mpar[usi].modulselector)
				.empty()
				.prepend("<tr><td><div class=\"uc-no-searches\">"+AUBIUC.texts.no_searches+"</div></td></tr>")
				.rtemp();
				
				// Remove "Alle Suchen"
				$("#gespeicherte-suchen div.listenende-links").remove();
				
				return false;
			}

			for(var i=0, ol = data.searches.length; i < ol && i < 4;i++) {
				content[content.length] = "<tr id=\"gespsuchen_"+data.searches[i].id+"\">"+
					"<td>"+
						data.searches[i].texts.join("; ")+
						"<div class=\"suche-optionen\">"+
							"<a class=\"cmd cmd-exec\" href=\""+AUBIUC.gwbbaseurl+"my_abild.php?option=ausfuehren&amp;dienst=suche&amp;id="+data.searches[i].id+"\">ausf&uuml;hren</a>"+
							"<a class=\"cmd cmd-delete\" href=\"javascript:void(0);\" id=\"cmd-delete_"+data.searches[i].id+"\">entfernen</a>"+
						"</div>"+
					"</td>"+
				"</tr>";
			}
			
			// Clear and append
			$(this.mpar[usi].modulselector)
			.rtemp()
			.empty()
			.append(content.join(""));
			
			// register click handler for deleting searches
			$(this.mpar[usi].modulselector+" .cmd-delete").each(function(i) {
   				$(this).unbind().click(function() { 
   					// Reload
   					try {
	   					var id = ($(this).attr("id").split("_"))[1];
	   					// Reload with mode=delete
   						AUBIUC.reload("gespsuchen", { id: id, mode: "remove" } );
   						return false;
   					}
   					catch (e) {
   						return false;
   					}
   				});
			});
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 15: "Gemerkte inserate" (Liste) - Prepare
		 */
		prepare_gemerkteinslist: function(modulselector) {
			if(!isu(this.parameter) && !isu(this.parameter.id) && this.parameter.mode == "remove") {
				try {
					var id = parseInt(this.parameter.id);
					
					// Transparent request
					// delete car from "gemerkte inserate"
					$.getJSONP(AUBIUC.gwbbaseurl+"meine_gemerkten_inserate.php?aktion=entfernen&id="+id+"&json=1", null, { ident: -1 });
					
					// Remove <div>
					$("#uc-noted-car-"+id).remove();
					
					// End here
					return false;
					
				} catch(e) {}
			}
			
			return ({
				modulselector: modulselector,
				url: "vehicle", // URL of JSON-Data API
				tokenparams: {
					count: 3, // Number of noted cars
					mode: 3, // Mode 3 = "gemerkte Inserate"
					iruserid: AUBIUC.irui // User ID in InterRed System
				},
				dataparams: {
					count: 3,
					extended: 1 // Full set of infos for the cars
				}
			});
			
		},
		
		/*
		 * Module 15: "Gemerkte inserate" - Success
		 */
		success_gemerkteinslist: function(data) {
			var usi = data.usi;
			var that = this;
			var module = "gemerkteinslist";
			var c = [];
			var token = this.storageload(module,"token");
			var sel = $(this.mpar[usi].modulselector);
			
			// Do we return from "delete" call to the Autoboerse?
			// LATER: Still needed?
			/*if(data.hits == 1 && data.message === "removed") {
				// Reload Module, this time the content
				AUBIUC.reload(module);
				// Return false
				return false;
			}*/
			
			// Are there searches to process or
			// are all cars in noted list deleted?
			if(!isu(usi) && isu(data.cars) || data.cars.length == 0) {
				
				// Insert Text
				sel
				.empty()
				.prepend("<div class=\"uc-no-searches\">"+((token.flags.deleted_cars > 0)?AUBIUC.texts.noted_all_sold:AUBIUC.texts.no_noted_cars)+"</div>")
				.rtemp();
				
				// Remove Link
				$("#gemerkte-fz div.listenende-links").remove();
				
				return false;
			}

			// Read number of cars not found
			if(token.flags.deleted_cars > 0) {
				c[c.length] = "<div class=\"uc-noted-del\">"+((token.flags.deleted_cars>1)?token.flags.deleted_cars+" Ihrer gemerkten Fahrzeuge wurden":"Ein gemerktes Fahrzeug wurde")+" inzwischen durch den Anbieter verkauft.</div>";
			}
			
			c[c.length] = "<div class=\"uc-notedcars\">";
			for(var i=0, ol = data.cars.length; i < ol && i < 3;i++) {
				c[c.length] = "<div class=\"inserat-L\" id=\"uc-noted-car-"+data.cars[i].id+"\">";
				c[c.length] = 	"<div class=\"inserat-img\"><a href=\""+data.cars[i].id+"\"><img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" /></a></div>";
				c[c.length] = 	"<div class=\"inserat-data\">";
				c[c.length] = 		"<div class=\"inserat-header\">";
				c[c.length] = 			"<div class=\"inserat-data-modell\"><a href=\""+data.cars[i].id+"\">"+data.cars[i].make+" "+data.cars[i].model+"</a></div>";
				c[c.length] = 			"<div class=\"inserat-data-funktionen\"><a class=\"cmd cmd-delete\" href=\"javascript:void(0);\" id=\"cmd-gmrkliste-delete_"+data.cars[i].id+"\">entfernen</a></div>";
				c[c.length] = 		"</div>";
				c[c.length] = 		"<div class=\"inserat-einzelangaben\">";
				c[c.length] = 			"<ul>";
				c[c.length] = 				"<li class=\"ea-preis\">EUR "+this.formatnumber(data.cars[i].price)+"</li>";
				c[c.length] = 				"<li class=\"ea-ez\">EZ "+this.twodig(data.cars[i].initial_registration_date.month)+"/"+new String(data.cars[i].initial_registration_date.year).substr(2)+"</li>";
				c[c.length] = 				"<li class=\"ea-km\">"+this.formatnumber(data.cars[i].mileage)+" km</li>";
				c[c.length] = 				"<li class=\"ea-aufbau\">"+data.cars[i].body_type+"</li>";
				c[c.length] = 				"<li class=\"ea-farbe\">"+data.cars[i].color+"</li>";
				c[c.length] = 			"</ul>";
				c[c.length] = 		"</div>";
				c[c.length] = 	"</div>";
				c[c.length] = "</div>";
			}
			c[c.length] = "</div>";
			
			// Clear and append
			sel
			.after(c.join(""))
			.remove()
			.rtemp();
			
			// register click handler for deleting searches
			$(this.mpar[usi].modulselector+" .cmd-delete").each(function(i) {
   				$(this).unbind().click(function() { 
   					// Reload
   					try {
	   					var id = ($(this).attr("id").split("_"))[1];
	   					// Reload with mode=remove
   						AUBIUC.reload(module, { id: id, mode: "remove" } );
   					}
   					catch (e) {
   						return false;
   					}
   				});
			});
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 16: "Meine Fahrzeuge" - Prepare
		 * "Anzahl in Boerse", "In Boerse ab", "In Boerse bis"
		 */
		prepare_meinefahrzeuge: function(modulselector) {
			// Extract aubiid
			return ({
				modulselector: modulselector,
				url: "info",
				options: {
					loadingindicator: "http://www.autobild.de/api/ajax-loading-white-small.gif", // Custom loading sign
					loadingselector: ".uc-loading" // Additional selector for loading-indicator
				},
				dataparams: {
					aubiid: $(modulselector).aubiid()
				}
			});
		},
		
		/*
		 * Module 16: "Meine Fahrzeuge" - Success
		 * "Anzahl in Boerse", "In Boerse ab", "In Boerse bis"
		 * TODO: suchen_start mit aubi_id als Parameter
		 */
		success_meinefahrzeuge: function(data) {
			var usi=data.usi;
			var base = "<a href=\""+AUBIUC.gwbbaseurl+"suchen_start.php?aubi_id="+((isu(data.aubi_id))?"":data.aubi_id);
			var txt0 = (data.count>0)?base+"\">"+AUBIUC.formatnumber(data.count)+" Inserat"+((data.count>1)?"e":"")+"</a>":"Keine";
			var txt1 = (data.min_price>0)?base+"&preis_von="+data.min_price+"&preis_bis="+data.min_price+"\">EUR "+AUBIUC.formatnumber(data.min_price)+"</a>":"-";
			var txt2 = (data.max_price>0)?base+"&preis_von="+data.max_price+"&preis_bis="+data.max_price+"\">EUR "+AUBIUC.formatnumber(data.max_price)+"</a>":"-";
			
			// "Anzahl in Boerse":
			$(this.mpar[usi].modulselector+" .uc-boerse-anzahl")
			.empty()
			.append(txt0)
			.rtemp();
			
			// "In Boerse ab"
			$(this.mpar[usi].modulselector+" .uc-boerse-eur-ab")
			.empty()
			.append(txt1)
			.rtemp();
			
			// "In Boerse bis"
			$(this.mpar[usi].modulselector+" .uc-boerse-eur-bis")
			.empty()
			.append(txt2)
			.rtemp();
		},
		
		/*
		 * Module 16: "Meine Fahrzeuge" - Custom failhandler
		 * "Anzahl in Boerse", "In Boerse ab", "In Boerse bis"
		 */
		fail_meinefahrzeuge: function(usi) {
			$(this.mpar[usi].modulselector+" .uc-loading")
			.empty()
			.append("unbekannt")
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 16 (Part 2): "Meine Wunschfahrzeuge" - Prepare
		 * "Anzahl in Boerse", "In Boerse ab", "In Boerse bis"
		 */
		prepare_mwunschkfz: function(modulselector) {
			return ({
				modulselector: modulselector,
				url: "info",
				options: {
					loadingindicator: "http://www.autobild.de/api/ajax-loading-white-small.gif", // Custom loading sign
					loadingselector: ".uc-loading" // Additional selector for loading-inddicator
				},
				dataparams: {
					aubiid: $(modulselector).aubiid()
				}
			});
		},
		
		/*
		 * Module 16 (Part 2): "Meine Wunschfahrzeuge" - Success
		 * "Anzahl in Boerse", "In Boerse ab", "In Boerse bis"
		 */
		success_mwunschkfz: function(data) {
			var usi=data.usi;
			var base = "<a href=\""+AUBIUC.gwbbaseurl+"suchen_start.php?aubi_id="+((isu(data.aubi_id))?"":data.aubi_id);
			var txt0 = (data.count>0)?base+"\">"+AUBIUC.formatnumber(data.count)+" Inserat"+((data.count>1)?"e":"")+"</a>":"Keine";
			var txt1 = (data.min_price>0)?base+"&preis_von="+data.min_price+"&preis_bis="+data.min_price+"\">EUR "+AUBIUC.formatnumber(data.min_price)+"</a>":"-";
			var txt2 = (data.max_price>0)?base+"&preis_von="+data.max_price+"&preis_bis="+data.max_price+"\">EUR "+AUBIUC.formatnumber(data.max_price)+"</a>":"-";
			
			// "Anzahl in Boerse":
			$(this.mpar[usi].modulselector+" .uc-boerse-anzahl")
			.empty()
			.append(txt0)
			.rtemp();
			
			// "In Boerse ab"
			$(this.mpar[usi].modulselector+" .uc-boerse-eur-ab")
			.empty()
			.append(txt1)
			.rtemp();
			
			// "In Boerse bis"
			$(this.mpar[usi].modulselector+" .uc-boerse-eur-bis")
			.empty()
			.append(txt2)
			.rtemp();
		},
		
		/*
		 * Module 16 (Part 2): "Meine Fahrzeuge" - Custom failhandler
		 * "Anzahl in Boerse", "In Boerse ab", "In Boerse bis"
		 */
		fail_mwunschkfz: function(usi) {
			$(this.mpar[usi].modulselector+" .uc-loading")
			.empty()
			.append("unbekannt")
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 20: "Gemerkte Inserate" - Prepare
		 */
		prepare_gemerkteins: function(modulselector) {
			return ({
				modulselector: modulselector,
				url: "vehicle",
				tokenparams: {
					count: 3,
					mode: 3,
					iruserid: AUBIUC.irui
				},
				dataparams: {
					count: 3
				}
			});
		},
		
		/*
		 * Module 20: "Gemerkte Inserate" - Success
		 */
		success_gemerkteins: function(data) {
			var usi=data.usi;
			var c = [];
			var token = this.storageload("gemerkteins","token");
			var sel = $(this.mpar[usi].modulselector);
			
			// Are there searches to process or
			// are all cars in noted list deleted?
			if(!isu(usi) && isu(data.cars) || data.cars.length == 0) {
				sel
				.empty()
				.prepend("<div class=\"uc-no-searches\">"+((token.flags.deleted_cars > 0)?AUBIUC.texts.noted_all_sold:AUBIUC.texts.no_noted_cars)+"</div>")
				.rtemp();
				
				return false;
			}
			
			// Read number of cars not found
			if(token.flags.deleted_cars > 0) {
				c[c.length] = "<div class=\"uc-noted-del\">"+((token.flags.deleted_cars>1)?token.flags.deleted_cars+" Ihrer gemerkten Fahrzeuge wurden":"Ein gemerktes Fahrzeug wurde")+" inzwischen durch den Anbieter verkauft.</div>";
			}
			
			for(var i=0, ol = data.cars.length; i < ol && i < 3;i++) {
				c[c.length] = "<div class=\"inserat-S uc-islink\" onclick=\"AUBIUC.go('"+data.cars[i].id+"')\">";
				c[c.length] = 	"<div class=\"inserat-img\">";
				c[c.length] = 		"<img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" />";
				c[c.length] = 	"</div>";
				c[c.length] = 	"<div class=\"inserat-data\">";
				c[c.length] = 		"<ul>";
				c[c.length] = 			"<li>"+data.cars[i].make+"</li>";
				c[c.length] = 			"<li>"+data.cars[i].model+"</li>";
				c[c.length] = 			"<li>"+this.formatnumber(data.cars[i].mileage)+" km</li>";
				c[c.length] = 			"<li>"+data.cars[i].power_kw+" kW ("+this.convertpower(data.cars[i].power_kw)+" PS)</li>";
				c[c.length] = 			"<li>EZ "+this.twodig(data.cars[i].initial_registration_date.month)+"/"+data.cars[i].initial_registration_date.year+"</li>";
				c[c.length] = 			"<li>&euro; "+this.formatnumber(data.cars[i].price)+"</li>";
				c[c.length] = 		"</ul>";
				c[c.length] = 	"</div>";
				c[c.length] = "</div>";
			}
			
			sel
			.empty()
			.prepend(c.join(""))
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 21: "Meine Suchen" (Vertikal; Klappbar Modul) - Prepare
		 */
		prepare_meinesuchen: function(modulselector) {
			// Modify Moduleselector to only include variable contents
			return ({
				modulselector: modulselector,
				url: "searches", 
				tokenparams: {
					count: 3
				},
				dataparams: {
					count: 3,
					mode: 1,
					iruserid: AUBIUC.irui
				}
			});
		},
		
		/*
		 * Module 21: "Meine Suchen" (Vertikal; Klappbar Modul) - Success
		 */
		success_meinesuchen: function(data) {
			var usi=data.usi;
			var content = "";
			var sel = $(this.mpar[usi].modulselector);
			
			// No data?
			if(isu(data.searches)) {
				sel
				.empty()
				.prepend("<div class=\"uc-no-searches\">"+AUBIUC.texts.no_searches+"</div>")
				.rtemp()
				.prev() // remove "Alle anzeigen"
				.remove();
				return false;
			}
			
			for(var i=0, ol = data.searches.length; i < ol && i < 3;i++) {
				content += "<div class=\"fzsuche-daten\">"+
					"<div class=\"data-hersteller\">"+data.searches[i].texts[0]+"</div>"+
					"<div class=\"data-marke\">"+(isu(data.searches[i].texts[1])?"":data.searches[i].texts[1])+"</div>"+
					"<div class=\"data-optionen\">"+(isu(data.searches[i].texts[2])?"":data.searches[i].texts[2])+" [...]</div>"+
					"<div class=\"links-funktionen\">"+
						"<a class=\"cmd cmd-edit\" href=\""+AUBIUC.gwbbaseurl+"my_abild.php?option=bearbeiten&amp;dienst=suche&amp;id="+data.searches[i].id+"\">bearbeiten</a>"+
						"<a class=\"cmd cmd-exec\" href=\""+AUBIUC.gwbbaseurl+"my_abild.php?option=ausfuehren&amp;dienst=suche&amp;id="+data.searches[i].id+"\">ausf&uuml;hren</a>"+
					"</div>"+
				"</div>";
			}
			
			// Modify DOM
			sel
			.empty()
			.prepend(content)
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 22: "Zuletzt angesehende Inserate" - Prepare
		 */
		prepare_angesehen: function(modulselector) {
			return ({
				modulselector: modulselector,
				url: "vehicle",
				tokenparams: {
					count: 3,
					mode: 2
				},
				dataparams: {
					count: 3
				}
			});
		},
		
		/*
		 * Module 22: "Zuletzt angesehende Inserate" - Success
		 */
		success_angesehen: function(data) {
			var usi=data.usi;
			var content = [];
			var sel = $(this.mpar[usi].modulselector);
			
			// Are there viewed cars?
			if(isu(data.cars) || data.cars.length == 0) {
				sel
				.empty()
				.prepend("<div class=\"uc-no-searches\">"+AUBIUC.texts.no_viewed_cars+"</div>")
				.rtemp();
				
				return false;
			}
			
			for(var i=0, ol = data.cars.length; i < ol && i < 3;i++) {
				content[content.length] =  "<div class=\"inserat-S uc-islink\" onclick=\"AUBIUC.go('"+data.cars[i].id+"')\">"+
						"<div class=\"inserat-img\">"+
							"<img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" />"+
						"</div>"+
						"<div class=\"inserat-data\">"+
							"<ul>"+
								"<li>"+data.cars[i].make+"</li>"+
								"<li>"+data.cars[i].model+"</li>"+
								"<li>"+this.formatnumber(data.cars[i].mileage)+" km</li>"+
								"<li>"+data.cars[i].power_kw+" kW ("+this.convertpower(data.cars[i].power_kw)+" PS)</li>"+
								"<li>EZ "+this.twodig(data.cars[i].initial_registration_date.month)+"/"+data.cars[i].initial_registration_date.year+"</li>"+
								"<li>&euro; "+this.formatnumber(data.cars[i].price)+"</li>"+
							"</ul>"+
						"</div>"+
					"</div>";
			}
			
			// Replace
			sel
			.empty()
			.prepend(content.join(""))
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 23: "Zuletzt gesucht" (Vertikal; Klappbar Modul) - Prepare
		 */
		prepare_zuletztgesucht: function(modulselector) {
			// Modify Moduleselector to only include variable contents
			return ({
				modulselector: modulselector,
				url: "searches", 
				options: {
					skiptosuccess: true
				},
				dataparams: {
					mode: 2, // Show all executed searches
					count: 3
				}
			});
		},
		
		/*
		 * Module 23: "Zuletzt gesucht" (Vertikal; Klappbar Modul) - Success
		 */
		success_zuletztgesucht: function(data) {
			var usi=data.usi;
			var c = [];
			var sel = $(this.mpar[usi].modulselector)
			if(isu(data.searches) || data.searches.length == 0) {
				sel
				.empty()
				.prepend("<tr><td><div class=\"uc-no-searches\">"+AUBIUC.texts.no_exec_searches+"</div></td></tr>")
				.rtemp();
				return false;
			}
			for(var i=0, ol = data.searches.length; i < ol && i < 3;i++) {
				c[c.length] = "<div class=\"fzsuche-daten\">";
				c[c.length] =	"<div class=\"data-hersteller\">"+data.searches[i].texts[0]+"</div>";
				c[c.length] =	"<div class=\"data-marke\">"+((!isu(data.searches[i].texts[1]))?data.searches[i].texts[1]:"")+"</div>";
				c[c.length] =	"<div class=\"data-optionen\">"+((!isu(data.searches[i].texts[2]))?data.searches[i].texts[2]:"")+"</div>";
				c[c.length] =	"<div class=\"data-optionen\">"+((!isu(data.searches[i].texts[3]))?data.searches[i].texts[3]:"")+" [...]</div>";
				c[c.length] =	"<div class=\"links-funktionen\">";
				c[c.length] =		"<a class=\"cmd cmd-edit\" href=\""+AUBIUC.gwbbaseurl+"my_abild.php?option=bearbeiten&amp;dienst=suche&amp;id="+data.searches[i].id+"\">&auml;ndern</a>";
				c[c.length] =		"<a class=\"cmd cmd-exec\" href=\""+AUBIUC.gwbbaseurl+"my_abild.php?option=ausfuehren&amp;dienst=suche&amp;id="+data.searches[i].id+"\">ausf&uuml;hren</a>";
				c[c.length] =	"</div>";
				c[c.length] = "</div>";
			}
			
			// Modify DOM
			$(this.mpar[usi].modulselector)
			.empty()
			.prepend(c.join(""))
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 24: "Passend Gebrauchtwagen" - Prepare
		 */
		prepare_passendegwb: function(modulselector) {
			var that = this;
			if(!isu(this.parameter) && !isu(this.parameter.aubiid)) {
				// If aubiid is not set in the correct node return now
				if(this.parameter.aubiid == null) {
					return false;
				}
				
				// If there is a aubiid in the parameter object,
				// show or hide "passendegwb" line
				var node = $(".modellnavigator .aubiid_"+this.parameter.aubiid.replace(/;/g,"-")+" li.uc-gwb");
				
				// If node is open (expanded), hide it and stop here
				if($(node[0]).attr("class").indexOf("node-expanded") > -1) {
					$(node[0]).removeClass("node-expanded").addClass("node-collapsed");
					return false;
				} 
				else {
					// Show div:
					$(node[0]).removeClass("node-collapsed").addClass("node-expanded");
					
					// When the data is already there, just show it again, don't request new data.
					if($(node[0]).html().indexOf(that.texts.passendegwb_checkstring) > -1) {
						return false;
					}
					
					// Return Values
					return ({
						modulselector: ".modellnavigator .aubiid_"+this.parameter.aubiid.replace(/;/g,"-")+" .uc-passendegwb", // Modify selector name
						url: "vehicle", // URL of JSON-Data API
						options: {  
							next: "div", // For all actions, that replace content, choose $("").next(VALUE) as replacable element
							notokenreuse: true // Do not reuse token, important!
						},
						tokenparams: { 
							count: 3,
							aubiid: this.parameter.aubiid 
						},
						dataparams: {
							count: 3
						}
					});
				}
			}
			else {
				// Bind click event to EVERY class "uc-passendegwb"
				// Executes a reload of this module but this time with actual data
				$(".modellnavigator .uc-passendegwb").each(function(i) {
	   				$(this)
	   				.unbind('click') // There should be only on click event in this case
	   				.click(function() { 
	   					// Parent hopping :)
	   					var aubiid2 = $(this).parent().parent().parent().parent().aubiid();
	   					// Reload
	   					that.reload("passendegwb", { aubiid: aubiid2, state: "expand"});
	   				});
				});
				
				// Don't do the inititalization just yet! (aka. return false)
				return false;
			}
			
		},
		
		/*
		 * Module 24: "Passend Gebrauchtwagen" - Success
		 */
		success_passendegwb: function(data) {
			var usi=data.usi;
			var c = ["<div class=\"node-content-container\">"];
			
			for(var i=0, ol = data.cars.length; i < ol && i < 3;i++) {
				c[c.length] = "<div class=\"inserat-S uc-islink\" onclick=\"AUBIUC.go('"+data.cars[i].id+"')\">";
				c[c.length] = 	"<div class=\"inserat-img\">";
				c[c.length] = 		"<img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" />";
				c[c.length] = 	"</div>";
				c[c.length] = 	"<div class=\"inserat-data\">";
				c[c.length] = 		"<ul>";
				c[c.length] = 			"<li>"+data.cars[i].make+"</li>";
				c[c.length] = 			"<li>"+data.cars[i].model+"</li>";
				c[c.length] = 			"<li>"+this.formatnumber(data.cars[i].mileage)+" km</li>";
				c[c.length] = 			"<li>"+data.cars[i].power_kw+" kW ("+this.convertpower(data.cars[i].power_kw)+" PS)</li>";
				c[c.length] = 			"<li>EZ "+this.twodig(data.cars[i].initial_registration_date.month)+"/"+data.cars[i].initial_registration_date.year+"</li>";
				c[c.length] = 			"<li>&euro; "+this.formatnumber(data.cars[i].price)+"</li>";
				c[c.length] = 		"</ul>";
				c[c.length] = 	"</div>";
				c[c.length] = "</div>";
			}
			c[c.length] = "</div>";
			
			// Clear and append
			$(this.mpar[usi].modulselector)
			.next("div")
			.empty()
			.append(c.join(""))
			.rtemp();
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Module 27: "Inserate aus ORT" (2x3) - Prepare
		 */
		prepare_ins2x3: function(modulselector) {
			// Get ZIP ("uc-plz_20356"):
			var tmp = $(".mod-inserate2").attr("class");
			var zip = "";
			if(!isu(tmp)) {
				zip = tmp.substr(tmp.indexOf("uc-plz_")+7,5);
			}
			// Return Variables
			return ({
				modulselector: modulselector,
				url: "vehicle",
				options: {
					notokenreuse: true
				},
				tokenparams: {
					count: 6,
					zip: zip
				},
				dataparams: {
					count: 6
				}
			});
		},
		
		/*
		 * Module 27: "Inserate aus ORT" (2x3) - Success
		 */
		success_ins2x3: function(data) {
			var c = ["<div id=\"mod-inserate2-row1\">"];
			for(var i=0, ol = data.cars.length; i < ol && i < 6;i++) {
				c[c.length] = "<div class=\"inserat-S2 uc-islink\" id=\"mod-inserate2-inserat1\" onclick=\"AUBIUC.go('"+data.cars[i].id+"')\">";
				c[c.length] = "	<div class=\"inserat-img\">";
				c[c.length] = "		<img src=\""+this.motosoimageurl(data.cars[i].image_ref)+"\" alt=\""+data.cars[i].make+" "+data.cars[i].model+"\" title=\"\" />";
				c[c.length] = "	</div>";
				c[c.length] = "	<div class=\"inserat-data\">";
				c[c.length] = "		<div class=\"inserat-data-modell\" title=\""+data.cars[i].make+" "+data.cars[i].model+"\">"+data.cars[i].make+" "+data.cars[i].model+"</div>";
				c[c.length] = "		<div class=\"inserat-data-km\">"+this.formatnumber(data.cars[i].mileage)+" km</div>";
				c[c.length] = "		<div class=\"inserat-data-preis\">EUR "+this.formatnumber(data.cars[i].price)+"</div>";
				c[c.length] = "	</div>";
				c[c.length] = "</div>";
				
				// Middle divider
				if(i==2) {
					c[c.length] = "</div><div id=\"mod-inserate2-row2\">";
				}
			}
			c[c.length] = "</div>";
			
			// Replace content
			$(this.mpar[data.usi].modulselector)
			.empty()
			.prepend(c.join(""))
			.rtemp();
			
			// Replace city name
			// Select only the first span
			if(!isu(data.cars[0].city)) {
				var temp = $("div.mod-inserate2 div.mod-title")[0];
				$("span",temp)
				.empty()
				.prepend("Inserate aus "+data.cars[0].city);
			}
		},
		
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		/* ********************************************************************************************************* */
		
		/*
		 * Generate URL of image based on Hash
		 * e.g. 37_26231811_a53b1a9cbd6b28f642d45d6b07b651e2 = http://media.autobild.de/autoboerse/picture/e2/51/37_26231811_a53b1a9cbd6b28f642d45d6b07b651e2_2.jpg
		 */
		mediaurl: function(hash,size) {
			if(isu(size) || size < 1) {
				size = 3;
			}
			var url = "http://media.autobild.de/autoboerse/picture/"+hash.substr(hash.length-2,2)+"/"+hash.substr(hash.length-4,2)+"/"+hash+"_"+size+".jpg";
			return url;
		},
		
		/*
		 * check for image-url
		 */
		
		motosoimageurl: function(url) {
      if(typeof url == "undefined")
      {
        return 'http://media.autobild.de/autoboerse/picture/00/00/00000000000000000000000000000000_5.jpg';
      }
      else
      {
        return url;
      }
    },
		
		/*
		 * Format a number with decimal seperator
		 * Input: when float use . as decimal seperator (123.45)
		 */
		formatnumber: function(nStr) {
			var inD = ".", outD = ",", sep = ".";
			nStr += '';
			var dpos = nStr.indexOf(inD);
			var nStrEnd = '';
			if (dpos != -1) {
				nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
				nStr = nStr.substring(0, dpos);
			}
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(nStr)) {
				nStr = nStr.replace(rgx, '$1' + sep + '$2');
			}
			return nStr + nStrEnd;
		},
		
		/*
		 * Format month with leading zero
		 */
		twodig: function(month) {
			if(parseInt(month,10) < 10) {
				return "0"+month;
			}
			return month;	
		},
		
		/*
		 * Convert PS to kw and kW to PS
		 */
		convertpower: function(power, convertto) {
			if(convertto == "kw") {
				val = parseInt(power,10) / this.kwtops;
			} 
			else {
				val = this.kwtops * parseInt(power,10);
			}
			return Math.round(val);
		},
		
		/*
		 * Insert general purpose failure message
		 */
		failnotice: function(usi) {
			var sel = (!isu(this.mpar[usi].options.next))?$(this.mpar[usi].modulselector).next(this.mpar[usi].options.next):$(this.mpar[usi].modulselector);
			$(sel)
			.empty()
			.prepend(
			"<div class=\"uc-timeout\">"+this.texts.timeout+"</div>")
			.rtemp();
		},
		
		/*
		 * Replaces Content of Element with a "loading" indicator
		 */
		loading: function(usindex) {
			var sel = $(this.mpar[usindex].modulselector);
			var image = this.ajaxloadingimage;
			var that = this;
			
			// Select custom elements?
			if(!isu(this.mpar[usindex].options.loadingselector)) {
				sel = $(this.mpar[usindex].options.loadingselector,sel);
			}
			
			// Select NEXT Element?
			if(!isu(this.mpar[usindex].options.next)) {
				sel = $(sel).next(this.mpar[usindex].options.next);
			}
			
			// Custom image?
			if(!isu(this.mpar[usindex].options.loadingindicator)) {
				image = this.mpar[usindex].options.loadingindicator;
			}
			
			$.each(sel, function() {
				// remember height
				var height = $(this).height();
			
				// Center for IE
				$(this).empty()
				// Set height of container so there is no flickering
				// TODO: Fix! rtemp must remove height and reset it
				//.height(height+"px")
				// Center image vertically and horizontal:
				.addClass("us-center-vrt");
				
				// Insert the image
				$(this).append("<img src=\""+image+"\" class=\"uc-indicator\" alt=\"Inhalt wird geladen...\" class=\"uc-loading\" />");
				
				// Wrap the image in ...
				if(!isu(that.mpar[usindex].options.loading_wrap)) {
					$(this).prepend(that.mpar[usindex].options.loading_wrap);
				}
			});
		},
		
		/*
		 * Aufraeumen
		 */
		cleanup: function() {
			this.mpar = null;
			this.updaterstack = null;
			this.modulstorage = null;
			// Bye Bye
			AUBIUC = null;
		},
		
		/*
		 * Trigger on element to reload itself
		 */
		reload: function(moduleid, parameter) {
			// Get the one module
			var found = false;
			var modules =this.modules;
			// some module_ids require reload of IVW
			var ivw_reload = new Array('ada_3er','ada_1er','ada_6er','mautom','ins2x3');
			for (var i = 0; i < ivw_reload.length; ++i)
			{
				if(ivw_reload[i] == moduleid)
				{
					var ivw_pixel = $("#content_ivw_pixel");
					if(ivw_pixel.attr("src"))
					{
						var url = ivw_pixel.attr("src").split("?");
						ivw_pixel.attr("src", url[0] + "?d=" + Math.round(Math.random()*10000000000));
					}
				}
			}
			for(var i = 0, ol = modules.length; i < ol && !found; i++ ) {
				if(this.modules[i].id == moduleid) {
					// Trigger reload
					this.init([modules[i]],parameter);
					found = true;
				}
			}
			return false;
		},
			
		/*
		 * Find module element by id
		 */	
		findmodulebyid: function(moduleid) {
			for(var i = 0, ol = this.modules.length; i < ol; i++ ) {
				if(this.modules[i].id == moduleid) {
					return this.modules[i];
				}
			}
			return null;
		},
		
		/*
		 * Bind click event.
		 * Bug in IE causes Event inside an event to fire again, causing an endless loop of events
		 */
		clickreload: function(selector, moduleid) {
			$(selector).unbind("click").click(function() { AUBIUC.reload(moduleid); });			
		}
		,
		
		/*
		 * Reload module with next car per token
		 */
		nextcar: function(moduleid, nextcarindex) {
			AUBIUC.storagesave(moduleid,"current_car",nextcarindex);
			AUBIUC.reload(moduleid);
		},
		
		/*
		 * Reload module with previous car per token
		 */
		prevcar: function(moduleid, previouscarindex) {
			AUBIUC.storagesave(moduleid,"current_car",previouscarindex);
			AUBIUC.reload(moduleid);
		},
		
		/*
		 * Note a car
		 * Works by noting down the id inside the users cookie.
		 * The corresponding php-file in the usedcar market checks if the cookie is set.
		 * Values seperated by "-"
		 */
		 notecar: function(id, moduleid) {
		 	if(!isu(id) && !isNaN(parseInt(id,10))) {
		 		var cname = "uc_note_cars";
		 		var duplicate = false;
		 		// Get Cookie
		 		var cars = $.cookieget(cname);
		 		// Check if duplicate ID
		 		var carsarray = cars.split("-");
		 		if(carsarray[0] == "") {
		 			carsarray = [];
		 		}
		 		for(var i=0; i < carsarray.length && !duplicate; i++) {
		 			if(carsarray[i] == id.toString(16)) {
		 				duplicate = true;
		 			}
		 		}
		 		if(!duplicate) {
		 			carsarray[carsarray.length]=id.toString(16);
		 			cars = carsarray.join("-");
		 			// Set cookie
		 			$.cookieset(cname, cars, { domain: 'autobild.de', path: '/' });
		 		}
		 	}
		 	
		 	// Change HTML to display notice
		 	if(!isu(moduleid)) {
		 		// Change HTML to display note-message
		 		$(this.findmodulebyid(moduleid).selector+" .cmd-savelisting")
		 		// Unbind "click" event
		 		.unbind("click").removeAttr("href")
		 		// Remove Class
		 		.removeClass("cmd-savelisting")
		 		// Add Notice Icon
		 		.addClass("uc-notice")
		 		// Clear cottnent
		 		.empty()
		 		// Add Notice text
		 		.prepend(this.texts.noted);
		 	}
		 	
		 },
		 
		/*
		 * Storage SAVE
		 */
		storagesave: function(moduleid, key, value) {
			// Check if storage exists
			if(isu(AUBIUC.modulstorage[moduleid])) {
				AUBIUC.modulstorage[moduleid] = {};
			}
			if(!isu(key) && !isu(value)) {
				AUBIUC.modulstorage[moduleid][key] = value;
			}
		},
		
		/*
		 * Storage LOAD
		 */
		storageload: function(moduleid, key) {
			// Check if storage exists
			if(isu(AUBIUC.modulstorage[moduleid])) {
				return null;
			}
			if(isu(key)) {
				return AUBIUC.modulstorage[moduleid];
			}
			return AUBIUC.modulstorage[moduleid][key];
		},
		
		/*
		 * Watch for inflight JSONP requests
		 */
		watchJSONP: function() {
			var now = (new Date()).getTime();
			$.each(AUBIUC.inflight, function(id,value) {
				if (!isu(value) &&
					now - value.start >= (value.timeout*1000) ) {
					// Timeout! Remove Updater + inflight
					if(value.ident != null) {
						// Call Timeout of Updater
						try {
							AUBIUC.updaterstack[value.ident].timeout(id);
						}
						catch (e) {	}

						// Remove inflight
						delete AUBIUC.inflight[id];
						AUBIUC.inflightcount--;
					}
				}
			});
			
			// Timer still neccessary?
			if(AUBIUC.inflightcount < 1) {
				AUBIUC.inflightcount = 0;
				// Stop timer
				window.clearInterval(AUBIUC.JSONPtimer);
				delete AUBIUC.JSONPtimer;
			}
		},
		
		/*
		 * Goto on car in the Used Car Market
		 */
		go: function(id) {
			window.location.href = id;
		},
		
		
		/*
		 * Register GWI Events 
		 * Attention: aubigl.js also registers a click event for div.node-label
		 * This event is reset for the "modellnavigator" by calling unbind('click') first.
		 */
		gwieventregister: function() {
			// Register treenode-toggle /was defaultjs: line 224
			$(".modellnavigator .node-label")
			.unbind('click') // unbind aubigl event (see aubigl.js function "impl_treeview")
			.click( 
			function() {
				var dad = $(this).parent();
				if(dad.attr("class").indexOf('node-expanded') >= 0) {
					// Collapse
					dad.removeClass("node-expanded").addClass("node-collapsed");
				}
				else {
					// Expand
					dad.removeClass("node-collapsed").addClass("node-expanded");
				}
			});
		},
		
		/*
		 * Finally: Global final function after success
		 * Clean up stacks for GC
		 */
		finallygeneral: function(usi) {
			delete this.updaterstack[usi];
		},
		
		init_jq_ext: function() {
			/*
			 * Extend jQuery to support JSONP via <script> transport
			 * 
			 * Parameter:
			 * url: "http://...?callback={callback}"
			 * callback: function(json) {} OR null for blind request
			 * params: { ident: [identcode inside updaterstack], timeout: [timeout in seconds] }
			 */
			// Remember outstanding calls here:
			(function($) {
				jQuery.getJSONP = function(url, callback, params) {
				    var self = this;
				    
				    // Default timeout:
				    var timeoutsec = params.timeout || AUBIUC.timeoutsec;
				    
				    // Ident in Updater Stack:
				    var ident = params.ident;
				    
				    // Load the URL (aka. change <HEAD> to include JS call
				    var cbname = cbname(callback);
				    var uri = url.replace(/{callback}/,cbname);
					
					if(callback != null) {
						// Register Timer to check for inflight requests
						if(isu(AUBIUC.JSONPtimer)) {
							AUBIUC.JSONPtimer = setInterval("AUBIUC.watchJSONP();",AUBIUC.watchjsontimer);
						}
						
						// Remember this call for tracking purpose
					    AUBIUC.inflight[cbname] = { start: (new Date()).getTime(), timeout: timeoutsec, ident: ident };
					    AUBIUC.inflightcount++;
					}
							        
					// Load data via <script> transport
				    loadviascript(uri);
				    return cbname;
				
				    function cbname(callback) {
				    	// Get unique identifier
				        var id = (new Date).getTime();
				        var name = 'json_' + id;
						// generate callback
				        var cb = function(json) {
				        	// If function gets executed the JSOP-request is finished,
				        	// delete the inflight check
				            delete AUBIUC.inflight[name];
				            AUBIUC.inflightcount--;
				            // Delete Callback:
				            eval('delete ' + name);
				            callback(json); 
				        };
				        eval(name + ' = cb');
				        return name;
				    }
				
					// Append <script> tag to Head
				    function loadviascript(url) {
				        var script = document.createElement('script');
				        script.type = 'text/javascript';
				        script.src = url;
				        script.id = "s"+cbname;
				        $('head',document).append(script);
				    }
				}	
			})(jQuery);
			
			/*
			 * Extend jQuery for easier cookie handling
			 * SET cookie
			 * Parameters:
			 * name of cookie
			 * value to set
			 * options to set (a { object } :
			 * 	expires: value in days
			 * 	domain: set cookie for domain (eg. .autobild.de)
			 * 	other options see http://stilbuero.de/index.php?s=cookie&x=0&y=0
			 * 
			 */
			(function($) {
				jQuery.cookieset = function(name, value, options) {
				    if (!isu(value)) { 
				    	// name and value given, set cookie
				        options = options || {};
				        if (value === null) {
				            value = '';
				            options.expires = -1;
				        }
				        var expires = '';
				        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				            var date;
				            if (typeof options.expires == 'number') {
				                date = new Date();
				                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				            } else {
				                date = options.expires;
				            }
				            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
				        }
				        var path = options.path ? '; path=' + options.path : '';
				        var domain = options.domain ? '; domain=' + options.domain : '';
				        var secure = options.secure ? '; secure' : '';
				        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
				    } 
				    else { 
				    	// only name given, get cookie
				        var cookieValue = null;
				        if (document.cookie && document.cookie != '') {
				            var cookies = document.cookie.split(';');
				            for (var i = 0; i < cookies.length; i++) {
				                var cookie = jQuery.trim(cookies[i]);
				                // Does this cookie string begin with the name we want?
				                if (cookie.substring(0, name.length + 1) == (name + '=')) {
				                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
				                    break;
				                }
				            }
				        }
				        return cookieValue;
				    }
				}
			})(jQuery);
			
			/*
			 * Extend jQuery for easier cookie handling
			 * GET a the corresponding key from the cookie
			 * returns "" if not set
			 * 
			 */
			(function($) {
				jQuery.cookieget = function(key) {
				    var self = this;
				    var cookie = document.cookie+";";
				    var cookiei = cookie.indexOf(key+"=");
				    var match = "";
				  	// Try to get the key
				  	if(cookiei > -1) {
				  		match = cookie.substring(cookiei+key.length+1,cookie.indexOf(";",cookiei));
				  	}
				    return match;
				}	
			})(jQuery);
			
			/*
			 * Remove Temporary Styles set during JSONP request (etc.)
			 * a jQuery plugin
			 */
			(function($) {
				jQuery.fn.rtemp = function() {
					return this.each(function() {
						$(this).removeClass("us-center-vrt")
						
						// Remove height style
						
						// Remove class attribute also?
						if(isu($(this).attr("class"))) {
							$(this).removeAttr("class");
						}
					});
				}
			})(jQuery);
			
			/*
			 * Extract AUBIID from class
			 * e.g. from class="has-aubiid aubiid_1-2-3"
			 * returns "1;2;3"
			 * a jQuery extension plugin
			 * usage: var aubiid = $("someselector").aubiid();
			 */
			(function($) {
				jQuery.fn.aubiid = function() {
					var classes = $(this).attr("class").split(" ");
					for(var i=0; i < classes.length; i++)
					{
						// When an AUBIID is found, return it in proper format
						if(classes[i].indexOf("aubiid_") > -1) {
							return classes[i].substr(7).replace(/-/g,";");
						} 
					};
					return null;
				}
			})(jQuery);
		}
		
	} // END AUBIUC

	function aubi_init_init() {
		$(document).ready(function() {
			AUBIUC.init();
		});
	}
	
	/*
	 * Load the necessary CSS-File
	 */
	var c = document.createElement('link');
    c.type = 'text/css';
    c.rel = 'stylesheet';
    c.href = AUBIUC.cssfilename;
    document.getElementsByTagName("head")[0].appendChild(c);
	
	/*
	 * Register hook to initialize AUBIUC object
	 * when the DOM is ready
	 */
	if(typeof jQuery == "undefined") {
		// Try again later
		setTimeout("aubi_init_init()",2000);
	}
	else {
		aubi_init_init();
	}
} // END AUBIUC defined

/*
 * One update "thread" for the DOM
 * 
 * Gets a token and, when successful, the data.
 * Starts an update "thread" which calls success_* or fail_* functions on the AUBIUC Object.
 * 
 */
function Updater(indexinsideupdaterstack) {
	// Configuration:
	this.usindex = indexinsideupdaterstack;
	this.scriptidtoken = "";
	this.scriptiddata = "";
}

/*
 * Start the updater process
 */
Updater.prototype.process = function() {
	var params = "";
	var aubiid = "";
	
	// AJAX-Loading sign?
	if(	isu(AUBIUC.mpar[this.usindex].options) || 
		isu(AUBIUC.mpar[this.usindex].options.loadingindicator) ||
		AUBIUC.mpar[this.usindex].options.loadingindicator !== false) {
		
		// Display loading indicator
		AUBIUC.loading(this.usindex);		
	}
	
	// Skip directly to getdata?
	if(AUBIUC.mpar[this.usindex].options.skiptosuccess === true) {
		// Skip to GETDATA
		this.getdata({usi: this.usindex});
		
		return;
	}
	
	// Is there already a token?
	if(	AUBIUC.storageload(AUBIUC.mpar[this.usindex].id,"token") != null &&
		AUBIUC.mpar[this.usindex].options.notokenreuse !== true) {
		// Get used token and save "new" usindex
		var token = AUBIUC.storageload(AUBIUC.mpar[this.usindex].id,"token");
		token.usi = this.usindex;
		AUBIUC.storagesave(AUBIUC.mpar[this.usindex].id,"token",token);
		
		// Skip to GETDATA
		this.getdata(token);
		
		return;
	}
	
	// URL of Token API
	var uri = AUBIUC.databaseurl+"get?callback={callback}&usi="+this.usindex;
	
	// Parameters (create empty object id none)
	if (isu(AUBIUC.mpar[this.usindex].tokenparams)) {
		AUBIUC.mpar[this.usindex].tokenparams = {};
	}
	
	// Append aubiid - tokenparams, local or global
	if(!isu(AUBIUC.mpar[this.usindex].tokenparams.aubiid)) {
		aubiid = AUBIUC.mpar[this.usindex].tokenparams.aubiid;
	}
	else if(!isu(AUBIUC.aubiid)) {
		aubiid = AUBIUC.aubiid;
	}
	else if(!isu(AUBIID)) {
		aubiid = AUBIID;
	}
	
	// Temporarily save available aubiid
	AUBIUC.mpar[this.usindex].tokenparams.aubiid = aubiid;
	
	// Build URL
	params = jQuery.param(AUBIUC.mpar[this.usindex].tokenparams);
	uri += ((uri.indexOf("?") > -1) ? "&" : "?") + params;
	
	// Load Token
	this.scriptidtoken = $.getJSONP(uri, AUBIUC.updaterstack[this.usindex].gettoken_ok, { ident: this.usindex });
};
	
/*
 * Loading of token successful 
 */
Updater.prototype.gettoken_ok = function(token) {
	// Get reference to this
	var self = AUBIUC.updaterstack[token.usi];
	
	// Is the token REALLY ok?
	if(!isu(self) && !isu(token.token))	{
		// Save Token
		AUBIUC.storagesave(AUBIUC.mpar[token.usi].id,"token",token);
		
		// Remove <script>
		self.removescript(self.scriptidtoken);
		
		// Call getdata
		self.getdata(token);
	}
};
	
/*
 * Get DATA
 */
Updater.prototype.getdata = function(token) {
	// Get reference to this
	var self = AUBIUC.updaterstack[token.usi];

	var uri = AUBIUC.databaseurl+AUBIUC.mpar[token.usi].url+"?callback={callback}&transid="+token.token+"&usi="+self.usindex;
	
	// Append parameter
	var params = "";
	if (!isu(AUBIUC.mpar[token.usi].dataparams)) {
		params = jQuery.param(AUBIUC.mpar[token.usi].dataparams);
		uri += ((uri.indexOf("?") > -1) ? "&" : "?") + params;
	}
	
	// Get the necessary data for modifying the DOM via JSOP-script transport
	self.scriptiddata = $.getJSONP(uri,AUBIUC.updaterstack[token.usi].getdata_ok, { ident: self.usindex });
};

/*
 * Loading of data successful
 */
Updater.prototype.getdata_ok = function(json) {
	var self = AUBIUC.updaterstack[json.usi];
	
	// If usi is missing from json object return.
	if(isu(self)) {
		return;
	}
	
	if(!isu(json)) {
		// This needs to be edited after step 1 of compressing the JS build (json)
		eval("AUBIUC.success_"+AUBIUC.mpar[json.usi].functionname+"(json)");
		
		// Remove <script>
		self.removescript(self.scriptiddata);
		
		return;
	}
	else {
		// Simulate failure
		self.timeout(self.scriptiddata);
	}
	
	// Finally:
	try {
		// First try the custom fail function
		eval("AUBIUC.finally_"+AUBIUC.mpar[json.usi].functionname+"(self.usindex)");		
	}
	catch(e) {
		// Fail with default message
		AUBIUC.finallygeneral(json.usi);
	}
};

/*
 * Request timed out in step "token" or "data"
 */
Updater.prototype.timeout = function(id) {
	// Fail :
	try {
		// First try the custom fail function
		eval("AUBIUC.fail_"+AUBIUC.mpar[this.usindex].functionname+"(this.usindex)");		
	}
	catch(e) {
		// Fail with default message
		AUBIUC.failnotice(this.usindex);
	}
	// Remove Updaterstack entry
	delete AUBIUC.updaterstack[this.usindex];	
	
	// Remove <script>
	this.removescript(this.scriptiddata);
	this.removescript(this.scriptidtoken);
};

/*
 * Remove script tag
 */
Updater.prototype.removescript = function(id) {
	if(!isu(id)) {
		$("#s"+id).remove();
	}
}

/*
 * Shortcut to "typeof undefined"
 */
if(typeof isu == "undefined") {
	function isu(obj) {
	   return (typeof obj == "undefined");
	}
}
