/*
	addLoadEvent by Simon Willison
	http://simon.incutio.com/archive/2004/05/26/addLoadEvent
	** DEPRECATED **
	* Just use code inside *
*/

function addLoadEvent(func) {
	Event.observe(window, 'load', func);
}

/**
 * window.createCookie
 * Creates a cookie
 */
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*86400000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

/**
 * window.readCookie
 * Read a cookie
 */
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/**
 * window.eraseCookie
 * Erase a cookie
 */
function eraseCookie(name) {
	createCookie(name, "", -1);
}

/**
 * window.toggleArea
 * Show/hide contentToHide and hide/show calledBy
 */
function toggleArea(contentToHide, calledBy) {
	if ($(contentToHide).style.display == 'none' | $(contentToHide).style.display == '') {
		$(contentToHide).style.display = 'block';
		$(calledBy).style.display = 'none';
	} else {
		$(contentToHide).style.display = 'none';
		$(calledBy).style.display = 'inline';
	}
}

Event.observe(window, 'load', function() {
	COOKIEPROPERTIES = readCookie("youAreNumber");
	if (COOKIEPROPERTIES == null) {
		var randomSeed = Math.floor((Math.random() * 10000000000000));
		var epochDate = new Date()
		var seconds = epochDate.getTime();
		var userID = String(randomSeed) + seconds;
		createCookie("youAreNumber", userID, 365);
	}
});

/**
 * .IR (Image Replacement for .NET) is based on
 * sIFR (Scalable Inman Flash Replacement) Version 2.0b2
 * Copyright 2004 Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben
 * This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
 * The code has been modified by Milan Negovan (http://www.aspnetresources.com) to 
 * facilitate image replacement in .NET.
*/

String.prototype.normalize = function(){
	return this.replace(/\s+/gi, " ");
};

/* IE 5.0 does not support the push method, so here goes */
if(Array.prototype.push == null){
	Array.prototype.push = function(item){
		this[this.length] = item;
		return this.length;
	};
};

/*	Implement function.apply for browsers which don't support it natively
	Courtesy of Aaron Boodman - http://youngpup.net */
if (!Function.prototype.apply){
	Function.prototype.apply = function(oScope, args) {
		var sarg = [];
		var rtrn, call;

		if (!oScope) oScope = window;
		if (!args) args = [];

		for (var i = 0; i < args.length; i++) {
			sarg[i] = "args["+i+"]";
		};

		call = "oScope.__applyTemp__(" + sarg.join(",") + ");";

		oScope.__applyTemp__ = this;
		rtrn = eval(call);
		oScope.__applyTemp__ = null;
		return rtrn;
	};
};

/**
 * The following code parses CSS selectors.
 * This script however is not the right place to explain it,
 * please visit the documentation for more information.
 */
var dotIR_parseSelector = function(){
	var redotIR_parseSelector = /^([^#\.>\`]*)(#|\.|\>|\`)(.+)$/;
	function dotIR_parseSelector(sSelector, oParentNode, sMode){
		sSelector = sSelector.replace(" ", "`");
		var selector = sSelector.match(redotIR_parseSelector);
		var node, listNodes, listSubNodes, subselector;
		var listReturn = [];

		if(selector == null){ selector = [sSelector, sSelector]	};
		if(selector[1] == ""){ selector[1] = "*" };
		if(sMode == null){ sMode = "`" };

		switch(selector[2]){
			case "#":
				subselector = selector[3].match(redotIR_parseSelector);
				if(subselector == null){ subselector = [null, selector[3]] };
				node = 	$(subselector[1]);
				if(node == null || (selector[1] != "*" && node.nodeName.toLowerCase() != selector[1].toLowerCase())){
					return listReturn;
				};
				if(subselector.length == 2){
					listReturn.push(node);
					return listReturn;
				};
				return dotIR_parseSelector(subselector[3], node, "#");
			case ".":
				if(sMode == "`"){
					listNodes = getElementsByTagName(oParentNode, selector[1]);
				} else {
					listNodes = oParentNode.childNodes;
				};

				for(var i = 0; i < listNodes.length; i++){
					node = listNodes[i];
					if(node.nodeType != 1){
						continue;
					};

					subselector = selector[3].match(redotIR_parseSelector);
					if(subselector != null){
						if(node.className.match("\\b" + subselector[1] + "\\b") == null){
							continue;
						};
						listSubNodes = dotIR_parseSelector(subselector[3], node, subselector[2]);
						listReturn = listReturn.concat(listSubNodes);
					} else if(node.className.match("\\b" + selector[3] + "\\b") != null){
						listReturn.push(node);
					};
				};
				return listReturn;
			case ">":
				if(sMode == "`"){
					listNodes = getElementsByTagName(oParentNode, selector[1]);
				} else {
					listNodes = oParentNode.childNodes;
				};
				for(var i = 0; i < listNodes.length; i++){
					node = listNodes[i];
					if(node.nodeType != 1){
						continue;
					};
					if(node.nodeName.toLowerCase() != selector[1].toLowerCase()){
						continue;
					};
					listSubNodes = dotIR_parseSelector(selector[3], node, ">");
					listReturn = listReturn.concat(listSubNodes);
				};
				return listReturn;
			case "`":
				listNodes = getElementsByTagName(oParentNode, selector[1]);
				for(var i = 0; i < listNodes.length; i++){
					node = listNodes[i];
					listSubNodes = dotIR_parseSelector(selector[3], node, "`");
					listReturn = listReturn.concat(listSubNodes);
				};
				return listReturn;
			default:
				listNodes = getElementsByTagName(oParentNode, selector[0]);
				for(var i = 0; i < listNodes.length; i++){
					listReturn.push(listNodes[i]);
				};
				return listReturn;
		};
	};

	function getElementsByTagName(oParentNode, sTagName){
		/*	IE5.x does not support document.getElementsByTagName("*")
			therefore we're resorting to element.all */
		if(sTagName == "*" && oParentNode.all != null){
			return oParentNode.all;
		};
		return oParentNode.getElementsByTagName(sTagName);
	};

	return dotIR_parseSelector;
}();

/**
 * Executes an anonymous function which returns the function dotIR (defined inside the function).
 * You can replace elements using dotIR.replaceElement()
 * All other variables and methods you see are private. If you want to understand how this works you should
 * learn more about the variable-scope in JavaScript.
 */
var dotIR = function(){

	if(!document.createElement || !document.getElementById){ return function(){return false} };

	/* Opera and Mozilla require a namespace when creating elements in an XML page */
	var sNameSpaceURI = "http://www.w3.org/1999/xhtml";
	var UA = function(){ 
		var sUA = navigator.userAgent.toLowerCase();
		var oReturn =  {
			bIsKHTML: sUA.indexOf('safari') > -1 || sUA.indexOf('konqueror') > -1 || sUA.indexOf('omniweb') > -1,
			bIsOpera : sUA.indexOf('opera') > -1,
			bIsGecko : navigator.product != null && navigator.product.toLowerCase() == 'gecko',
			bIsXML : document.contentType != null && document.contentType.indexOf('xml') > -1
		};
		oReturn.bIsIE = sUA.indexOf('msie') > -1 && ! oReturn.bIsOpera && !oReturn.bIsKHTML && !oReturn.bIsGecko;
		return oReturn;
	}();

	var bIsInitialized = false;
	var stackReplaceElementArguments = [];

	function fetchContent(oNode){
		var sContent = "";
		var oSearch = oNode.firstChild;
		var oRemove, oRemovedNode, oTarget;

		while(oSearch){
			if(oSearch.nodeType == 3){
				sContent += oSearch.nodeValue;
			} else if(oSearch.nodeType == 1){
				if(oSearch.nodeName.toLowerCase() == "a"){
					if(oSearch.getAttribute("target")){
						oTarget = oSearch.getAttribute("target");
					} else {
						oTarget = "";
					};
					sContent += '<a href="' + oSearch.getAttribute("href") + '" target="' + oTarget + '">';
				} else if(oSearch.nodeName.toLowerCase() == "br"){
					sContent += "$NEWLINE$";
				}
				if(oSearch.hasChildNodes){
					sContent += fetchContent(oSearch);
				};
				if(oSearch.nodeName.toLowerCase() == "a"){
					sContent += "</a>";
				};
			};
			oRemove = oSearch;
			oSearch = oSearch.nextSibling;
			oRemovedNode = oRemove.parentNode.removeChild(oRemove);
		};
		return sContent;
	};

	function createElement(sTagName){
		if(document.createElementNS){
			return document.createElementNS(sNameSpaceURI, sTagName);
		} else {
			return document.createElement(sTagName);
		};
	};

	function forceRedraw() {
		/*	Corrects a margin-bottom sum bug in Mozilla
			In case you're wondering why I didn't use document.body,
			it's because that throws an error if used in an XML page. */
		var nodeBody = document.getElementsByTagName("body")[0];
		nodeBody.style.height = "1px";
		nodeBody.style.height = "auto";
	};

	function urlEncode(sText)
	{
		sText = sText.replace(/%\d{0}/g, '%25');
		sText = sText.replace(/\+/g, '%2B');
		sText = sText.replace(/&amp;/g, '%26');
		sText = sText.replace(/&\w{0}#{0}/g, '%26');
		sText = sText.replace(/\"/g, '%22');
		sText = sText.replace(/\#/g, '%23');
		sText = sText.replace(/\?/g, '%3F');
		sText = sText.replace(/\£/g, '%u00A3');
		sText = sText.replace(/\&bull;/g, '%u2022');
		return sText;
	}

	function replaceElement(sSelector, sForeColor, sBackgroundColor, sWidth, sAlign, sFontSize, sFont){
		if(!mayReplace()){
			return stackReplaceElementArguments.push(arguments);
		};

		var node, sText, sVars;
		var listNodes = $$(sSelector);

		if(listNodes.length == 0){ return false };

		for(var i = 0, il = listNodes.length; i < il; i++){
			node = listNodes[i];

			if(node.firstChild.tagName && node.firstChild.tagName.toLowerCase() == 'a')
      	node = node.firstChild;

			/* Prevents elements from being replaced multiple times. */
			if(node.className.match(/\bdotIR\-replaced\b/) != null){ continue; };

			var sTexts = urlEncode(fetchContent(node)).split("$NEWLINE$");
			node.className += " dotIR-replaced";

			for(var j = 0, jl = sTexts.length; j < jl; j++)
			{
				sText = sTexts[j];

				sVars = "t=" + sText;
				sVars += "&w=" + sWidth;
				sVars += "&fc=" + urlEncode (sForeColor);
				sVars += "&bc=" + urlEncode (sBackgroundColor);
				sVars += "&fs=" + sFontSize;
				sVars += "&fn=" + urlEncode (sFont);
		
				if (sAlign != null)
					sVars += "&align=" + sAlign;

				imgNode = document.createElement("img");
				imgNode.setAttribute ("src", window.location.protocol + "//www.zopa.it/dotIR/IrImageHanler.ashx?" + sVars);
				imgNode.setAttribute ("alt", sText);

				var imgHolder = node.appendChild(document.createElement('span'));
				imgHolder.appendChild(imgNode);

				/*	Workaround to force KHTML-browsers to repaint the document. 
					Additionally, IE for both Mac and PC need this.
					See: http://neo.dzygn.com/archive/2004/09/forcing-safari-to-repaint */

				if(UA.bIsKHTML){
					node.innerHTML += "";
				}
			}
		};
		forceRedraw();
	};

	function mayReplace(e){
		if(((UA.bIsXML && UA.bIsGecko || UA.bIsKHTML) && e == null && bIsInitialized == false) || document.getElementsByTagName("body").length == 0){
			return false;
		};
		return true;
	};

	function dotIR(e){
		if((!dotIR.bAutoInit && (window.event || e) != null) || !mayReplace(e)){
			return;
		};
		bIsInitialized = true;

		for(var i = 0; i < stackReplaceElementArguments.length; i++){
			replaceElement.apply(null, stackReplaceElementArguments[i]);
		};
		stackReplaceElementArguments = [];
	};

	dotIR.replaceElement = replaceElement;
	dotIR.UA = UA;
	dotIR.bAutoInit = true;

	if(window.attachEvent){
		window.attachEvent("onload", dotIR);
	} else {
		if(document.addEventListener){
			document.addEventListener("load", dotIR, false);
		};
		if(window.addEventListener){
			window.addEventListener("load", dotIR, false);
		};
	};

	return dotIR;
}();

function zopaIr(){
	if (document.location.href.indexOf("mode=CUSTOM") == -1 && document.location.href.indexOf("stage=EDIT_LENDING") == -1) {
		dotIR.replaceElement ("body.community h1.dotIR", "#c70304", "#fff", 440, "left", 36, "AgBuch.ttf");
		dotIR.replaceElement ("body.community h2.dotIR", "#c70304", "#fff", 440, "left", 20, "AgBuch.ttf");
		dotIR.replaceElement ("body.community h3.dotIR", "#b7b3a1", "#fff", 300, "left", 20, "AgBuch.ttf");
	}
};
