var hiresLinkTemplate = 'hires.php?ProductID={ID}';
var salesLinkTemplate = 'sales.php?ProductID={ID}';
var productTemplate =
'<div class="container float{FLOAT}">' +
	'<input type="hidden" class="ID" value="{ID}" />' +
	'<div class="objPicture displayNone floatLeft"><img alt="Object Foto" src="{THUMB}"></div>' +
	'<div class="objDescription floatRight">' +
		'<div class="objHeadline"><span class="companyCol1">{HEADLINE}</span></div>' +
		'<div class="objDetails">' +
			'<table>' +
				'<tr>' +
					'<td class="descCell">{PRICESTRING}:</td>' +
					'<td class="descCell">{PRICE} &euro;</td>' +
				'</tr>' +
				'<tr>' +
					'<td class="descCell">{AREASTRING}:</td>' +
					'<td class="descCell">{AREA} m&sup2;</td>' +
				'</tr>' +
				'<tr>' +
					'<td class="descCell">{ROOMSTRING}:</td>' +
					'<td class="descCell">{ROOMS}</td>' +
				'</tr>' +
			'</table>' +
		'</div>' +
		'<div class="objAddress">{ZIPCODE} {LOCATION}</div>' +
		'<div class="objLink" title="Angebot ansehen"><a href="{LINK}">Details anzeigen &raquo;</a></div>' +
	'</div>' +
'</div>';
//Hier stehen alle Felder drin, die automatisch im produkttemplate ausgetauscht werden
var productInformations = new Array('PRICE', 'AREA', 'ROOMS', 'ZipCode', 'Location', 'HeadLine', 'ID');
var euroFields = new Array('Rent', 'SalePrice', 'GarageRent');
var doubleFields = new Array('LivingSpace', 'LandArea', 'NumberOfRooms');

//Für den Dauerwechsel
var productsHires = null;							//Die Vermietungsprodukte
var productsSales = null;							//Die Verkaufsprodukte
var hiresTimer = null;								//Der Timer
var salesTimer = null;								//Der Timer
var timerDuration = 10000;							//Die Timerdauer
var productsHiresActivated = new Array();			//Diese Produkte waren schon aktiviert
var productsSalesActivated = new Array();			//Diese Produkte waren schon aktiviert
var productsPerView = 2;							//Diese Anzahl an Produkten wird in einer Ansicht gezeigt

function startProductHiresDiaShow(){
	var object = $('#hiresWrapper');
	
	if(productsHires != null && productsHires.length > 0){
		//Produkte heraussuchen
		var productLength = productsHires.length;
		var product = new Array();
		var products = new Array();
		
		for(var i = 0; i < productsPerView; i++){
			//Erst einmal Zufallszahl generieren
			product[i] = parseInt(Math.random() * productLength, 10);
			
			//Wenn schon alle Elemente durchgelaufen sind, fängt es wieder von vorn an
			if(productsHiresActivated.length >= productLength)		productsHiresActivated = new Array();
			
			if(productsHiresActivated.length > 0){
				//Bis ein Ergebnis gefunden ist, welches noch nicht benutzt wurde
				while($.inArray(product[i], productsHiresActivated) >= 0){
					product[i] = parseInt(Math.random() * productLength, 10);
				}
			}
			
			//Wenn ein Ergebnis gefunden wurde, wird dies als Besetzt eingegeben
			productsHiresActivated.push(product[i]);
			
			//Das jeweilige Produkt wird dem Ergebnis hinzugefügt
			products.push(productsHires[product[i]]);
		}
		
		//Produkte füllen
		fillProducts(products, object);
		
		//Timer erneut starten
		hiresTimer = window.setTimeout(function(){
			startProductHiresDiaShow();
		}, timerDuration);
	}
}

function startProductsalesDiaShow(){
	var object = $('#salesWrapper');
	
	if(productsSales != null && productsSales.length > 0){
		//Produkte heraussuchen
		var productLength = productsSales.length;
		var product = new Array();
		var products = new Array();
		
		for(var i = 0; i < productsPerView; i++){
			//Erst einmal Zufallszahl generieren
			product[i] = parseInt(Math.random() * productLength, 10);
			
			//Wenn schon alle Elemente durchgelaufen sind, fängt es wieder von vorn an
			if(productsSalesActivated.length >= productLength)		productsSalesActivated = new Array();
			
			if(productsSalesActivated.length > 0){
				//Bis ein Ergebnis gefunden ist, welches noch nicht benutzt wurde
				while($.inArray(product[i], productsSalesActivated) >= 0){
					product[i] = parseInt(Math.random() * productLength, 10);
				}
			}
			
			//Wenn ein Ergebnis gefunden wurde, wird dies als Besetzt eingegeben
			productsSalesActivated.push(product[i]);
			
			//Das jeweilige Produkt wird dem Ergebnis hinzugefügt
			products.push(productsSales[product[i]]);
		}
		
		//Produkte füllen
		fillProducts(products, object);
		
		//Timer erneut starten
		salesTimer = window.setTimeout(function(){
			startProductsalesDiaShow();
		}, timerDuration);
	}
}

function searchProducts(){
	var post = new Object();
	post.Categories = new Array(1, 3, 5, 6);
	post.AJAXType = 1;
	post.Archived = 0;			//Keine archivierten Immobilien
	
	//AJAX-Request senden
	$.ajax({
		async: "async",
		url: "PHP/Products.php",
		type: "POST",
		dataType: "json",
		data: post,
		success: function(data, status){
			if(data && data.length > 0){
				productsHires = data;
				startProductHiresDiaShow();
			}
		},
		error: function(xmlhttp, statzs, error){
			alert('Verbindung konnte nicht aufgebaut werden!');
		}
	});
	
	post.Categories = new Array(2, 4);
	//AJAX-Request senden
	$.ajax({
		async: "async",
		url: "PHP/Products.php",
		type: "POST",
		dataType: "json",
		data: post,
		success: function(data, status){
			if(data && data.length > 0){
				productsSales = data;
				startProductsalesDiaShow();
			}
		},
		error: function(xmlhttp, statzs, error){
			alert('Verbindung konnte nicht aufgebaut werden!');
		}
	});
}

function fillProducts(data, object){
	var html = '';
	var newObject = function(){
		if(data && data.length > 0){
			var count = 1;
			for(var i in data){
				//Nur X Container werden angezeigt
				if(count > productsPerView)		break;
				
				var product = data[i];
				
				if(product){
					//Ist der aktuelle Datensatz ungerade, steht er links, ansonsten rechts
					var float = 'Right';
					if(count++ & 1)		float = 'Left';
					
					//Daten befüllen
					var temp = productTemplate
									.replace(/{PRICESTRING}/g, getTitleString('{PRICESTRING}', product.Category))
									.replace(/{AREASTRING}/g, getTitleString('{AREASTRING}', product.Category))
									.replace(/{ROOMSTRING}/g, getTitleString('{ROOMSTRING}', product.Category))
									.replace(/{FLOAT}/g, float)
									.replace(/{LINK}/g, getDetailLink(product));
					
					//Übersichtsbild einfügen
					if(product.Pictures && product.Pictures.length > 0){
						temp = temp.replace(/{THUMB}/g, ROOTDIR + product.Pictures[0].Thumb);
					}
					
					//Alle Informationen austauschen
					for(var j in productInformations){
						var information = productInformations[j];
						temp = temp.replace(new RegExp('{' + information.toUpperCase() + '}', 'g'), getInformation(information, product.Category, product));
					}
					
					//Container hinzufügen
					$(object).append(temp.replace(/{[^}]*}/g, '')).ready(function(){
						$(object).find('.container .objPicture, .container .objDescription').fadeIn(1500);
					});
				}
			}
		}
	};
	
	
	if($(object).find('.container').length > 0){
		$(object).find('.container .objPicture, .container .objDescription').fadeOut(1500, function(){
			$(object).empty();
		
			newObject();
		});
	}
	else			newObject();
}

/**
 * Bestimmt von einer Kategorie und dem jeweiligen Typ die Überschrift des jeweiligen Felds
 * 
 * @param type				Was wird gesucht
 * @param category			Welche Produktkategorie
 * @returns 				Der gesuchte String
 */
function getTitleString(type, category){
	var title = '';
	category = parseInt(category, 10);
	
	switch(category){
		//Miete
		case 1:
		case 3:
			if(type == '{PRICESTRING}')			title = 'Kaltmiete';
			else if(type == '{AREASTRING}')		title = 'Wohnfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'Zimmer';
			break;
		//WG-Zimmer
		case 5:
			if(type == '{PRICESTRING}')			title = 'Kaltmiete';
			else if(type == '{AREASTRING}')		title = 'Wohnfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'WG-Gr&ouml;&szlig;e';
			break;
		//Garage
		case 6:
			if(type == '{PRICESTRING}')			title = 'Miete';
			else if(type == '{AREASTRING}')		title = 'Fl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'Objektart';
			break;
		//Verkauf
		case 2:
		case 4:
			if(type == '{PRICESTRING}')			title = 'Verkaufspreis';
			else if(type == '{AREASTRING}')		title = 'Wohnfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'Zimmer';
			break;
		//Gewerbe
		case 7:
			if(type == '{PRICESTRING}')			title = 'Miet-/Kaufpreis';
			else if(type == '{AREASTRING}')		title = 'Gesamtfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'Verkaufsfl&auml;che';
			break;
		case 8:
			if(type == '{PRICESTRING}')			title = 'Miet-/Kaufpreis';
			else if(type == '{AREASTRING}')		title = 'Gesamtfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'B&uuml;rofl&auml;che';
			break;
		case 9:
			if(type == '{PRICESTRING}')			title = 'Preis/Pacht/Miete';
			else if(type == '{AREASTRING}')		title = 'Gesamtfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'B&uuml;rofl&auml;che';
			break;
		case 10:
			if(type == '{PRICESTRING}')			title = 'Preis/Pacht/Miete';
			else if(type == '{AREASTRING}')		title = 'Grundst&uuml;cksfl&auml;che';
			else if(type == '{ROOMSTRING}')		title = 'Kurzfr. bebaubar';
			break;
	}
	
	return title;
}

/**
 * Sucht zur jeweiligen Kategorie und dem gefragten Typ den richtigen Inhalt aus den mitgegebenen Daten heraus.
 * 
 * @param type			Der Typ, was gesucht wird
 * @param category		Die Kategorie des Produkts
 * @param data			Die Daten des Produktes
 * @returns				Der gesuchte String
 */
function getInformation(type, category, data){
	var information = '';
	category = parseInt(category, 10);
	
	switch(category){
		//Miete
		case 1:
		case 3:
			if(type == 'PRICE')				information = formateEuro(data.Rent);
			else if(type == 'AREA')			information = formateDouble(data.LivingSpace);
			else if(type == 'ROOMS')		information = formateDouble(data.NumberOfRooms);
			else							information = data[type];
			break;
		//WG-Zimmer
		case 5:
			if(type == 'PRICE')				information = formateEuro(data.Rent);
			else if(type == 'AREA')			information = formateDouble(data.LivingSpace);
			else if(type == 'ROOMS')		information = formateDouble(data.SharedSize);
			else							information = data[type];
			break;
		//Garage
		case 6:
			if(type == 'PRICE')				information = formateEuro(data.GarageRent);
			else if(type == 'AREA')			information = formateDouble(data.GarageArea);
			else if(type == 'ROOMS')		information = data.ObjectType;
			else							information = data[type];
			break;
		//Verkauf
		case 2:
		case 4:
			if(type == 'PRICE')				information = formateEuro(data.SalePrice);
			else if(type == 'AREA')			information = formateDouble(data.LivingSpace);
			else if(type == 'ROOMS')		information = formateDouble(data.NumberOfRooms);
			else							information = data[type];
			break;
		//Gewerbe
		case 7:
			if(type == 'PRICE')				information = data.OfficeRent;
			else if(type == 'AREA')			information = data.TotalAreaOffice;
			else if(type == 'ROOMS')		information = data.SalesArea + unescape(' m%B2');
			else							information = data[type];
			break;
		case 8:
			if(type == 'PRICE')				information = data.OfficeRent;
			else if(type == 'AREA')			information = data.TotalAreaOffice;
			else if(type == 'ROOMS')		information = data.AreaOffice + unescape(' m%B2');
			else							information = data[type];
			break;
		case 9:
			if(type == 'PRICE')				information = data.Price;
			else if(type == 'AREA')			information = data.TotalAreaOffice;
			else if(type == 'ROOMS')		information = data.GuestRoomArea + unescape(' m%B2');
			else							information = data[type];
			break;
		case 10:
			if(type == 'PRICE')				information = data.Price;
			else if(type == 'AREA')			information = data.LandArea;
			else if(type == 'ROOMS')		information = data.Cultivable;
			else							information = data[type];
			break;
	}
	
	return formatiereDiv(information);
}

function getDetailLink(data){
	var link = '';
	
	//Wenn Daten vorhanden sind
	if(data && data.ID && data.ID > 0 && data.Category && data.Category > 0){
		//Welcher Link muss genommen werden
		switch(parseInt(data.Category, 10)){
			//Miete
			case 1:
			case 3:
			case 5:
			case 6:
				link = hiresLinkTemplate;
				break;
			//Verkauf
			case 2:
			case 4:
				link = salesLinkTemplate;
				break;
		}
		
		//ID hinzufügen
		link = link.replace(/{ID}/g, data.ID);
	}
	
	return link.replace(/{[^}]*}/);
}

$(function(){
	searchProducts();
});
