/*
 * Functions require jQuery
 */

function externalLinks() { $("A[href][rel*='external']").attr("target","_blank"); }

function coverOn(id) { $('#cover_div_' + id).css("display","block"); }
function coverOff(id) { $('#cover_div_' + id).css("display","none"); }
function listeOn(id) {
	$('#liste_tr_' + id).css("background-image",'url("/_images/kachel_back.png")');
	$('#liste_tr_' + id).css("background-repeat",'repeat-x');
}
function listeOff(id) {	$('#liste_tr_' + id).css("background-image","none"); }

function toggleNavi(id,on) {
	if ($("#nav_" + id).css("filter") && $.browser.msie && $.browser.version < 7) {
		if ((on && on == true) || (!on && $("#nav_" + id).css("filter").indexOf("/_images/" + id + "_grau.png") == -1)) {
			$("#nav_" + id).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/_images/" + id + "_grau.png', sizingMethod='crop')");
		} else {
			$("#nav_" + id).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/_images/" + id + ".png', sizingMethod='crop')");
		}
	} else if ($("#nav_" + id).css("background-image")) {
		if ((on && on == true) || (!on && $("#nav_" + id).css("background-image").indexOf("/_images/" + id + "_grau.png") == -1)) {
			$("#nav_" + id).css("background-image","url('/_images/" + id + "_grau.png')");
		} else {
			$("#nav_" + id).css("background-image","url('/_images/" + id + ".png')");
		}
	}
}
var navi_to = null;
function naviOn(id) {
	if (navi_to != null) {
		window.clearTimeout(navi_to);
	}
	if (id && navi_hi != id) {
		toggleNavi(navi_hi,false);
		$("div[id^='navi_']").css("display","none");
		toggleNavi(id,true);
		$("#navi_" + id).show();
		navi_hi = id;
	}
}
function naviOff() {
	if(navi_act != navi_hi) {
		if (navi_to != null) {
			window.clearTimeout(navi_to);
		}
		navi_to = window.setTimeout("naviOffTimer()",500);
	}
}
function naviOffTimer() {
	navi_to = null;
	toggleNavi(navi_hi,false);
	$("div[id^='navi_']").css("display","none");
	toggleNavi(navi_act,true);
	$("#navi_" + navi_act).fadeIn();
	navi_hi = navi_act; // reset Navi_Hi to Navi_Act
}

function setNavi() {
	toggleNavi(navi_act,true);
	// ie6 hack (DirectX overlay)
	if ($.browser.msie && $.browser.version < 7) {
		$("*[id^='nav_']").click(function(){
			window.location.href = $(this).find("a:first").attr("href");
		});
	}
}

function decryptThis(s) {
	var n=0;
	var r="mailto:";
	for(var i=0;i<s.length;i++) { 
		n=s.charCodeAt(i); 
		if (n>=8364) {n = 128;}
		r += String.fromCharCode(n-(2)); 
	}
	return r;
}
function doMailto(s) {
	location.href=decryptThis(s);
}

function AjaxObject(url) {                                           // This is the object constructor
	var that=this;                                                    // A workaround for some javascript idiosyncrocies
	var updating = false;                                             // Set to true if this object is already working on a request
	this.callback = function() {}                                     // A post-processing call -- a stub you overwrite.

	this.update = function(passData, method) {                        // Initiates the server call.
		if (!method) { method = "POST"; }
		if (updating==true) { return false; }                          // Abort if we're already processing a call.
//		updating=true;                                                 // Set the updating flag.
		var AJAX = null;                                               // Initialize the AJAX variable.
		try {
			AJAX = new XMLHttpRequest();
		} catch (trymicrosoft) {
			try {
				AJAX = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (othermicrosoft) {
				try {
					AJAX = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (failed) {
					AJAX = null;
				}
			}
		}
		if (AJAX==null) {                                              // If we couldn't initialize Ajax...
			alert("Ihre Browser unterstützt kein AJAX.");               // Sorry msg.                                              
			return false                                                // Return false (WARNING - SAME AS ALREADY PROCESSING!)
		} else {
			AJAX.onreadystatechange = function() {                      // When the browser has the request info..
				if (AJAX.readyState==4 || AJAX.readyState=="complete") { //   see if the complete flag is set.
					if (AJAX.status == 200) {
						that.data = AJAX.responseText.replace(/^\s*([\S ]+)\s*$/,'$1'); //   It is, so put the new data in the object's layer
						that.responseText = AJAX.responseText;
						that.responseXML = AJAX.responseXML;
						delete AJAX;                                       //   delete the AJAX object since it's done.
						updating=false;                                    //   Set the updating flag to false so we can do a new request
						that.callback();                                   //   Call the post-processing function.
					} else {
						// AJAX response error
						alert("Fehler in AJAX Antwort.");
					}
				}                                                        // End Ajax readystate check.
			}                                                           // End create post-process fucntion block.
			var timestamp = new Date();                                 // Get a new date (this will make the url unique)
			if (method == 'POST') {
				AJAX.open(method, urlCall, true);                        // Open the url this object was set-up with.
				AJAX.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				AJAX.setRequestHeader('Content-length', passData.length);
				AJAX.send(passData);
			} else {
				var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1); // Append date to url (so the browser doesn't cache the call)
				AJAX.open(method, uri, true);                             // Open the url this object was set-up with.
				AJAX.send(null);                                          // Send the request.
			}
			return true;                                                // Everything went a-ok.
		}                                                              // End Ajax setup aok if/else block                 
	}
	
	// This area set up on constructor calls.
	var urlCall = url;                                                // Remember the url associated with this object.
}                                                                    // End AjaxObject

var fades_to	= new Array ();

function addWakoItem (bestellnr, objBtn, objDiv) {
	var a = new AjaxObject ('/warenkorb/additem_ajax.cfm');
	a.callback = addWakoItemResponse;
	a.bestellnr = bestellnr;
	a.update ('bestellnr=' + bestellnr, 'GET');
	// Div einblenden
	$("#div_titel" + bestellnr).fadeIn();
}
function addWakoItemResponse () {
	var xml = this.responseXML;
	if (xml) {
		if (getNodeValue(xml, 'result') == 'success') {
//			alert ('Es befinden sich ' + getNodeValue(xml, 'wako_items') + ' Artikel in Ihrem Warenkorb');
			$("#div_titel" + this.bestellnr).html(getNodeValue(xml, 'html'));
			var anz = getNodeValue(xml, 'wako_items');
			if (anz == 0) {
				$("#wakolink").text("Warenkorb");
			} else {
				$("#wakolink").text("Warenkorb (" + anz + ")");
			}
		} else {
			$('#div_titel' + this.bestellnr).html("<strong>Fehler:<br/></strong>" + getNodeValue(xml, 'html'));
		}
	} else {
		$('#div_titel' + this.bestellnr).text("Der Titel konnte nicht in den Warenkorb gelegt werden.");
	}
	if (fades_to[this.bestellnr]) {
		window.clearTimeout(fades_to[this.bestellnr]);
	}
	fades_to[this.bestellnr] = window.setTimeout('$(\'#div_titel' + this.bestellnr + '\').fadeOut();', 3000);
}

function addBookmark (bestellnr) {
	var a = new AjaxObject ('/merken.cfm');
	a.callback = addBookmarkResponse;
	a.bestellnr = bestellnr;
	a.update ('bestellnr=' + bestellnr, 'GET');
	// Div einblenden
	$('#div_titel' + bestellnr).text('Der Titel wird hinzugefügt...');
	$("#div_titel" + bestellnr).fadeIn();
}
function addBookmarkResponse () {
	var xml = this.responseXML;
	if (xml) {
		if (getNodeValue(xml, 'result') == 'success') {
			$("#div_titel" + this.bestellnr).html(getNodeValue(xml, 'html'));
			$("#bookmarktd_titel" + this.bestellnr).html("<div class=\"buch_merken_i\">Ist auf dem Merkzettel</div>");
			var anz = getNodeValue(xml, 'bookmarks');
			if (anz == 0) {
				$("#bookmarklink").text("Merkzettel");
			} else {
				$("#bookmarklink").text("Merkzettel (" + anz + ")");
			}
			$("#bookmark_titel" + this.bestellnr).fadeIn();
		} else {
			$("#div_titel" + this.bestellnr).html("<strong>Fehler:<br/></strong>" + getNodeValue(xml, 'html'));
		}
	} else {
		$("#div_titel" + this.bestellnr).text("Der Titel konnte nicht auf Ihre Mekrliste gesetzt werden.");
	}
	if (fades_to[this.bestellnr]) {
		window.clearTimeout(fades_to[this.bestellnr]);
	}
	fades_to[this.bestellnr] = window.setTimeout('$(\'#div_titel' + this.bestellnr + '\').fadeOut();', 3000);
}

// Für XML auslesen
function getNode (obj, tagname, index_no) {
	if (!index_no) {
		index_no = 0;
	}
	if (!obj.getElementsByTagName(tagname) || obj.getElementsByTagName(tagname).length < index_no) {
		return;
	}
	return obj.getElementsByTagName(tagname)[index_no];
}
function getNodeValue (obj, tagname, index_no) {
	var node = getNode(obj, tagname, index_no);
	if (node) {
		return node.firstChild.nodeValue;
	}
}

function windowSize(coordinate) {
	var x,y;
	if (window.innerHeight) {
		// all except Explorer
		x = window.outerWidth - 8;
		y = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		// Explorer 6 Strict Mode
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	} else if (document.body) {
		// other Explorers
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	if (coordinate == "x") return x;
		else if (coordinate == "y") return y;
}

function sidebarSize() {
	var x = windowSize("x");
	if (x < 1140) {
		$("#sidebar > A").css("fontSize","13px");
	} else if (x < 1240) {
		$("#sidebar > A").css("fontSize","18px");
	} else {
		$("#sidebar > A").css("fontSize","23px");
	}
}

$(document).ready(function(){
	externalLinks();	// set target="_blank" for external Links
	sidebarSize();	// right Side-Navigation Fontsize
	setNavi();	// Highlight Navigation Image
//	$("A").css("outline","none");	// hide Link-Outline on Clickfocus
});
$(window).resize(function(){ sidebarSize(); });
