/**
 * AJAX Objekt
 */
var SupcatAjax = {
	
	debug:			false,	// Aktiviert den Debug Modus
	request:		null,	// request-Objekt
	requestURL:		null,
	catalogNr:		null,	// Katalognr in dem ich mich grad befinde
	div:			null,	// Div-Element im Frontend in dem die Zusatzkataloge gezeigt werden
	path:			null,
	position:		0,  	// Welcher Block wird derzeit angezeigt, wird
					// mit uebergeben bei Call
	resolution:		null,  	// aktuelle Aufloesung
	minWidth:		910,	// Minimale Aufloesung
	
	/**
	 * Bindet den Aufruf der Funktion getResponse an das Load-Event des Window Objektes
	 * damit kann man die Init-Funktion direkt im Header der HTML Seite aufrufen.
	 */
	init: function(path, catnr, divid) {
		this.addEvent(window, "load", function supcatinit() {SupcatAjax.getResponse(path, catnr, divid);});
	},
	
	/* 
	 * Holen des Responses, d.h. sehen ob die Verbindung moeglich ist
 	 */	
	getResponse: function (path, catnr, divid) {

                // Abbruch wenn Minimale Größer nicht überschritten
		if(this.windowWidth < this.minWidth) 
			return;
		// DEBUG
		if(this.debug) alert("PATH: " + path + "\nCATNR: " + catnr + "\nDIVID: " + divid);
		
		if(!path || !catnr || path == '' || catnr == '' || catnr == '0')
			return;
		
		// Prüfen ob der Parameter divid angegeben wurde
		if(typeof (divid) == "string") {
			this.div = document.getElementById(divid);
		}
					
		// Mozilla, Opera, Safari sowie Internet Explorer 7
		if (typeof XMLHttpRequest != 'undefined') {
		    this.request = new XMLHttpRequest();
		}
		
	    // Internet Explorer 6 und älter
		if (!this.request) {
		    try {
		        this.request = new ActiveXObject("Msxml2.XMLHTTP");
		    } catch(e) {
		        try {
		            this.request = new ActiveXObject("Microsoft.XMLHTTP");
		        } catch(e) {
		            this.request = false;
		        }
		    }
		}
		
		// Request prüfen
		if (this.request) {
			// beim ersten Aufruf muss der Path uebergeben werden
			if(!this.requestURL) this.requestURL = path;
			// Katalognummer
			if(!this.catalogNr) this.catalogNr = catnr;				
			// Aufloesung
			if(!this.resolution) this.resolution = this.windowWidth();
			
			// Zusammenbauen der RequestURL	
			var path = this.requestURL + "?cat=" + this.catalogNr + "&pos=" + this.position + "&res=" + this.resolution;
			
			// DEBUG
			if(this.debug) alert("REQUEST URL: " + path);
			
			// Get fuer 
		    this.request.open('GET', path, true);
		    this.request.onreadystatechange = function() {SupcatAjax.requestCheck();};
		    this.request.send(null);
		}	
		
	},

	/* 
	 * Wenn die Verbinung moeglich ist, dann Aufruf der 
	 * eigentlichen Methode, die die Ausgabe ausgibt
	 */  
	requestCheck: function() {
		switch(this.request.readyState) {
			case 4:
				// Case 4 bedeutet, dass der Request vollstaendig durchgefuehrt wurde
				if(this.request.status != 200) {
					// request.status == 200: alles okay, sonst keine Rueckgabe
					return;
				} 
				else {						
					SupcatAjax.writeContent();
				}
		  	break;				
		}	 		
	},


	/* 
	 * Ausgabe der XML-Anfrage
	 */		
	writeContent: function() {
		if(this.div == null) return;
		
		try {
			var xmlResponse = this.request.responseXML;
			
			// DEBUG
			if(this.debug) alert(this.request.responseText);
			
			// Betrachten des Inputtes als text und umwandeln in XML
			/*
			var daten = this.request.responseText;
			if (window.ActiveXObject) {
				var xmlResponse = new ActiveXObject("Microsoft.XMLDOM");
				xmlResponse.loadXML(daten);
			} 
			else if (document.implementation) {
				var xmlResponse = (new DOMParser()).parseFromString(daten, "text/xml");
			}
			*/
			// Anzeigedauer ermitteln
			var displaytime = parseInt(xmlResponse.getElementsByTagName("displaytime")[0].firstChild.nodeValue) * 1000;			
			// Welche Positiom im Range
			this.position = parseInt(xmlResponse.getElementsByTagName("position")[0].firstChild.nodeValue);
			
			// Spalten ermitteln
			var columns = xmlResponse.getElementsByTagName("column");
			
			// DEBUG
			if(this.debug) alert("RANGE DISPLAYTIME: " + displaytime + "\nRANGE POSITION: " + this.position);
			
			// Auesserer Container fuer Anzeigebereich
			var htmloutput = '<table class="supcat-container-table" cellspacing="0" cellpadding="0"><tr>';	
			
			// Schleife über Spalten
			for (var x=0; x<columns.length; x++) {	
				
				// Weite der Spalte ermitteln
				var width = columns[x].getElementsByTagName("width")[0].firstChild.nodeValue;
				
				// DEBUG
				if(this.debug) alert("COLUMN WIDTH: " + width);
				
				htmloutput += '<td style="width:'+ width + 'px; vertical-align:top;">';
				htmloutput += '<table class="supcat-table" cellpadding="0" cellspacing="0">';
				
				// Blöcke der Spalte ermitteln
				var blocks = columns[x].getElementsByTagName("block");
				
				// Schleife über Blöcke
				for(var y=0;y<blocks.length;y++) {
									
					// Werte der Elemente ermitteln
					var imageurl = unescape(blocks[y].getElementsByTagName("imageurl")[0].firstChild.nodeValue);
					var url = unescape(blocks[y].getElementsByTagName("url")[0].firstChild.nodeValue);					
					var description = (blocks[y].getElementsByTagName("description")[0].firstChild) ? unescape(blocks[y].getElementsByTagName("description")[0].firstChild.nodeValue) : "";
					var target = "_self";
					
					// Prüfen ob URL ein externer Verweis ist
					//if(url.search(/^http|https|ftp/) != -1) target = "_blank";	
					
					// DEBUG
					if(this.debug) alert("BLOCK IMAGEURL: " + imageurl + "\nBLOCK URL: " + url + "\nBLOCK DESCRIPTION:" + description);
									
					// Bild + Verweis
					htmloutput += '<tr><td>';
					htmloutput += '<a href="'+ url +'" target="' + target + '">';
					htmloutput += '<img src="' + imageurl + '" border="0" width="'+ width +'">'; 
					htmloutput += '</a>';
					htmloutput += '</td></tr>';
					
					// Beschreibung
					if(description && description.length > 1) {
						htmloutput += '<tr><td class="supcat-description">';
						htmloutput +=  description; 
						htmloutput += '</td></tr>';					
					}
				}
		
				htmloutput += '</table>';
				htmloutput += '</td>';
			}		
			htmloutput += '</tr></table>';
			
			// DEBUG
			if(this.debug) alert(htmloutput);
			
			// Zeige das DIV Element
			this.div.style.visibility = 'visible';
			this.div.style.display = 'block';
			this.div.innerHTML = htmloutput;
			
			// Erneutes Abfragen
			if(displaytime > 0)
				window.setTimeout("SupcatAjax.getResponse('" + this.requestURL + "','" + this.catalogNr + "')" , displaytime);			
	
		}
		catch (e) {
			// DEBUG
			if(this.debug) alert(e);
		}
	},
	
	/**
	 * Add an event listener
	 *
	 * @param obj Object on which the event will be attached
	 * @param ev Kind of event
	 * @param fu Function which is execute on the event
	 */
	addEvent: function(obj, ev, fu) {
		if (obj.attachEvent)
			obj.attachEvent("on" + ev, fu);
		else
			obj.addEventListener(ev, fu, false);
	},
	
	/**
	 * Ermittelt die Fenstergröße
	 */
	windowWidth: function () {
		if (window.innerWidth) {
	  		return window.innerWidth;
	  	} 
		else if (parent.document.body && parent.document.body.offsetWidth) {
			return parent.document.body.offsetWidth;
		}
		else if (document.body && document.body.offsetWidth) {
	  		return document.body.offsetWidth;
	  	} 
		else {
	  		return 0;
	  	}
	}
};


