/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/Ajax.js */
/**
 * (C) 2006 IMIS group AG, Zurich, Switzerland.
 *
 * Java Script Logger class.
 */

/* Log level constants */
Logger.TRACE = 0;
Logger.DEBUG = 1;
Logger.INFO = 2;
Logger.WARN = 3;
Logger.ERROR = 4;
Logger.FATAL = 5;
Logger.OFF = 10;

/**
 * Static LogFactory
 */
function LogFactory()
{
	return LogFactory;
}

LogFactory.LOG_LEVEL = Logger.OFF;

LogFactory.getLog = function(_source)
{
	var log = new Logger();
	log.logSource = _source;
	log.logLevel = LogFactory.LOG_LEVEL;
	return log;
}

/**
 * Constructor
 */
function Logger()
{
	
	/* Level to log (defaults to INFO) */
	var logLevel = Logger.INFO;
	
	/* Log source name */
	var logSource = "Unknown";
	
}




/**
 * Log trace message
 */
Logger.prototype.trace = function(_msg)
{
	if(this.logLevel <= Logger.TRACE)
	{
		this.internalDoLog(Logger.TRACE, _msg);
	}
}

/**
 * Log debug message
 */
Logger.prototype.debug = function(_msg)
{
	if(this.logLevel <= Logger.DEBUG)
	{
		this.internalDoLog(Logger.DEBUG, _msg);
	}
}

/**
 * Log info message
 */
Logger.prototype.info = function(_msg)
{
	if(this.logLevel <= Logger.INFO)
	{
		this.internalDoLog(Logger.INFO, _msg);
	}
}

/**
 * Log warn message
 */
Logger.prototype.warn = function(_msg)
{
	if(this.logLevel <= Logger.WARN)
	{
		this.internalDoLog(Logger.WARN, _msg);
	}
}

/**
 * Log error message
 */
Logger.prototype.error = function(_msg)
{
	if(this.logLevel <= Logger.ERROR)
	{
		this.internalDoLog(Logger.ERROR, _msg);
	}
}

/**
 * Log fatal message
 */
Logger.prototype.fatal = function(_msg)
{
	if(this.logLevel <= Logger.FATAL)
	{
		this.internalDoLog(Logger.FATAL, _msg);
	}
}

/**
 * Internal log implementation (override this method if necessary)
 */
Logger.prototype.internalDoLog = function(_level, _msg)
{
	var message = new Date() + ":" + this.logSource + " (" + _level + "): " + _msg;
	window.status = message;
	var out = this.internalGetLogWindow();
	if(out)
	{
		out.innerHTML = out.innerHTML + "<br />" + message;
	}
}

/**
 * Internal method to create log output
 */
Logger.prototype.internalGetLogWindow = function()
{
	if(document.getElementById("Logger.output"))
	{
		return document.getElementById("Logger.output");
	}
	var logoutput = document.createElement("div");
	logoutput.setAttribute("id", "Logger.output");
	var body = document.getElementsByTagName("body")[0];
	if(body)
	{
		var firstBodyChild = body.firstChild;
		body.insertBefore(logoutput, firstBodyChild);
		logoutput.style.position = "absolute";
		logoutput.style.bottom = "5px";
		logoutput.style.height = "200px";
		logoutput.style.width = "900px";
		logoutput.style.overflow = "auto";
		logoutput.style.backgroundColor = "#ffffff";
		logoutput.style.border = "1px solid black";
		logoutput.style.fontFamily = "monospace";
		logoutput.style.fontSize = "9px";
		logoutput.style.zIndex = "500";
		return logoutput;
	}
	return null;
}



/**
 * (C) 2006 IMIS group AG, Zurich, Switzerland.
 * 
 * XMLRPCProvider class, based on code from:
 * 
 * ------------------------------------------------------ JavaScript Refactoring
 * for safer, faster, better AJAX.
 * 
 * Copyright 2005, Pavel Simakov, http://www.softwaresecretweapons.com
 * ------------------------------------------------------
 * 
 * @author tam
 */

// http method constants
XMLRPCProvider.METHOD_GET = "GET";
XMLRPCProvider.METHOD_POST = "POST";

// constructor
function XMLRPCProvider() {

	this.log = LogFactory.getLog("XMLRPCProvider");

	this.status = null;
	this.async = true;

	var method = XMLRPCProvider.METHOD_GET;
	var url = null;
	var body = null;
	var req = null;
	var inProgress = false;
	var isComplete = false;
}

// tells us whether we are busy waiting for the response to another request
XMLRPCProvider.prototype.internalIsBusy = function() {
	return this.inProgress && !this.isComplete;
}

// internal callback function for the browser; it is called when a state of a
// request object changes
XMLRPCProvider.prototype.internalRequestComplete = function() {

	var STATE_COMPLETED = 4;
	var STATUS_200 = 200;

	if (!this.internalIsBusy()) {
		this.log.error("internalRequestComplete: error - no request submitted");
	}

	this.onProgress(this.req.readyState);

	this.log
			.debug("internalRequestComplete: readyState " + this.req.readyState);

	if (this.req.readyState == STATE_COMPLETED) {
		this.status = this.req.status;
		this.inProgress = false;
		this.isComplete = true;

		this.log.debug("internalRequestComplete: status " + status);

		if (this.status == STATUS_200) {
			this.log
					.debug("internalRequestComplete: calling callback on content with length "
							+ this.req.responseText.length + " chars");
			this.log.debug("internalRequestComplete: response headers = "
					+ this.req.getAllResponseHeaders());
			this.log.debug("internalRequestComplete: xml document: "
					+ this.req.responseXML);
			if (this.onComplete) {
				this.onComplete(this.req.responseText, this.req.responseXML);
			}
			this.log.info("internalRequestComplete: complete on " + new Date());
		} else {
			this.log
					.warn("internalRequestComplete: error - bad status while fetching "
							+ this.url + " - status: " + this.status);
		}
	} else {
		// do nothing in particular
	}
}

// call this function to figure out version of this class
XMLRPCProvider.prototype.getVersion = function() {
	return "1.0.0";
}

// call this function to figure out if current browser supports XML HTTP
// Requests
XMLRPCProvider.prototype.isSupported = function() {
	var nonEI = window.XMLHttpRequest;
	var onIE = window.ActiveXObject;

	if (onIE) {
		onIE = new ActiveXObject("Microsoft.XMLHTTP") != null;
	}

	return window.XMLHttpRequest || onIE;
}

// internally called to create new instance of XMLHttpRequest
XMLRPCProvider.prototype.internalNewRequest = function() {
	var xmlhttp = false;
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  this.log.debug("Trying to use Msxml2.XMLHTTP ActiveX Object...");
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   this.log.debug("Trying to use Microsoft.XMLHTTP ActiveX Object...");
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   this.log.error("failed to create xml http request (MSIE)");
	   xmlhttp = false;
	  }
	 }
	 if(xmlhttp)
	 {
	   this.log.debug("created xml http request successfully (MSIE)");
	 }
	 this.log.debug("cache request headers set (MSIE)");
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

// call this function to find out if more calls are possible and if request has
// been completely received
XMLRPCProvider.prototype.isBusy = function() {
	return this.internalIsBusy();
}

/**
 * Submit POST request
 */
XMLRPCProvider.prototype.post = function(_url, _body) {
	this.submit(XMLRPCProvider.METHOD_POST, _url, _body);
}

/**
 * Submit GET request
 */
XMLRPCProvider.prototype.get = function(_url) {
	this.submit(XMLRPCProvider.METHOD_GET, _url, null);
}

/**
 * Submit called by post / get methods.
 * 
 * Todo: Add support for sync requests???
 */
XMLRPCProvider.prototype.submit = function(_method, _url, _body) {
	if (this.internalIsBusy()) {
		this.log.error("submit: error - busy processing another request "
				+ _url);
	}

	this.msgCount = 0;
	this.log.info("submit: started on " + new Date() + " for " + _url);

	this.method = _method;
	this.url = _url;
	this.body = _body;
	this.status = null;
	this.inProgress = true;
	this.isComplete = false;

	this.log.debug("creating new XMLHttpRequest");
	// create new request
	this.req = this.internalNewRequest();

	this.log.info("created new request: " + this.req);

	this.log.debug("using method " + this.method + " to submit request");

	this.log.debug("initiating call (set callback and open); async = "
			+ this.async);
	if (this.async) {
		var _this = this;
		this.req.onreadystatechange = function() {
			_this.internalRequestComplete();
		};
	}
	this.req.open(this.method, this.url, this.async);

	// set headers necessary for post requests
	if (this.method == XMLRPCProvider.METHOD_POST) {
		this.log.debug("setting request header: Content-type");
		this.req.setRequestHeader("Content-type",
				"application/x-www-form-urlencoded");
		this.log.debug("setting request header: Content-length");
		this.req.setRequestHeader("Content-length", this.body.length);
		// this.log.debug("setting request header: Connection");
		// this.req.setRequestHeader("Connection", "close");
		this.log.debug("request headers for POST request set");
	}

	// branch for IE/Windows ActiveX version
	/*
	 * if (window.ActiveXObject) { this.log.debug("setting request headers for
	 * Internet Explorer (disable caching)");
	 * this.req.setrequestheader("Pragma","no-cache");
	 * this.req.setrequestheader("Cache-control","no-cache"); }
	 */

	this.req.send(this.body);
	this.log.info("submit complete");

	// if not async call request must be complete here
	if (!this.async) {
		this.log.info("syncronous call complete");
		this.log.debug("response headers: " + this.req.getAllResponseHeaders());
		if (this.onComplete) {
			this.log.info("calling onComplete callback method");
			this.onComplete(this.req.responseText, this.req.responseXML);
		}
	}

}

// call this function to abort current request
XMLRPCProvider.prototype.abort = function() {
	this.log.info("abort: " + this.url);

	if (!this.internalIsBusy()) {
		this.log.error("abort: error - no request submitted");
	}

	this.onComplete = null;
	this.req.abort();
}

// call this function to find out current url
XMLRPCProvider.prototype.getUrl = function() {
	return this.url;
}

// call this function to find out HTTP status code after response completes
XMLRPCProvider.prototype.getStatus = function() {
	return this.status;
}

// user can overrise this; this function is called when ready state of request
// changes
XMLRPCProvider.prototype.onProgress = function(progressState) {

}

// user can override this; this function is called when response is received
// without errors
XMLRPCProvider.prototype.onComplete = function(responseText, responseXML) {

}

/**
 */

/**
 * Constructor
 */
function XMLRPCPost() 
{
	this.log = LogFactory.getLog("XMLRPCPost");

	this.form = null;
	this.elements = new Array();
	this.eventSourceElement = null;
	
	this.url = null;
	
	this.responseText = null;
	this.responseXML = null;
	this.xmlrpc = null;
}

/**
 * Add an element whose data should be included in post body
 */
XMLRPCPost.prototype.addElement = function(_element)
{
	this.log.debug("adding element " + _element);
	this.elements.push(_element);
}

/**
 * Submit a form; the event source element may be specified to "simulate"
 * normal form post (if specified, other form submit buttons, etc. will be
 * excluded).
 */
XMLRPCPost.prototype.submit = function(_form, _sourceElement)
{
	this.form = _form;
	this.log.debug("form is " + this.form);
	if(!this.url)
	{
		this.url = this.form.action;
		this.log.debug("using form url: " + this.url);
	}
	this.eventSourceElement = _sourceElement;
	
	var _this = this;
	
	this.xmlrpc = new XMLRPCProvider();
	//this.xmlrpc.async = false;
	this.xmlrpc.onComplete = function(_responseText, _responseXML) { _this.internalCallback(_responseText, _responseXML); };
	
	var body = this.internalCreateBody();
	this.log.debug("body to post: " + body);
	
	this.xmlrpc.post(this.url, body);
}



/**
 * Creates the http post body using all form elements, and / or additionally 
 * defined elements.
 */
XMLRPCPost.prototype.internalCreateBody = function()
{
	// create array of all elements to include
	var includeElements = new Array();
	
	// if form is present, add all form elements
	if(this.form != null)
	{
		var frmElements = this.form.elements;
		for(var i = 0; i < frmElements.length; i++)
		{
			includeElements.push(frmElements[i]);
		}
		this.log.debug("adding " + frmElements.length + " form elements to encode; now contains " + includeElements.length + " elements");
		
	}
	
	// add array of elements
	if(this.elements != null && this.elements instanceof Array && this.elements.length > 0)
	{
		this.log.debug("adding " + this.elements.length + " form elements to the array");
		includeElements = includeElements.concat(this.elements);
	}
	
	// add event source element (some form elements are not present in the
	// array of elements, e.g. image submit; thus the event source element
	// has to be added to the elements)
	if(this.eventSourceElement != null)
	{
		this.log.debug("adding event source form element to the array");
		if(this.eventSourceElement.type == 'image')
		{
			includeElements.push(this.eventSourceElement);
		}
	}
	
	// create http post body
	var body = "";
	var elemCount = includeElements.length;
	this.log.info("Number of elements: " + elemCount);
	
	for(var i = 0; i < elemCount; i++)
	{
		var curElement = includeElements[i];
		var curType = curElement.type;
		// if event source element specified all other submit buttons should 
		// be excluded
		if(curType == "button" || curType == "submit" || curType == "image"
			|| curType == "reset")
		{
			// exclude if not event source element
			if(this.eventSourceElement != null 
				&& this.eventSourceElement != curElement)
			{
				continue;
			}
		}
		var encodedElement = this.internalEncodeElement(curElement);
		if(encodedElement != "")
		{
			this.log.debug("adding encoded element to body: " + encodedElement);
			if(body != "")
			{
				body += "&";
			}
			body += encodedElement;
		}
	}
	return body;
}

/**
 * Creates an URI encoded string representation of an element.
 */
XMLRPCPost.prototype.internalEncodeElement = function(_element)
{
	// encode element name and value
	var encodedName = encodeURIComponent(_element.name);
	var encodedValue = encodeURIComponent(_element.value);
	
	// do not create part for elements without name
	if(encodedName == "")
	{
		return "";
	}
	
	// handle hidden
	if(_element.type == "hidden")
	{
		return encodedName + "=" + encodedValue;
	}
	
	// handle checkboxes
	if(_element.type == "checkbox")
	{
		if(_element.checked)
		{
			return encodedName + "=" + encodedValue;
		}
		return "";
	}
	
	// handle radio button
	if(_element.type == "radio")
	{
		if(_element.checked)
		{
			return encodedName + "=" + encodedValue;
		}
		return "";
	}
	
	// handle select boxes
	if(_element.options)
	{
		var uriPart = "";
		var optionCount = _element.options.length;
		for(var i = 0; i < optionCount; i++)
		{
			var option = _element.options[i];
			if(option.selected)
			{
				if(uriPart != "")
				{
					uriPart += "&";
				}
				uriPart += encodedName + "=" + encodeURIComponent(option.value);
			}
		}
		return uriPart;
	}

	// handle image (coordinates submitted are always 0 / 0)
	if(_element.type == "image")
	{
		var uriPart = "";
		uriPart += encodedName + ".x=0&";
		uriPart += encodedName + ".y=0&";
		uriPart += encodedName + "=" + encodedValue;
		return uriPart;
	}
	
	// handle button
	if(_element.type == "button" || _element.type == "submit")
	{
		return encodedName + "=" + encodedValue;
	}
	
	// text fields
	if(_element.type == "text" || _element.type == "textarea")
	{
		return encodedName + "=" + encodedValue;
	}
	// fallback; just return empty string
	return "";
}

/**
 *
 */
XMLRPCPost.prototype.internalCallback = function(_responseText, _responseXML)
{
	this.log.info("internalCallback: request is complete");
	this.log.debug("responseText length: " + _responseText.length);
	this.log.debug("responseXML: " + _responseXML);
	this.responseText = _responseText;
	this.responseXML = _responseXML;
	this.onComplete(_responseText, _responseXML);
}

XMLRPCPost.prototype.onComplete = function(_responseText, _responseXML)
{
}

/**
 * DOJO/Tapestry Javascript Emulation
 */

var forms; //:{}

var dojo = function()
{
}


dojo.addOnLoad = function(obj, functionName) 
{
	if(arguments.length == 1)
	{
		obj();
	}
}

dojo.require = function()
{
}

dojo.event = function()
{
}

dojo.byId = function()
{
}

dojo.event.connect = function()
{
}

var tapestry = function()
{
}


tapestry.cleanConnect = function()
{
}

tapestry.form = function()
{
}

tapestry.form.registerForm = function(id, async, json)
{
	
	if(async)
	{
		var form=document.getElementById(id);
		if(null != form)
		{
			form.onsubmit =  function() { return submitAsync(this) };
			for (var i=0; i < form.elements.length; i++) 
			{
			   var element = form.elements[i];
			   if(element.type == 'submit')
			   {
				   element.onclick =  function() { return trackClick(this) };
			   }
			}
		}
	}
}

tapestry.linkOnClick = function(href,name,json)
{
	anchor = document.getElementById(name);
	var updateParts = getQueryVariable(href,'updateParts')
	href += "&beventtarget.id="+name+"&beventname=onClick";
	anchor.href=href;
	return submitLink(anchor,updateParts,json);	
}

function trackClick(submit)
{
	window.clicked = submit;
}

function submitAsync(form)
{
	submitName = null;
	if(null != window.clicked && window.clicked != 'undefined')
	{
		submitElement = window.clicked;
		window.clicked = null;
	}
	tapestry.form.submitAsync(form.id,null,submitElement,null);
	return false;
}

tapestry.form.focusField = function(fieldId)
{	
}

tapestry.form.submitAsync = function(formName, content, submitName, validate)
{
	var form = document.getElementById(formName);
	updatepartsField = form.elements["updateParts"];
	
	var updates = null;
	if(null != updatepartsField && "undefined" != typeof(updatepartsField))
	{
		updates = updatepartsField.value;	
	}
	
	return submitForm(form, updates , submitName ,null);
}

tapestry.form.refreshAsync = function(formName, content, submitName, callbackfunction)
{
    var form = document.getElementById(formName);
	updatepartsField = form.elements["updateParts"];
	form.submitmode.value = "refresh";
	
	var updates = null;
	if(null != updatepartsField && "undefined" != typeof(updatepartsField))
	{
		updates = updatepartsField.value;	
	}
	
	return submitForm(form, updates, submitName, callbackfunction);
}



tapestry.form.submit = function(formName, submitName, parms){
    var form=document.getElementById(formName);
    
    if (!form) {
            dojo.raise("Form not found with id " + form);
            return;
    }
    if (submitName){
            form.submitname.value=submitName;
    }
    	form.submit();
        return false;

}


function getQueryVariable(url,variable) {
	  var parts = url.split("?");
	  var vars = parts[1].split("&");
	  for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == variable) {
	      return pair[1];
	    }
	  }
} 
/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/AjaxUtils.js */
/**
 * 
 * 
 * @author tam
 */

var logger = LogFactory.getLog("main");

/**
 * Submit a link asynchronously; call to submitURL with _anchor.href.
 * 
 * @param _anchor
 * @param _update
 * @param _callbackFunction
 * @return
 */
function submitLink(_anchor, _update, _callbackFunction) {
	return submitURL(_anchor.href, _update, _callbackFunction);
}

/**
 * Submit a URL asynchronously and returns false if the submission was
 * successful.
 * 
 * @param _url
 * @param _update
 * @return
 */
function submitURL(_url, _update, _callbackFunction) {
	try {
		if (!_update) {
			// just discard the output? or follow the link?
		}
		if (typeof _update == 'string') {
			_update = new Array(_update);
		}

		logger.info("URL is: " + _url);
		var xrp = new XMLRPCProvider();
		xrp.onComplete = function(_responseText, _responseXML) {
			var d;
			/*
			 * if (typeof DOMParser != "undefined") { d = ((new
			 * DOMParser).parseFromString(_responseText, "application/xml"));
			 * for(var i = 0; i < _update.length; i++) { logger.info("Replacing
			 * element: " + _update[i]); var newContent =
			 * d.getElementById(_update[i]); if(newContent == null) {
			 * logger.warn("No new content element found for id: " +
			 * _update[i]); continue; } replaceElement(newContent, _update[i]); } }
			 * else {
			 */
			var target = document.createElement("div");
			target.innerHTML = _responseText;

			for ( var i = 0; i < _update.length; i++) {
				var newContent = getHTMLById(target, _update[i]);
				if (newContent == null) {
					logger.warn("No new content element found for id: "
							+ _update[i]);
					continue;
				}
				replaceElement(newContent, _update[i]);
			}
			/* } */
			runDojoLoads(target);
			// execute the callback function
			if (_callbackFunction) {
				_callbackFunction();
			}
		}
		xrp.get(_url);
		return false;
	} catch (e) {
		// if anything goes wrong, just follow the link as usual.
		return true;
	}
}

/**
 * Submits a form asynchronously.
 * 
 * @param _form
 * @param _update
 * @param _submitElement
 * @return
 */
function submitForm(_form, _update, _submitElement, _callbackFunction) {
	try {
		
		//_form.elements["updateParts"].value=_update;
		
		if (!_update) {
			// just discard the output? or follow the link?
		}
		if (typeof _update == 'string') {
			_update = new Array(_update);
		}

		logger.info("ACTION is: " + _form.action);
		

		var xrp = new XMLRPCPost();

		xrp.onComplete = function(_responseText, _responseXML) {

			var target = document.createElement("div");
			target.innerHTML = _responseText;
			for ( var i = 0; i < _update.length; i++) {
				var newContent = getHTMLById(target, _update[i]);
				if (newContent == null) {
					logger.warn("No new content element found for id: "
							+ _update[i]);
					continue;
				}
				replaceElement(newContent, _update[i]);
			}

			runDojoLoads(target);
						 
			
			if (_callbackFunction) {

				_callbackFunction();
			}
		}
		xrp.submit(_form, _submitElement);
		return false;
	} catch (e) {
		logger.warn("Error submitting form asyn: " + e.message);
		return true;
	}
}

/**
 * run the dojo on load functions
 */
function runDojoLoads(target)
{
	var newScripts = target.getElementsByTagName("script");
	if(newScripts.length > 0)
	{
		var newDojoHtml = newScripts[newScripts.length - 1];
		// remove html comment
		newDojoScript = newDojoHtml.innerHTML;
		newDojoScript = newDojoScript.replace(/<!--(.*)/g, "$1");
		newDojoScript = newDojoScript.replace(/(.*)\/\/ -->/g, "$1");
		eval(newDojoScript);
	}
}

/**
 * Utility function to replace an element in the HTML DOM tree.
 * 
 * @param _newElement
 * @param _elementId
 * @return
 */
function replaceElement(_newElement, _elementId) {
	var curContent = document.getElementById(_elementId);
	var par = curContent.parentNode;
	if (document.importNode) {
		_newElement = document.importNode(_newElement, true);
	}
	par.replaceChild(_newElement, curContent);
}

/**
 * Utility method to "lookup"
 * 
 * @param container
 * @param id
 * @return
 */
function getHTMLById(container, id) {
	logger.info("Id: " + id + " in container: " + container.nodeName
			+ " with id = " + container.id)
	for ( var i = 0; i < container.childNodes.length; i++) {
		var child = container.childNodes[i];
		if (child.nodeType == 1) {
			if (child.id == id) {
				logger.info("Found element");
				return child;
			}
			if (child.childNodes.length > 0) {
				var innerChild = getHTMLById(child, id);
				if (innerChild != null) {
					return innerChild;
				}
			}
		}
	}
	return null;
}
/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/ContentLoader.class.js */
/**
 * Content loading support (ajax)
 *
 * @author tam
 */

// constructor
function ContentLoader(_url, _targetElementId)
{
	this.log = LogFactory.getLog("ContentLoader");
	this.url = _url;
	this.targetElementId = _targetElementId;
}

// execute load
ContentLoader.prototype.doLoad = function()
{
	this.log.debug("Executing load {url = " + this.url + "; targetElementId = " + this.targetElementId + "}");
	if(!document.getElementById(this.targetElementId))
	{
		this.log.warn("Target element {id = '" + this.targetElementId + "'} does not exist, aborting");
		return;
	}
	
	this.log.debug("Creating new XML RPC Provider...");
	var xrp = new XMLRPCProvider();

	this.log.debug("Setting up XML RPC Provider...");	
	// de-reference "this" and set callback
	var _this = this;
	xrp.onComplete = function(_responseText, _responseXML) { _this.internalUpdateContent(_responseText, _responseXML); };
	
	this.log.info("Executing call to url: " + this.url);
	// execute call
	xrp.get(this.url);
}

// callback method after content has been loaded
ContentLoader.prototype.internalUpdateContent = function(_responseText, _responseXML)
{
	this.log.debug("Response : \n" + _responseText);
	// check if response is not null
	if(_responseText == null)
	{
		this.log.warn("Received 'null' response, aborting");
		return;
	}
	
	// set response as innerHTML of target element (target element is not 
	// replaced!)
	this.log.info("Received response; length: " + _responseText.length);
	var targetElement = document.getElementById(this.targetElementId);
	// be safe
	if(!targetElement)
	{
		log.warn("Target element does not exist (anymore), aborting");
		return;
	}
	targetElement.innerHTML = _responseText;
}/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/DomUtils.js */
/**
 * DomUtils: Dom Document manipulation utility functions.
 *
 * @author tam 
 */

function DomUtils()
{}


/**
 * Returns an element by it's id or null if no such element.
 */
DomUtils.byId = function(_elementId)
{
	return document.getElementById(_elementId);
}

/**
 * Sets the element's (<code>_elementId</code>) display style attribute; 
 * for <code>_display</code> argument <code>true</code> or <code>false</code>
 * is expected. 
 */
DomUtils.setDisplay = function(_elementId, _display)
{
	var elem = DomUtils.byId(_elementId);
	if(elem)
	{
		elem.style.display = _display ? '' : 'none';
	}
}

/**
 * Sets the element's (<code>_elementId</code>) display style attribute as 
 * follows: if the element is currently not displayed (i.e. display == 'none')
 * the display style attribute is set to the value of argument 
 * <code>_displayStyle</code>; otherwise the display style is set to 'none'.
 */
DomUtils.toggleDisplay = function(_elementId, _displayStyle)
{
	var elem = DomUtils.byId(_elementId);
	if(elem)
	{
		if(elem.style.display == 'none')
		{
			elem.style.display = _displayStyle;
		}
		else
		{
			elem.style.display = 'none';
		}
	}
}

/**
 * Returns the text content of a given node.
 */
DomUtils.textContent = function(_node, _deep)
{
	var text = "";
	if(_deep && _node.textContent)
	{
		return _node.textContent;
	}
	for(var i = 0; i < _node.childNodes.length; i++)
	{
		var ccn = _node.childNodes[i];
		switch(ccn.nodeType)
		{
		case 3:
		case 4:
			text += ccn.nodeValue;
			break;
		case 5:
			text += "&"+ccn.nodeName+";";
			break;
		case 1:
			if(_deep)
			{
				text += DomUtils.textContent(ccn, _deep);
			}
			break;
		}
	}
	return text;
}


/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/Fader.class.js */
/**
 * Fader to support fade in / out effects to elements.
 *
 * @author tam
 */ 
function Fader()
{
	var element = null;
	var opacity = null;
	var numSteps = null;
	var intervalId = null;
}

Fader.prototype.fadeOutElementById = function(_elementId)
{
	var element = getElement(_elementId);
	this.fadeOut(element);
}

Fader.prototype.fadeOut = function(_element)
{
	this.element = _element;

	// start at opacity 1.0
	this.opacity = 1.0;
	this.numSteps = 10;
	// set opacity of element.
	this.element.style.opacity = "" + this.opacity;

	var _this = this;	
	
	var faderFunction = function() { _this.internalFadeOut() };

	this.intervalId = window.setInterval(faderFunction, 20);
}

Fader.prototype.fadeInElementById = function(_elementId)
{
	var element = getElement(_elementId);
	this.fadeId(element);
}


Fader.prototype.fadeIn = function(_element)
{
	this.element = _element;

	// start at opacity 0.0
	this.opacity = 0.0;
	this.numSteps = 10;
	// set opacity of element.
	this.element.style.opacity = "" + this.opacity;
	this.element.style.visibility = "visible";

	var _this = this;
	var faderFunction = function() { _this.internalFadeIn() };	

	this.intervalId = window.setInterval(faderFunction, 20);		
}
			
Fader.prototype.internalFadeOut = function()
{
	this.internalFade(-1);
}

Fader.prototype.internalFadeIn = function()
{
	this.internalFade(1);
}
	
Fader.prototype.internalFade = function(inOut)
{
	var opacityDiff = 1.0 / this.numSteps;
	this.opacity += (inOut) * opacityDiff;
	if(this.opacity <= 0)
	{
		this.opacity = null;
		this.element.style.visibility = "hidden";
		this.element.style.opacity = "" + 1.0;
		window.clearInterval(this.intervalId);
	}
	else if(this.opacity >= 1)
	{
		this.opacity = null;
		this.element.style.opacity = "" + 1.0;
		window.clearInterval(this.intervalId);
	}
	else
	{
		this.element.style.opacity = "" + this.opacity;
	}
}/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/Logger.class.js */
/**
 * (C) 2006 IMIS group AG, Zurich, Switzerland.
 *
 * Java Script Logger class.
 */

/* Log level constants */
Logger.TRACE = 0;
Logger.DEBUG = 1;
Logger.INFO = 2;
Logger.WARN = 3;
Logger.ERROR = 4;
Logger.FATAL = 5;
Logger.OFF = 10;

/**
 * Static LogFactory
 */
function LogFactory()
{
	return LogFactory;
}

LogFactory.LOG_LEVEL = Logger.OFF;

LogFactory.getLog = function(_source)
{
	var log = new Logger();
	log.logSource = _source;
	log.logLevel = LogFactory.LOG_LEVEL;
	return log;
}

/**
 * Constructor
 */
function Logger()
{
	
	/* Level to log (defaults to INFO) */
	var logLevel = Logger.INFO;
	
	/* Log source name */
	var logSource = "Unknown";
	
}




/**
 * Log trace message
 */
Logger.prototype.trace = function(_msg)
{
	if(this.logLevel <= Logger.TRACE)
	{
		this.internalDoLog(Logger.TRACE, _msg);
	}
}

/**
 * Log debug message
 */
Logger.prototype.debug = function(_msg)
{
	if(this.logLevel <= Logger.DEBUG)
	{
		this.internalDoLog(Logger.DEBUG, _msg);
	}
}

/**
 * Log info message
 */
Logger.prototype.info = function(_msg)
{
	if(this.logLevel <= Logger.INFO)
	{
		this.internalDoLog(Logger.INFO, _msg);
	}
}

/**
 * Log warn message
 */
Logger.prototype.warn = function(_msg)
{
	if(this.logLevel <= Logger.WARN)
	{
		this.internalDoLog(Logger.WARN, _msg);
	}
}

/**
 * Log error message
 */
Logger.prototype.error = function(_msg)
{
	if(this.logLevel <= Logger.ERROR)
	{
		this.internalDoLog(Logger.ERROR, _msg);
	}
}

/**
 * Log fatal message
 */
Logger.prototype.fatal = function(_msg)
{
	if(this.logLevel <= Logger.FATAL)
	{
		this.internalDoLog(Logger.FATAL, _msg);
	}
}

/**
 * Internal log implementation (override this method if necessary)
 */
Logger.prototype.internalDoLog = function(_level, _msg)
{
	var message = new Date() + ":" + this.logSource + " (" + _level + "): " + _msg;
	window.status = message;
	out = this.internalGetLogWindow();
	if(out)
	{
		out.innerHTML = out.innerHTML + "<br />" + message;
	}
}

/**
 * Internal method to create log output
 */
Logger.prototype.internalGetLogWindow = function()
{
	if(document.getElementById("Logger.output"))
	{
		return document.getElementById("Logger.output");
	}
	var logoutput = document.createElement("div");
	logoutput.setAttribute("id", "Logger.output");
	var body = document.getElementsByTagName("body")[0];
	if(body)
	{
		var firstBodyChild = body.firstChild;
		body.insertBefore(logoutput, firstBodyChild);
		logoutput.style.position = "absolute";
		logoutput.style.bottom = "5px";
		logoutput.style.height = "200px";
		logoutput.style.width = "900px";
		logoutput.style.overflow = "auto";
		logoutput.style.backgroundColor = "#ffffff";
		logoutput.style.border = "1px solid black";
		logoutput.style.fontFamily = "monospace";
		logoutput.style.fontSize = "9px";
		logoutput.style.zIndex = "500";
		return logoutput;
	}
	return null;
}
/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/opo.js */
var curH = 0;
var h = 0;
var change = 0;

var dropDiv = null;
var interval = null;

var currentSlideDrop = null;
var currentSlideDropInner = null;

function slideDrop(dropId, dropInnerId)
{
	dropDiv = document.getElementById(dropId);
	dropInnerDiv = document.getElementById(dropInnerId);
	if(dropDiv.style.visibility == "visible")
	{
		var slider = new Slider();
		slider.slideOut(dropDiv, dropInnerDiv);
		currentSlideDrop = null;
		currentSlideDropInner = null;
	}
	else
	{
		if(currentSlideDrop != null)
		{
			var slider = new Slider();
			slider.slideOut(currentSlideDrop, currentSlideDropInner);
		}
		var slider = new Slider();
		slider.slideIn(dropDiv, dropInnerDiv);
		currentSlideDrop = dropDiv;
		currentSlideDropInner = dropInnerDiv;
	}
}

function closeDrop(dropId, dropInnerId)
{
	dropDiv = document.getElementById(dropId);
	dropInnerDiv = document.getElementById(dropInnerId);
	if(dropDiv)
	{
		dropDiv.style.visibility = "hidden";
	}
}

function fadeDrop(dropId)
{
	dropDiv = document.getElementById(dropId);
	if(dropDiv.style.visibility == "visible")
	{
		var fader = new Fader();
		fader.fadeOut(dropDiv);
	}
	else
	{
		var fader = new Fader();
		fader.fadeIn(dropDiv);
	}
}


function doPopOpen()
{
	if(h >= 10)
	{
		window.clearInterval(interval);
		dropDiv.style.height = "auto";
		var height = dropDiv.clientHeight;
		
		return;
	}
	h++;
	var inc = h;
	dropDiv.style.height = curH + inc + "px";
	curH = curH + inc;
}


function showErrorFieldInfo(fieldId)
{
	if(document.getElementById(fieldId))
	{
		document.getElementById(fieldId).style.display = "block";
	}
}

function hideErrorFieldInfo(fieldId)
{
	if(document.getElementById(fieldId))
	{
		document.getElementById(fieldId).style.display = "none";
	}
}

/**
 * Opens the article price info dialog.
 *
 */
function openArticleWindow(_evt, _eventSource, _articleNum, _url)
{
	if(!document.getElementById('articleWindow'))
	{
		PopupWindow.open(_evt, 'loginWindow', _eventSource);
		return false;
	}
	
	var log = LogFactory.getLog('OPO');
	
	// set to loading
	articleDataLoading();
	
	log.info("Opening windows; event source: " + _eventSource);
	
	// move element to body, to can move the layer over the sidebar etc.
	var articlewindow = document.getElementById('articleWindow');
	articlewindow.parentNode.removeChild(articlewindow);
	document.body.appendChild(articlewindow); 
	
	// move element to body, to can move the layer over the sidebar etc.
	var consignmentWindow = document.getElementById('consignmentWindow');
	consignmentWindow.parentNode.removeChild(consignmentWindow);
	document.body.appendChild(consignmentWindow); 
	
	// move element to body, to can move the layer over the sidebar etc.
	var basketWindow = document.getElementById('basketWindow');
	basketWindow.parentNode.removeChild(basketWindow);
	document.body.appendChild(basketWindow); 
	
	PopupWindow.open(_evt, 'articleWindow', null, 185, 300);
	PopupWindow.positionRightOf('consignmentWindow', 'articleWindow');
	PopupWindow.positionRightOf('basketWindow', 'articleWindow');
	
	// new handling of ajax calls without dojo.
	log.info("Prepare request; " + _url);
	
	var url = _url;
	var callback = function() { articleLoadingComplete(); };
	var get = submitURL(url, "articleData", callback);
	
	log.info("Result of async request: " + get);
	return get;
	
	/*
	document.getElementById("salesItemNo").value = _articleNum;
	document.getElementById("salesItemQuantity").value = "";

	// connect dojo postloading to set focus on quantity input field
	dojo.event.connect("around", tapestry, "loadContent", this, "articleLoadingComplete");
	
	tapestry.form.submitAsync("salesItemForm", null, null, true);
	return false;
	*/
}

/**
 * Shows "loading indicator" / hides data container
 */
function articleDataLoading()
{
	var loading = document.getElementById("salesItemDataLoading");
	document.getElementById("articleData").innerHTML = loading.innerHTML;
	// loading.style.display = "block";
}

/**
 * Shows "loading indicator" / hides data container
 */
function conditionsDataLoading()
{
	var loading = document.getElementById("conditionsDataLoading");
	document.getElementById("conditionsData").innerHTML = loading.innerHTML;
}


// registered pos quantity field id
var positionQuantityFieldId = null;

/**
 * Open price info dialog from basket (without quotationNr)
 */
function openPositionWindow(_evt, _eventSource, _artNum, _artNumFieldId, _quantityFieldId, _top, _left)
{
	openPositionWindow(_evt, _eventSource, _artNum, null, _artNumFieldId, _quantityFieldId, _top, _left);
}

/**
 * Open price info dialog from basket (with quotationNr)
 */
function openPositionWindow(_evt, _eventSource, _artNum, _quotationNr, _artNumFieldId, _quantityFieldId, _top, _left)
{
	// set to loading
	articleDataLoading();

	// calculate top and left.
	PopupWindow.open(_evt, 'positionWindow', null, _top, _left);
	
	// set article num if provided
	if(_artNum == null)
	{
		_artNum = FormUtil.getFieldValue(_artNumFieldId);
	}
	
	var quantity = FormUtil.getFieldValue(_quantityFieldId);
	
	// store field id
	positionQuantityFieldId = _quantityFieldId;
	
	if(_quotationNr == null){
		_quotationNr = "";
	}
	
	// new handling of ajax calls without dojo.
	var url = _eventSource.href + "?number=" + _artNum + "&quantity=" + quantity + "&quotation=" + _quotationNr + "&simpleMode=true";
	var callback = function() { articleLoadingComplete(); };
	return submitURL(url, "articleData", callback);

	/*
	document.getElementById("salesItemNo").value = _artNum;
	document.getElementById("salesItemQuantity").value = quantity;
	
	
	// connect dojo postloading to set focus on quantity input field
	dojo.event.connect("around", tapestry, "loadContent", this, "articleLoadingComplete");

	tapestry.form.submitAsync("salesItemForm", null, null, true);
	return false;
	*/
}

/**
 * Open conditions info dialog from basket
 */
function openConditionsWindow(_evt, _eventSource, _top, _left)
{
	// set to loading
	conditionsDataLoading();

	PopupWindow.open(_evt, 'conditionsWindow', null, _top, _left);
	
	// new handling of ajax calls without dojo.
	var url = _eventSource.href;
	var callback = function() { conditionsLoadingComplete(); };
	return submitURL(url, "conditionsData", callback);

}

/**
 * Close the price info dialog in basket and apply quantity
 */
function applyPositionQuantity()
{
	var inputField = document.getElementById("salesItemQuantity");
	var inputValue = inputField.value;
	var posField = document.getElementById(positionQuantityFieldId);
	posField.value = inputValue;
	closePositionWindow();
}

/**
 *
 */
function closePositionWindow()
{
	//alert("closePositionWindow");
	// close window
	PopupWindow.close('positionWindow');
	// clear article data contents
	document.getElementById("articleData").innerHTML = "";
	
	// document.getElementById("salesItemNo").value = "";
	// tapestry.form.submitAsync("salesItemForm", null, null, false);
}

/**
* Close the conditions info popup
*/
function closeConditionsWindow()
{
	// close window
	PopupWindow.close('conditionsWindow');
	// clear conditions data contents
	document.getElementById("conditionsData").innerHTML = "";
}

/**
* Close the message info popup
*/
function closeMessageWindow()
{
	// close window
	PopupWindow.close('messageWindow');
	// clear message data contents
	document.getElementById("messageDataContainer").innerHTML = "";
}

/**
 * Update.
 * 
 * @return
 */
function updateArticleData(_form, _eventSource)
{
	//alert("updateArticleData");
	FormUtil.disableControls('salesItemForm');
	var callback = function() { articleLoadingComplete(); };
	return submitForm(_form, 'articleData', _eventSource, callback);
}

/**
 * Article loading complete
 */
function articleLoadingComplete()
{
	FormUtil.enableControls('salesItemForm');
	var elems = document.getElementById("salesItemForm").elements;
	if(elems["salesItemQuantity"])
	{
		elems["salesItemQuantity"].focus();
		// funny simple workaround - call select() twice; IE ignores first call
		elems["salesItemQuantity"].focus();
	}
}

/**
 * Conditions loading complete
 */
function conditionsLoadingComplete()
{
	var cond = document.getElementById("paymentCond1");
	if(cond)
	{
		//do nothing
	}
}

/**
 * Close article window
 */
function closeArticleWindow()
{
	//alert("closeArticleWindow");
	document.getElementById("articleData").innerHTML = "";
	// document.getElementById("salesItemNo").value = "";
	FormUtil.enableControls("salesItemForm");
	// tapestry.form.submitAsync("salesItemForm", null, null, false);
	PopupWindow.close('basketWindow');
	PopupWindow.close('consignmentWindow');
	PopupWindow.close('articleWindow');
}

PopupWindow.positionRightOf = function(_windowId, _refWindowId)
{
	var popup = document.getElementById(_windowId);
	var refwin = document.getElementById(_refWindowId);
	// only continue when both windows exist
	if(popup && refwin)
	{
		var cleft = refwin.offsetLeft;
		var ctop = refwin.offsetTop;
		var cwidth = refwin.clientWidth;
		popup.style.left = (cleft + cwidth + 1) + "px";
		popup.style.top = ctop + "px";
	}
}

/**
 * Handles closing of article window when "commit" is selected.
 */
function handleArticleWindowCommit()
{
	// check if can close (new consignment/no input wont validate)
	var cbConsNew = document.getElementById("checkCreateConsignment");
	if(cbConsNew.checked)
	{
		var tfConsName = document.getElementById("tfConsignmentName");
		var consName = tfConsName.value;
		if(consName && consName.length > 0)
		{
			PopupWindow.close("articleWindow");
		}
		// can't close.
	}
	else
	{
		// no new consignment; allways close
		// PopupWindow.close("articleWindow");
	}
}

function handleArticleFormCommit(_form, _submit)
{
	//alert("handleArticleFormCommit");
	
	var submitResult = submitForm(_form, 'funcbarBasketBox', _submit);
	var cbConsNew = document.getElementById("checkCreateConsignment");
 
	var consMandatory = '';
	if(null != document.getElementById("consignmentMandatory"))
	{
		var consMandatory = document.getElementById("consignmentMandatory").textContent;
		if(consMandatory == undefined)
		{
			consMandatory = document.getElementById("consignmentMandatory").innerText;
		}
	}
		
   var consignments = document.getElementById("consignmentValue");
   var consignmentName = consignments.options[consignments.options.selectedIndex].value;
    
    //alert("consMandatory " + consMandatory + " consignmentName " + consignmentName);
    if(consMandatory == "*" && ((consignmentName == null || consignmentName == '') && !cbConsNew.checked))
    {
        document.getElementById("Submit").click();
        return false;
    }

	if(cbConsNew.checked)
	{
		var tfConsName = document.getElementById("tfConsignmentName");
		var consName = tfConsName.value;
		//alert("consName=" + consName);
		if(consName.length == 0)
		{
	        document.getElementById("Submit").click();
	        return false;
		}
	}
	
	if(typeof(_serviceName) != "undefined" && _serviceName != null && _serviceName == 'leavescatalog')
	{
		//alert("_serviceName=" + _serviceName);
		closeLeafArticleWindow();
	}
	
	//alert("submitResult=",submitResult);
	if(submitResult == false)
	{
		var articleDataContent = document.getElementById('articleData');
        if (articleDataContent != null)
        {
            articleDataContent.innerHTML = "";
        }
		PopupWindow.close("articleWindow");
	}
		
	return submitResult;
	
}

var origWidth = 540;
var largeWidth = 760;
var offsetWidth = 170;

function closeLeafArticleWindow()
{
	//alert("closeLeafArticleWindow");
	document.getElementById('realCommit').click();
	window.setTimeout("self.close()", 200);
	
}

function openLeafConsignmentWindow(_evt, _eventSource)
{
	//alert("openLeafConsignmentWindow");
	if(!document.getElementById('consignmentWindow'))
	{
		return false;
	}
	
	openConsignmentWindow(_evt, _eventSource);
	
	var container = document.getElementById('layout-content');
	if(container)
	{
		container.style.width = largeWidth + "px";
	}
	
	window.resizeBy(offsetWidth, 0);

}

function closeLeafConsignmentWindow()
{
	//alert("closeLeafConsignmentWindow");
	closeConsignmentWindow();
	window.resizeBy(offsetWidth * -1, 0);
	var container = document.getElementById('layout-content');
	if(container)
	{
		container.style.width = origWidth + "px";
	}
}

function openConsignmentWindow(_evt, _eventSource)
{
	if(!document.getElementById('consignmentWindow'))
	{
		return false;
	}
	
	FormUtil.disableControls("salesItemForm");
	
	PopupWindow.positionRightOf('consignmentWindow', 'articleWindow');
	PopupWindow.open(_evt, 'consignmentWindow', null);
	PopupWindow.close('basketWindow');
	return false;
}

function closeConsignmentWindow()
{
	//alert("closeConsignmentWindow");
	PopupWindow.close('consignmentWindow');
	FormUtil.enableControls("salesItemForm");
//	tapestry.form.submitAsync("salesItemForm", null, "ConsignmentWindow", null);
	
	var property = document.getElementById("lastSelected").value;
	var consignmentElement = document.getElementById("consignmentValue");
    tapestry.form.refreshAsync("salesItemForm", null, "ConsignmentWindow", function()
    {
        setNewConsignmentValue(consignmentElement, property);
    });
    tapestry.form.submitAsync("resetConsignmentDataForm", null, null, null);
}

function setNewConsignmentValue(consignmentElement, value)
{
    if(value != null && value.length > 1)
	{
		value = value.substr(1, value.length -1);
        var consElem = document.getElementById("consignmentValue");
        consElem.value = value;
	}
}

function openLeafBasketWindow(_evt, _eventSource)
{
	if(!document.getElementById('basketWindow'))
	{
		return false;
	}

	openBasketWindow(_evt, _eventSource);
	
	var container = document.getElementById('layout-content');
	if(container)
	{
		container.style.width = largeWidth + "px";
	}

	window.resizeBy(offsetWidth, 0);
}

function closeLeafBasketWindow()
{
	//alert("closeLeafBasketWindow");
	window.resizeBy(offsetWidth * -1, 0);
	
	var container = document.getElementById('layout-content');
	if(container)
	{
		container.style.width = origWidth + "px";
	}
	
	closeBasketWindow();
}

function openBasketWindow(_evt, _eventSource)
{
	if(!document.getElementById('basketWindow'))
	{
		return false;
	}

	FormUtil.disableControls("salesItemForm");

	PopupWindow.positionRightOf('basketWindow', 'articleWindow');
	PopupWindow.open(_evt, 'basketWindow', null);
	PopupWindow.close('consignmentWindow');
	return false;
}


function closeBasketWindow()
{
	//alert("closeBasketWindow");
	PopupWindow.close('basketWindow');
	FormUtil.enableControls("salesItemForm");
	tapestry.form.submitAsync("salesItemForm", null, "BasketWindow", false);
	tapestry.form.submitAsync("resetBasketDataForm", null, "BasketWindow", false);
}


function addCatalogReference(_evt)
{
	tapestry.form.submitAsync("catalogRefForm", null, null, false);
	/* PopupWindow.open(_evt, 'messageWindow');*/
}

function toggleAddressOverride(_cb)
{
	var defAddress = document.getElementById("defaultDeliveryAddress");
	var ovrAddress = document.getElementById("overrideDeliveryAddress");
	if(_cb.checked)
	{
		defAddress.style.display = "none";
		ovrAddress.style.display = "block";
	}
	else
	{
		defAddress.style.display = "block";
		ovrAddress.style.display = "none";
		var custNrField = document.getElementById("addressId");
		custNrField.value="";
	}
}

/**
 * Toggles between selection of managed consignments and input field for new
 * consignment creation
 */
function toggleConsignmentSelect(_cb)
{
	var csSelect = document.getElementById("selectConsignment");
	var csSelectDropdown = document.getElementById("consignmentValue");
	var csCreate = document.getElementById("createConsignment");
	var csCreateTextField = document.getElementById("tfConsignmentName");
	if(_cb.checked)
	{
		csSelect.style.display = "none";
		csSelectDropdown.disabled = true;
		csCreate.style.display = "inline";
		csCreateTextField.disabled = false;
		
		csCreateTextField.focus();
	}
	else
	{
		csSelect.style.display = "inline";
		csSelectDropdown.disabled = false;
		csCreate.style.display = "none";
		csCreateTextField.disabled = true;
	}
	
	
}

/**
 * Toggles between selection of managed consignments and input field for new
 * consignment creation
 */
function toggleConsignmentSelect2(_cb)
{
	var condId = _cb.id;
	var csSelect = document.getElementById(condId.replace(/cb/, "ps"));
	var csCreate = document.getElementById(condId.replace(/cb/, "tx"));
	var csCreateTextField = document.getElementById(condId.replace(/cb/, "tf"));
	
	if(_cb.checked)
	{
		csSelect.style.display = "none";
		csSelect.disabled = true;
		csSelect.value=" ";
		csCreate.style.display = "inline";
		csCreateTextField.disabled = false;
		
		csCreateTextField.focus();
	}
	else
	{
		csSelect.style.display = "inline";
		csSelect.disabled = false;
		csCreate.style.display = "none";
		csCreateTextField.disabled = true;
	}
}

// MIC: Does'n work in leavescatalog (Blaetterkatalog)
//function close()
//{
//}

function toggleDisplay(_elementId)
{
	var element = document.getElementById(_elementId);
	if(element.style.display == "none")
	{
		element.style.display = "block";
	}
	else
	{
		element.style.display = "none";
	}
}

function labelsSelectAll(cbMark)
{
	var frmElems = cbMark.form.elements;
	var markAll = cbMark.checked;
	for(var i = 0; i < frmElems.length; i++)
	{
		var elem = frmElems[i];
		if(elem.type == 'checkbox' && elem.id.substring(0,6) == 'cbItem')
		{
			elem.checked = markAll;
		}
	}
	
}

function FormUtil()
{
}

FormUtil.enableControls = function(formId)
{
	FormUtil.toggleControls(formId, false);
}

FormUtil.disableControls = function(formId)
{
	FormUtil.toggleControls(formId, true);
}

FormUtil.toggleControls = function(formId, disable)
{
	var frm = document.getElementById(formId);
	if(frm)
	{
		for(var i = 0; i < frm.elements.length; i++)
		{
			var elem = frm.elements[i];
			elem.disabled = disable;
		}
	}
}

FormUtil.setFieldFocus = function(fieldId)
{
	var field = document.getElementById(fieldId);
	if(field)
	{
		field.focus();
	}
}

FormUtil.getFieldValue = function(fieldId)
{
	var frmElem = document.getElementById(fieldId);
	if(frmElem)
	{
		return frmElem.value;
	}
	return null;
}

/**
 * Toggle to next / previous form field in group of text input fields.
 */
FormUtil.toggleMultiline = function(ev, fieldId, nextFieldId, prevFieldId)
{
	window.status = "keypress";
	var curInput = document.getElementById(fieldId);
	
	if(!ev)
	{
		ev = window.event;
	}
	
	var val = curInput.value;
	window.status = "value: " + val + " [length=" + val.length + "]";
	
	var keyCode = (ev.charCode ? ev.charCode : ev.keyCode);
	
	window.status = "keycode: " + keyCode;

	if(val.length == curInput.getAttribute("maxLength"))
	{
		if(!keyCode || keyCode == 9)
		{
			return;
		}
		if(!nextFieldId)
		{
			return;
		}
		var nextInput = document.getElementById(nextFieldId);
		if(nextInput.value == "")
		{
			if(navigator.userAgent.toLowerCase().indexOf("gecko") > -1)
			{
				nextInput.value = String.fromCharCode(keyCode);
			}
		}
		window.status = "switch to next";
		nextInput.focus();
	}
	if(val.length == 1)
	{
		if(keyCode == 8)
		{
			if(!prevFieldId)
			{
				return;
			}
			var prevInput = document.getElementById(prevFieldId);
			prevInput.focus();
		}
	}
}

/** 
 * Zoom Image Popup open / close 
 */

function ZoomImage()
{
}

// reference to currently opened window
ZoomImage.currentWindow = null;

// open zoom image popup
ZoomImage.open = function(windowUrl, imgUrl, label, page)
{
	ZoomImage.close();
	var re = /\+/g
	imgUrl = imgUrl.replace(re,"%2B");
	label = escape(label);
	var zoomUrl = windowUrl + "?image=" + imgUrl + "&label=" + label + "&pagenr=" + page;
	var zw = window.open(zoomUrl, "zoomImage", "width=497,height=542,menubar=yes,location=yes,resizable=no,scrollbars=no,status=no");
	
	if(zw.innerHeight == 542)
	{
		// innerHeight OK, nothing to do
	} else {
		// innerHeight not OK (probably IE), resizing Window
		zw.resizeBy(0, 50);
	}
	window.onunload = function() { ZoomImage.close(); };
	ZoomImage.currentWindow = zw;
}


// close opened zoom image popup
ZoomImage.close = function()
{
	if(ZoomImage.currentWindow != null)
	{
		ZoomImage.currentWindow.close();
	}
}


/**
 * Product info tabfolders (switch tabs)
 */

function TabFolder()
{
}

TabFolder.showTab = function(tabFolderId, tabId)
{
	// hide / deactivate all
	var tabfolder = document.getElementById("tabfolder.tab:" + tabFolderId);
	var tabs = tabfolder.childNodes;
	for(var i = 0; i < tabs.length; i++)
	{
		if(tabs[i].nodeType == 1)
		{
			tabs[i].className = "";
		}
	}
	
	var tabcontent = document.getElementById("tabfolder.content:" + tabFolderId);
	var contents = tabcontent.childNodes;
	for(var i = 0; i < contents.length; i++)
	{
		if(contents[i].nodeType == 1)
		{
			contents[i].style.display = "none";
		}
	}
	
	var activeTab = document.getElementById("tabfolder.tab:" + tabFolderId + "." + tabId);
	activeTab.className = "active";
	
	var activeContent = document.getElementById("tabfolder.content:" + tabFolderId + "." + tabId);
	activeContent.style.display = "block";
	
	var container = document.getElementById('layout-content');
	container.scrollTop = container.scrollHeight;
	
}





/**
 * Document / basket functions
 */
function Basket()
{
}

// show / hide basket item reference input field
Basket.showHideItemRef = function(rowId)
{
	var row = document.getElementById(rowId);
	if(row.style.display == 'none')
	{
		row.style.display = '';
	}
	else
	{
		row.style.display = 'none';
	}
}

// avoid resubmit
formClicked = false;
function disableSubmit() {
	if (formClicked == false){
		formClicked = true;
		return true;
	} else {
		return false;
	}
} 



function setdefaultcons(selectField)
{
	alert("Don't use this function");
    var selectConsignment = document.getElementById("consignmentValue");
	selectConsignment.selectedIndex = selectField.selectedIndex;
	selectConsignment.options[selectField.selectedIndex].selected = true;
}


/* COOKIES */

var Cookies = {
	init: function () {
		var allCookies = document.cookie.split('; ');
		for (var i=0;i<allCookies.length;i++) {
			var cookiePair = allCookies[i].split('=');
			this[cookiePair[0]] = cookiePair[1];
		}
	},
	create: function (name,value) {
		var date = new Date();
   		date.setTime(date.getTime()+(360*24*60*60*1000)); // 360 days 
   		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+value+expires+"; path=/";
		this[name] = value;
	},
	erase: function (name) {
		this.create(name,'',-1);
		this[name] = undefined;
	}
};
Cookies.init();

/**
 * start of [ save login ]
 */
var logincookiename = 'pkloginc';
var logincookiepw = 'pklogipc';

function initlogin()
{
	var checkboxName = document.getElementById("checkloginname");
	var checkboxPw = document.getElementById("checkpw");
	var qlUsername = document.getElementById("qlUsername");
	var qlPassword = document.getElementById("qlPassword");
	
	if(Cookies[logincookiename] != '' && Cookies[logincookiename] != null)
	{
		checkboxName.checked = true;
		qlUsername.value = Cookies[logincookiename];
	}
	if(Cookies[logincookiepw] != '' && Cookies[logincookiepw] != null)
	{
		checkboxPw.checked = true;
		qlPassword.value = Cookies[logincookiepw];
	}
}

function saveloginname()
{
	var checkbox = document.getElementById("checkloginname");
	var qlUsername = document.getElementById("qlUsername");
	
	if(checkbox.checked == false)
	{
		Cookies.erase(logincookiename);
	}
	else if(checkbox.checked == true)
	{
		Cookies.create(logincookiename, qlUsername.value);
	}
}
/**
 * end of [ save login ]
 */

function saveloginpw()
{
	var checkbox = document.getElementById("checkpw");
	var qlPassword = document.getElementById("qlPassword");
	
	if(checkbox.checked == false)
	{
		Cookies.erase(logincookiepw);
	}
	else if(checkbox.checked == true)
	{
		Cookies.create(logincookiepw, qlPassword.value);
	}
}

function adjustscrollbar()
{
	var scrollDiv = document.getElementById("layout-content-document-items");
	// Doesn't work properly: scrollDiv.scrollTop = 999999;
	scrollDiv.scrollTop = scrollDiv.scrollHeight + 500;
	
}
 
function showStackTrace()
{
	var stb = document.getElementById("stackTraceBox");
	if ( stb.style.visibility == 'hidden' ) stb.style.visibility = 'visible';
	else stb.style.visibility = 'hidden';
}

/**
 * Minimize a consignment in the basket
 */
function minimizeConsignment(tableId)
{
	/*var docItemtable = document.getElementById(tableId);
	docItemtable.style.display = "none";*/
}

function catchEnter(e)
{
	// Catch IE’s window.event if the 'e' variable is null.
    // FireFox and others populate the e variable automagically.

	if (!e) e = window.event; 
       

	// Catch the keyCode into a variable. 
    // IE = keyCode, DOM = which.

	var code = (e.keyCode) ? e.keyCode : e.which;

    // If code = 13 (enter) or 3 (return), cancel it out; else keep going and process the key.

    if (code == 13 || code == 3) return false;
    else return true;
}


function warnChangeOffer(offerNumber, newquantity, oldquantity){
	
	// if new quantity is bigger -> return (no action)
	if((parseInt(newquantity)) >= (parseInt(oldquantity))){
		return true;
	}
	// if new quantity is smaller -> delete offernr from basket
	document.getElementById("changeOfferHidden").value=offerNumber;
	document.getElementById("changeOffer").click();
	
}

function warnDeleteOffer(offerNumber){
		document.getElementById("changeOfferHidden").value=offerNumber;
		return true;
}

function blockDropDown(dropDown)
{
    dropDown.blur();
}
/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/PopupWindow.class.js */
/**
 * Popup Window support.
 *
 * @author tam
 */ 

function PopupWindow()
{
}

// vars for moving of windows
PopupWindow.lastEventX = 0;
PopupWindow.lastEventY = 0;
PopupWindow.currentMovingWindow = null;

PopupWindow.log = LogFactory.getLog("Popup");

/**
 * Open a popup window (positioned next to the element which fired the command).
 */
PopupWindow.open = function(_evt, _windowId, _refElement, _top, _left)
{
	var e = _evt;
	if(window.event)
	{
		e = event;
	}
	var popup = document.getElementById(_windowId);
	
	if(!popup)
	{
		return false;
	}
	
	// only calculate position if _refElement and e is provided
	if(_refElement && e != null)
	{
		PopupWindow.log.info("refElement: offsetLeft = " + _refElement.offsetLeft + "; offsetTop = " + _refElement.offsetTop);
		PopupWindow.log.info("event: layerX = " + e.layerX + "; layerY = " + e.layerY);
		//_refElement.parentNode.appendChild(popup);
		if(e.layerY)
		{
			popup.style.top = (e.layerY + 10) + "px";
		}
		else if(e.clientY)
		{
			popup.style.top = (e.clientY - 100 + 10) + "px";
		}
	}
	else if(_top && _left)
	{
		popup.style.left = _left + "px";
		popup.style.top = _top + "px";
	}
	popup.style.display = "";
	return false;
}

/**
 * Close a popup window.
 */
PopupWindow.close = function(_windowId)
{
	var popup = document.getElementById(_windowId);
	if(popup)
	{
		popup.style.display = "none";
	}
}

PopupWindow.positionRightOf = function(_windowId, _refWindowId)
{
	var popup = document.getElementById(_windowId);
	var refwin = document.getElementById(_refWindowId);
	// only continue when both windows exist
	if(popup && refwin)
	{
		var cleft = refwin.offsetLeft;
		var ctop = refwin.offsetTop;
		var cwidth = refwin.clientWidth;
		popup.style.left = (cleft + cwidth + 1) + "px";
		popup.style.top = ctop + "px";
	}
}

/**
 * Event handler: Start moving the window
 */
PopupWindow.startMove = function(evt, _windowId)
{
	PopupWindow.currentMovingWindow = document.getElementById(_windowId);
	if(navigator.userAgent.indexOf("Gecko") > -1)
	{
		window.captureEvents(Event.MOUSEMOVE);
		window.captureEvents(Event.MOUSEUP);
		window.onmousemove = PopupWindow.doMove;
		window.onmouseup = PopupWindow.stopMove;
		PopupWindow.lastEventX = evt.layerX;
		PopupWindow.lastEventY = evt.layerY;
		//evt.stopPropagation();
	}
	else if(navigator.userAgent.indexOf("MSIE") > -1)
	{
		document.onmousemove = PopupWindow.doMove;
		document.onmouseup = PopupWindow.stopMove;
		//window.attachEvent("onmousemove", moveControl);
		//window.attachEvent("onmouseup", stopMoveControl);
		PopupWindow.lastEventX = window.event.offsetX;
		PopupWindow.lastEventY = window.event.offsetY;
	}
	// silently ignore unsupported browsers.
	// alert("Moving is not supported for UserAgent: " + navigator.userAgent);
	return false; // prevent event bubbling (i.e. text selection)
}

/**
 * Event handler: Stop moving the window
 */
PopupWindow.stopMove = function(evt)
{
	PopupWindow.currentMovingWindow = null;
	if(navigator.userAgent.indexOf("Gecko") > -1)
	{
		window.onmousemove = null;
		window.onmouseup = null;
		window.releaseEvents(Event.MOUSEMOVE);
		window.releaseEvents(Event.MOUSEUP);
	}
	else if(navigator.userAgent.indexOf("MSIE") > -1)
	{
		document.onmousemove = null;
		document.onmouseup = null;
		/*
		window.detachEvent("onmousemove");
		window.detachEvent("onmouseup");*/
	}
	return false;
}

PopupWindow.doMove = function(evt)
{
	if(navigator.userAgent.indexOf("MSIE") > -1)
	{
		evt = window.event;
	}
	/*
	var diffX = evt.clientX - PopupWindow.lastEventX;
	var dixxY = evt.clientY - PopupWindow.lastEventY;
	PopupWindow.lastEventX = evt.clientX;
	PopupWindow.lastEventY = evt.clientY;
	*/
	
	var elem = PopupWindow.currentMovingWindow;
	
	var elemLeft = evt.clientX + elem.offsetLeft - PopupWindow.lastEventX;
	var elemTop = evt.clientY + elem.offsetTop - PopupWindow.lastEventY;
	elem.style.left = elemLeft + "px";
	elem.style.top = elemTop + "px";
	window.status = ""
	return false;
}/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/Scw.js */
// *****************************************************************************
//      Simple Calendar Widget - Cross-Browser Javascript pop-up calendar.
//
//   Copyright (C) 2005-2006  Anthony Garrett
//
//   This library is free software; you can redistribute it and/or
//   modify it under the terms of the GNU Lesser General Public
//   License as published by the Free Software Foundation; either
//   version 2.1 of the License, or (at your option) any later version.
//
//   This library is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//   Lesser General Public License for more details.
//
//   You should have received a copy of the GNU Lesser General Public
//   License along with this library; if not, it is available at
//   the GNU web site (http://www.gnu.org/) or by writing to the
//   Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
//   Boston, MA  02110-1301  USA
//
// *****************************************************************************
//
// Contact:   Sorry, I can't offer support for this but if you find a problem
//            (or just want to tell me how useful you find it), please send
//            me an email at scwfeedback@tarrget.info (Note the two Rs in
//            tarrget).  I will try to fix problems quickly but this is a
//            spare time thing for me.
//
// Credits:   I wrote this from scratch myself but I couldn't have done it
//            without the superb "JavaScript The Definitive Guide" by David
//            Flanagan (Pub. O'Reilly ISBN 0-596-00048-0).  I also recognise
//            a contribution from my experience with PopCalendar 4.1 by
//            Liming(Victor) Weng.
//
// Link back: Please give me credit and link back to my page.  To ensure that
//            search engines give my page a higher ranking you can add the
//            following HTML to any indexed page on your web site:
//
//            <A HREF="http://www.tarrget.info/calendar/scw.htm">
//              Simple Calendar Widget by Anthony Garrett
//            </A>
//
// Features:  Easily customised
//                  (output date format, colours, language, year range and
//                   week start day)
//            Accepts a date as input
//                  (see comments below for formats).
//            Cross-browser code tested against;
//                  Internet Explorer 6.0.28     Mozilla  1.7.1
//                  Opera             7.52+      Firefox  0.9.1+
//                  Konqueror         3.4.0      Flock    0.4.9
//
// How to add the Calendar to your page:
//            This script needs to be defined for your page so, immediately
//            after the BODY tag add the following line;
//
//                  <script type='Text/JavaScript' src='scw.js'></script>
//
//            Your root directory of the web site should also contain an empty
//            file called "scwblank.html". See
//                  http://www.tarrget.info/calendar/IEnightmare.html
//            for a full explanation.
//
// How to use the Calendar once it is defined for your page:
//
//            Simply choose an event to trigger the calendar (like an onClick
//            or an onMouseOver) and an element to work on (for the calendar
//            to take its initial date from and write its output date to) then
//            write it like this;
//
//                  <<event>>="scwShow(<<element>>,this);"
//
//            e.g. onClick="scwShow(scwID('myElement'),this);"
//            or   onMouseOver="scwShow(this,this);"
//
//            NOTE: The "this" keyword causes the script to fail when the
//                  triggered calendar is using an anchor tag. The following
//                  syntax works;
//
//                  <a id="<<ID>>"
//                     href="javascript:
//                              scwShow(<<element>>,scwID('<<ID>>'));">
//                      <<your text>>
//                  </a>
//
//            If you are using a text node then specify the text's parent node
//            in the function call. The date should be the only text under that
//            node;
//
//            e.g.  <p onclick="scwShow(this,this);"><<date>></p>
//
//            You can also disable days of the week by adding arguments to the
//            call to scwShow.  The values should be Sunday = 0 through to
//            Saturday = 6.  A call to scwShow with Friday and Monday disabled
//            would look something like this;
//
//                  scwShow(<<element>>,this,5,1);
//
//            Finally you can use the following technique to run a function
//            when the calendar closes:
//
//                  scwNextAction=<<function>>.runsAfterSCW(this,<<arguments>>);
//                  scwShow(<<element>>,this <<,optional arguments above>>);
//
//            Where <<function>> is a function defined on the calling page
//            and <<arguments>> is the list of arguments being passed to that
//            function.
//
//            ------------------------------------------------------------------
//            Here's an extremely trivial but fully functioning example page
//            showing two of the ways to trigger the calendar;
//
//            <html>
//                <head><title>Basic Example</title></head>
//                <body>
//                    <script type='text/JavaScript' src='scw.js'></script>
//                    <p onclick='scwShow(this,this);'>06-Dec-2006</p>
//                    <input onclick='scwShow(this,this);' value='07-Dec-2006' />
//                    <br/><br/>
//                    <a id='aTest'
//                       href='javascript:scwShow(scwID("aTest"),this);'>
//                        08-Dec-2006
//                    </a>
//                </body>
//            </html>
//
// *****************************************************************************
//
// See http://www.tarrget.info/calendar/scw.htm for a complete version history
//
// Version   Date        By               Description
// =======   ====        ===============  ===========
//   3.56    2006-12-13  Anthony Garrett  Fixed accidental disabling of the last
//                                         day of the last month in the calendar.
//                                        Added options to disable and hide days
//                                         that are out of the currently displayed
//                                         month. Thanks to Ruslan Androsyuk for
//                                         this feature request.
//                                        Applied the IFRAME backing to IE 7
//                                         in order to improve rendering when
//                                         the calendar overlays graphically
//                                         dynamic objects.  Thanks to Shaun
//                                         Plumb for reporting this issue.
//                                        Allowed date input/output to be a
//                                         text node.  Thanks to John Navratil
//                                         for this suggestion (and others).
//                                        Applied a work-around for Opera's
//                                         buggy selectIndex setting.
// *****************************************************************************

// ************************************
// Start of Simple Calendar Widget Code
// ************************************

// This date is used throughout to determine today's date.

    var scwDateNow = new Date(Date.parse(new Date().toDateString()));

//******************************************************************************
//------------------------------------------------------------------------------
// Customisation section
//------------------------------------------------------------------------------
//******************************************************************************

    // Set the bounds for the calendar here...
    // If you want the year to roll forward you can use something like this...
    //      var scwBaseYear = scwDateNow.getFullYear()-5;
    // alternatively, hard code a date like this...
    //      var scwBaseYear = 1990;

    var scwBaseYear        = scwDateNow.getFullYear() - 2;

    // How many years do want to be valid and to show in the drop-down list?

    var scwDropDownYears   = 4;

    // All language-dependent changes can be made here...

    // If you wish to work in a single language (other than English) then
    // just replace the English (in the function scwSetLanguage below) with
    // your own text.

    // Using multiple languages:
    // In order to keep this script to a resonable size I have not included
    // languages here.  You can set language fields in a function that you
    // should call  scwSetLanguage  the script will use your languages.
    // I have included all the translations that have been sent to me in
    // such a function on the demonstration page.

    var scwLanguage;

    function scwSetDefaultLanguage()
        {try
            {scwSetLanguage();}
         catch (exception)
            {// English
             scwToday               = 'Heute:';
             scwDrag                = 'click here to drag';
             scwArrMonthNames       = ['Jan','Feb','Mar','Apr','Mai','Jun',
                                       'Jul','Aug','Sep','Okt','Nov','Dez'];
             scwArrWeekInits        = ['So','Mo','Di','Mi','Do','Fr','Sa'];
             scwInvalidDateMsg      = 'The entered date is invalid.\n';
             scwOutOfRangeMsg       = 'The entered date is out of range.';
             scwDoesNotExistMsg     = 'The entered date does not exist.';
             scwInvalidAlert        = ['Invalid date (',') ignored.'];
             scwDateDisablingError  = ['Error ',' is not a Date object.'];
             scwRangeDisablingError = ['Error ',
                                       ' should consist of two elements.'];
            }
        }

    // Note:  Always start the scwArrWeekInits array with your string for
    //        Sunday whatever scwWeekStart (below) is set to.

    // scwWeekStart determines the start of the week in the display
    // Set it to: 0 (Zero) for Sunday, 1 (One) for Monday etc..

    var scwWeekStart       =    1;

    // The week start day for the display is taken as the week start
    // for week numbering.  This ensures that only one week number
    // applies to one line of the calendar table.
    // [ISO 8601 begins the week with Day 1 = Monday.]

    // If you want to see week numbering on the calendar, set
    // this to true.  If not, false.

    var scwWeekNumberDisplay    = false;

    // Week numbering rules are generally based on a day in the week
    // that determines the first week of the year.  ISO 8601 uses
    // Thursday (day four when Sunday is day zero).  You can alter
    // the base day here.

    // See http://www.cl.cam.ac.uk/~mgk25/iso-time.html for more information

    var scwWeekNumberBaseDay    = 4;

    // Each of the calendar's alert message types can be disabled
    // independently here.

    var scwShowInvalidDateMsg       = true,
        scwShowOutOfRangeMsg        = true,
        scwShowDoesNotExistMsg      = true,
        scwShowInvalidAlert         = true,
        scwShowDateDisablingError   = true,
        scwShowRangeDisablingError  = true;

    // Set the allowed input date delimiters here...
    // E.g. To set the rising slash, hyphen, full-stop (aka stop or point),
    //      comma and space as delimiters use
    //              var scwArrDelimiters   = ['/','-','.',',',' '];

    var scwArrDelimiters   = ['/','-','.',',',' '];

    // Set the format for the displayed 'Today' date and for the output
    // date here.
    //
    // The format is described using delimiters of your choice (as set
    // in scwArrDelimiters above) and case insensitive letters D, M and Y.
    //
    // Definition               Returns
    // ----------               -------
    // D            date in the month without zero filling
    // DD           date in the month left zero filled
    // M            month number without zero filling
    // MM           month number left zero filled
    // MMM          month string from scwArrMonthNames
    // YY           year number in two digits
    // YYYY         year number in four digits

    // Displayed "Today" date format

    var scwDateDisplayFormat = 'dd.mm.yy';     // e.g. 'MMM-DD-YYYY' for the US

    // Output date format

    var scwDateOutputFormat  = 'dd.MM.YYYY'; // e.g. 'MMM-DD-YYYY' for the US

    // The input date is fully parsed so a format is not required,
    // but there is no way to differentiate the sequence reliably.
    //
    // e.g. Is 05/08/03     5th August 2003,
    //                      8th May    2003 or even
    //                      3rd August 2005?
    //
    // So, you have to state how the code should interpret input dates.
    //
    // The sequence should always contain one D, one M and one Y only,
    // in any order.

    var scwDateInputSequence = 'DMY';           // e.g. 'MDY' for the US

    // Note: Because the user may select a date then trigger the
    //       calendar again to select another, it is necessary to
    //       have the input date sequence in the same order as the
    //       output display format.  To allow the flexibility of having
    //       a full input date and a partial (e.g. only Month and Year)
    //       output, the input sequence is set separately.
    //
    //       The same reason determines that the delimiters used should
    //       be in scwArrDelimiters.

    // scwZindex controls how the pop-up calendar interacts with the rest
    // of the page.  It is usually adequate to leave it as 1 (One) but I
    // have made it available here to help anyone who needs to alter the
    // level in order to ensure that the calendar displays correctly in
    // relation to all other elements on the page.

    var scwZindex          = 1;

    // Personally I like the fact that entering 31-Sep-2005 displays
    // 1-Oct-2005, however you may want that to be an error.  If so,
    // set scwBlnStrict = true.  That will cause an error message to
    // display and the selected month is displayed without a selected
    // day. Thanks to Brad Allan for his feedback prompting this feature.

    var scwBlnStrict       = false;

    // If you wish to disable any displayed day, e.g. Every Monday,
    // you can do it by setting the following array.  The array elements
    // match the displayed cells.
    //
    // You could put something like the following in your calling page
    // to disable all weekend days;
    //
    //  for (var i=0;i<scwEnabledDay.length;i++)
    //      {if (i%7%6==0) scwEnabledDay[i] = false;}
    //
    // The above approach will allow you to disable days of the week
    // for the whole of your page easily.  If you need to set different
    // disabled days for a number of date input fields on your page
    // there is an easier way: You can pass additional arguments to
    // scwShow. The syntax is described at the top of this script in
    // the section:
    //    "How to use the Calendar once it is defined for your page:"
    //
    // It is possible to use these two approaches in combination.

    var scwEnabledDay      = [true, true, true, true, true, true, true,
                              true, true, true, true, true, true, true,
                              true, true, true, true, true, true, true,
                              true, true, true, true, true, true, true,
                              true, true, true, true, true, true, true,
                              true, true, true, true, true, true, true];

    // You can disable any specific date (e.g. 24-Jan-2006 or Today) by
    // creating an element of the array scwDisabledDates as a date object
    // with the value you want to disable.  Date ranges can be disabled
    // by placing an array of two values (Start and End) into an element
    // of this array.

    var scwDisabledDates   = new Array();

    // e.g. To disable 10-Dec-2005:
    //          scwDisabledDates[0] = new Date(2005,11,10);
    //
    //      or a range from 2004-Dec-25 to 2005-Jan-01:
    //          scwDisabledDates[1] = [new Date(2004,11,25),new Date(2005,0,1)];
    //
    // Remember that Javascript months are Zero-based.

    // The disabling by date and date range does prevent the current day
    // from being selected.  Disabling days of the week does not so you can set
    // the scwActiveToday value to false to prevent selection.

    var scwActiveToday = true;

    // Dates that are out of the displayed month are shown at the start
    // (unless the month starts on the first day of the week) and end of each
    // month.
    //
    // Set scwOutOfMonthDisable to  true  to disable these dates (or  false  
    // to allow their selection).
    //
    // Set scwOutOfMonthHide    to  true  to hide    these dates (or  false  
    // to make them visible).

    var scwOutOfMonthDisable = false;
    var scwOutOfMonthHide    = false;

    // Dates that are out of the specified range can be displayed at the start
    // of the very first month and end of the very last.  Set
    // scwOutOfRangeDisable to  true  to disable these dates (or  false  to
    // allow their selection).

    var scwOutOfRangeDisable = true;

    // You can allow the calendar to be dragged around the screen by
    // using the setting scwAllowDrag to true.
    // I can't say I recommend it because of the danger of the user
    // forgetting which date field the calendar will update when there
    // are multiple date fields on a page.

    var scwAllowDrag = false;

    // Closing the calendar by clicking on it (rather than elsewhere on the
    // main page) can be inconvenient.  The scwClickToHide boolean value
    // controls this feature.

    var scwClickToHide = false;

    // I have made every effort to isolate the pop-up script from any
    // CSS defined on the main page but if you have anything set that
    // affects the pop-up (or you may want to change the way it looks)
    // then you can address it in the following style sheets.

    document.writeln(
        '<style type="text/css">'                                       +
            '.scw           {padding:1px;vertical-align:middle;}'       +
            'iframe.scw     {position:absolute;z-index:' + scwZindex    +
                            ';top:0px;left:0px;visibility:hidden;'      +
                            'width:1px;height:1px;}'                    +
            'table.scw      {padding:0px;visibility:hidden;'            +
                            'position:absolute;cursor:default;'         +
                            'width:200px;top:0px;left:0px;'             +
                            'z-index:' + (scwZindex+1)                  +
                            ';text-align:center;}'                      +
        '</style>'  );

    // This style sheet can be extracted from the script and edited into regular
    // CSS (by removing all occurrences of + and '). That can be used as the
    // basis for themes. Classes are described in comments within the style
    // sheet.

//******************************************************************************
//------------------------------------------------------------------------------
// End of customisation section
//------------------------------------------------------------------------------
//******************************************************************************

//  Variables required by both scwShow and scwShowMonth

    var scwTargetEle,
        scwTriggerEle,
        scwMonthSum            = 0,
        scwBlnFullInputDate    = false,
        scwPassEnabledDay      = new Array(),
        scwSeedDate            = new Date(),
        scwParmActiveToday     = true,
        scwWeekStart           = scwWeekStart%7,
        scwToday,
        scwDrag,
        scwArrMonthNames,
        scwArrWeekInits,
        scwInvalidDateMsg,
        scwOutOfRangeMsg,
        scwDoesNotExistMsg,
        scwInvalidAlert,
        scwDateDisablingError,
        scwRangeDisablingError;

    // Add a method to format a date into the required pattern

    Date.prototype.scwFormat =
        function(scwFormat)
            {var charCount = 0,
                 codeChar  = '',
                 result    = '';

             for (var i=0;i<=scwFormat.length;i++)
                {if (i<scwFormat.length && scwFormat.charAt(i)==codeChar)
                        {// If we haven't hit the end of the string and
                         // the format string character is the same as
                         // the previous one, just clock up one to the
                         // length of the current element definition
                         charCount++;
                        }
                 else   {switch (codeChar)
                            {case 'y': case 'Y':
                                result += (this.getFullYear()%Math.
                                            pow(10,charCount)).toString().
                                            scwPadLeft(charCount);
                                break;
                             case 'm': case 'M':
                                // If we find an M, check the number of them to
                                // determine whether to get the month number or
                                // the month name.
                                result += (charCount<3)
                                            ?(this.getMonth()+1).
                                                toString().scwPadLeft(charCount)
                                            :scwArrMonthNames[this.getMonth()];
                                break;
                             case 'd': case 'D':
                                // If we find a D, get the date and format it
                                result += this.getDate().toString().
                                            scwPadLeft(charCount);
                                break;
                             default:
                                // Copy any unrecognised characters across
                                while (charCount-- > 0) {result += codeChar;}
                            }

                         if (i<scwFormat.length)
                            {// Store the character we have just worked on
                             codeChar  = scwFormat.charAt(i);
                             charCount = 1;
                            }
                        }
                }
             return result;
            }

    // Add a method to left pad zeroes

    String.prototype.scwPadLeft =
        function(padToLength)
            {var result = '';
             for (var i=0;i<(padToLength - this.length);i++) {result += '0';}
             return (result + this);
            }

    // Set up a closure so that any next function can be triggered
    // after the calendar has been closed AND that function can take
    // arguments.

    Function.prototype.runsAfterSCW =
        function()  {var func = this,
                         args = new Array(arguments.length);

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

                     return function()
                        {// concat/join the two argument arrays
                         for (var i=0;i<arguments.length;++i)
                            {args[args.length] = arguments[i];}

                         return (args.shift()==scwTriggerEle)
                                    ?func.apply(this, args):null;
                        }
                    };

    // Set up some shortcuts

    function scwID(id)  {return document.getElementById(id);}

    // Use a global variable for the return value from the next action
    // IE fails to pass the function through if the target element is in
    // a form and scwNextAction is not defined.

    var scwNextActionReturn, scwNextAction;

// ****************************************************************************
// Start of Function Library
//
//  Exposed functions:
//
//      scwShow             Entry point for display of calendar,
//                              called in main page.
//      showCal             Legacy name of scwShow:
//                              Passes only legacy arguments,
//                              not the optional day disabling arguments.
//
//      scwShowMonth        Displays a month on the calendar,
//                              Called when a month is set or changed.
//
//      scwBeginDrag        Controls calendar dragging.
//
//      scwCancel           Called when the calendar background is clicked:
//                              Calls scwStopPropagation and may call scwHide.
//      scwHide             Hides the calendar, called on various events.
//      scwStopPropagation  Stops the propagation of an event.
//
// ****************************************************************************

    function showCal(scwEle,scwSourceEle)    {scwShow(scwEle,scwSourceEle);}
    function scwShow(scwEle,scwSourceEle)
        {scwTriggerEle = scwSourceEle;

         // Take any parameters that there might be from the third onwards as
         // day numbers to be disabled 0 = Sunday through to 6 = Saturday.

         scwParmActiveToday = true;

         for (var i=0;i<7;i++)
            {scwPassEnabledDay[(i+7-scwWeekStart)%7] = true;
             for (var j=2;j<arguments.length;j++)
                {if (arguments[j]==i)
                    {scwPassEnabledDay[(i+7-scwWeekStart)%7] = false;
                     if (scwDateNow.getDay()==i) scwParmActiveToday = false;
                    }
                }
            }

         //   If no value is preset then the seed date is
         //      Today (when today is in range) OR
         //      The middle of the date range.

         scwSeedDate = scwDateNow;

         // Find the date and Strip space characters from start and
         // end of date input.

         if (typeof scwEle.value == 'undefined')
            {var scwChildNodes = scwEle.childNodes;
             for (var i=0;i<scwChildNodes.length;i++)
                if (scwChildNodes[i].nodeType == 3)
                    {var scwDateValue = scwChildNodes[i].nodeValue.replace(/^\s+/,'').replace(/\s+$/,'');
                     if (scwDateValue.length > 0)
                        {scwTriggerEle.scwTextNode = scwChildNodes[i];
                         scwTriggerEle.scwLength   = scwChildNodes[i].nodeValue.length;
                         break;
                        }
                    }
            }
         else
            {var scwDateValue = scwEle.value.replace(/^\s+/,'').replace(/\s+$/,'');}

         // Set the language-dependent elements

         scwSetDefaultLanguage();

         scwID('scwDragText').innerHTML = scwDrag;

         scwID('scwMonths').options.length = 0;
         for (var i=0;i<scwArrMonthNames.length;i++)
            scwID('scwMonths').options[i] =
                 new Option(scwArrMonthNames[i],scwArrMonthNames[i]);

         scwID('scwYears').options.length = 0;
         for (var i=0;i<scwDropDownYears;i++)
            scwID('scwYears').options[i] =
                 new Option((scwBaseYear+i),(scwBaseYear+i));

         for (var i=0;i<scwArrWeekInits.length;i++)
            scwID('scwWeekInit' + i).innerHTML =
                          scwArrWeekInits[(i+scwWeekStart)%
                                            scwArrWeekInits.length];

         if (scwID('scwFoot'))
            scwID('scwFoot').innerHTML =
                    scwToday + ' ' +
                    scwDateNow.scwFormat(scwDateDisplayFormat);

         if (scwDateValue.length==0)
            {// If no value is entered and today is within the range,
             // use today's date, otherwise use the middle of the valid range.

             scwBlnFullInputDate=false;

             if ((new Date(scwBaseYear+scwDropDownYears,0,0))<scwSeedDate ||
                 (new Date(scwBaseYear,0,1))                 >scwSeedDate
                )
                {scwSeedDate = new Date(scwBaseYear +
                                        Math.floor(scwDropDownYears / 2), 5, 1);
                }
            }
         else
            {function scwInputFormat()
                {var scwArrSeed = new Array(),
                     scwArrInput = scwDateValue.
                                    split(new RegExp('[\\'+scwArrDelimiters.
                                                        join('\\')+']+','g'));

                 // "Escape" all the user defined date delimiters above -
                 // several delimiters will need it and it does no harm for
                 // the others.

                 // Strip any empty array elements (caused by delimiters)
                 // from the beginning or end of the array. They will
                 // still appear in the output string if in the output
                 // format.

                 if (scwArrInput[0]!=null)
                    {if (scwArrInput[0].length==0) scwArrInput.splice(0,1);

                     if (scwArrInput[scwArrInput.length-1].length==0)
                        scwArrInput.splice(scwArrInput.length-1,1);
                    }

                 scwBlnFullInputDate = false;

                 switch (scwArrInput.length)
                    {case 1:
                        {// Year only entry
                         scwArrSeed[0] = parseInt(scwArrInput[0],10);   // Year
                         scwArrSeed[1] = '6';                           // Month
                         scwArrSeed[2] = 1;                             // Day
                         break;
                        }
                     case 2:
                        {// Year and Month entry
                         scwArrSeed[0] =
                             parseInt(scwArrInput[scwDateInputSequence.
                                                    replace(/D/i,'').
                                                    search(/Y/i)],10);  // Year
                         scwArrSeed[1] = scwArrInput[scwDateInputSequence.
                                                    replace(/D/i,'').
                                                    search(/M/i)];      // Month
                         scwArrSeed[2] = 1;                             // Day
                         break;
                        }
                     case 3:
                        {// Day Month and Year entry

                         scwArrSeed[0] =
                             parseInt(scwArrInput[scwDateInputSequence.
                                                    search(/Y/i)],10);  // Year
                         scwArrSeed[1] = scwArrInput[scwDateInputSequence.
                                                    search(/M/i)];      // Month
                         scwArrSeed[2] =
                             parseInt(scwArrInput[scwDateInputSequence.
                                                    search(/D/i)],10);  // Day

                         scwBlnFullInputDate = true;
                         break;
                        }
                     default:
                        {// A stuff-up has led to more than three elements in
                         // the date.
                         scwArrSeed[0] = 0;     // Year
                         scwArrSeed[1] = 0;     // Month
                         scwArrSeed[2] = 0;     // Day
                        }
                    }

                 // These regular expressions validate the input date format
                 // to the following rules;
                 //         Day   1-31 (optional zero on single digits)
                 //         Month 1-12 (optional zero on single digits)
                 //                     or case insensitive name
                 //         Year  One, Two or four digits

                 // Months names are as set in the language-dependent
                 // definitions and delimiters are set just below there

                 var scwExpValDay    = /^(0?[1-9]|[1-2]\d|3[0-1])$/,
                     scwExpValMonth  = new RegExp('^(0?[1-9]|1[0-2]|'        +
                                                  scwArrMonthNames.join('|') +
                                                  ')$','i'),
                     scwExpValYear   = /^(\d{1,2}|\d{4})$/;

                 // Apply validation and report failures

                 if (scwExpValYear.exec(scwArrSeed[0])  == null ||
                     scwExpValMonth.exec(scwArrSeed[1]) == null ||
                     scwExpValDay.exec(scwArrSeed[2])   == null
                    )
                    {if (scwShowInvalidDateMsg)
                        alert(scwInvalidDateMsg  +
                               scwInvalidAlert[0] + scwDateValue +
                               scwInvalidAlert[1]);
                     scwBlnFullInputDate = false;
                     scwArrSeed[0] = scwBaseYear +
                                     Math.floor(scwDropDownYears/2); // Year
                     scwArrSeed[1] = '6';                            // Month
                     scwArrSeed[2] = 1;                              // Day
                    }

                 // Return the  Year    in scwArrSeed[0]
                 //             Month   in scwArrSeed[1]
                 //             Day     in scwArrSeed[2]

                 return scwArrSeed;
                }

             // Parse the string into an array using the allowed delimiters

             scwArrSeedDate = scwInputFormat();

             // So now we have the Year, Month and Day in an array.

             //   If the year is one or two digits then the routine assumes a
             //   year belongs in the 21st Century unless it is less than 50
             //   in which case it assumes the 20th Century is intended.

             if (scwArrSeedDate[0]<100)
                scwArrSeedDate[0] += (scwArrSeedDate[0]>50)?1900:2000;

             // Check whether the month is in digits or an abbreviation

             if (scwArrSeedDate[1].search(/\d+/)!=0)
                {month = scwArrMonthNames.join('|').toUpperCase().
                            search(scwArrSeedDate[1].substr(0,3).
                                                    toUpperCase());
                 scwArrSeedDate[1] = Math.floor(month/4)+1;
                }

             scwSeedDate = new Date(scwArrSeedDate[0],
                                    scwArrSeedDate[1]-1,
                                    scwArrSeedDate[2]);
            }

         // Test that we have arrived at a valid date

         if (isNaN(scwSeedDate))
            {if (scwShowInvalidDateMsg)
                alert(  scwInvalidDateMsg +
                        scwInvalidAlert[0] + scwDateValue +
                        scwInvalidAlert[1]);
             scwSeedDate = new Date(scwBaseYear +
                    Math.floor(scwDropDownYears/2),5,1);
             scwBlnFullInputDate=false;
            }
         else
            {// Test that the date is within range,
             // if not then set date to a sensible date in range.

             if ((new Date(scwBaseYear,0,1)) > scwSeedDate)
                {if (scwBlnStrict && scwShowOutOfRangeMsg)
                    alert(scwOutOfRangeMsg);
                 scwSeedDate = new Date(scwBaseYear,0,1);
                 scwBlnFullInputDate=false;
                }
             else
                {if ((new Date(scwBaseYear+scwDropDownYears,0,0))<
                      scwSeedDate)
                    {if (scwBlnStrict && scwShowOutOfRangeMsg)
                        alert(scwOutOfRangeMsg);
                     scwSeedDate = new Date(scwBaseYear +
                                            Math.floor(scwDropDownYears)-1,
                                                       11,1);
                     scwBlnFullInputDate=false;
                    }
                 else
                    {if (scwBlnStrict && scwBlnFullInputDate &&
                          (scwSeedDate.getDate()      != scwArrSeedDate[2] ||
                           (scwSeedDate.getMonth()+1) != scwArrSeedDate[1] ||
                           scwSeedDate.getFullYear()  != scwArrSeedDate[0]
                          )
                        )
                        {if (scwShowDoesNotExistMsg) alert(scwDoesNotExistMsg);
                         scwSeedDate = new Date(scwSeedDate.getFullYear(),
                                                scwSeedDate.getMonth()-1,1);
                         scwBlnFullInputDate=false;
                        }
                    }
                }
            }

         // Test the disabled dates for validity
         // Give error message if not valid.

         for (var i=0;i<scwDisabledDates.length;i++)
            {if (!((typeof scwDisabledDates[i]      == 'object') &&
                   (scwDisabledDates[i].constructor == Date)))
                {if ((typeof scwDisabledDates[i]      == 'object') &&
                     (scwDisabledDates[i].constructor == Array))
                    {var scwPass = true;

                     if (scwDisabledDates[i].length !=2)
                        {if (scwShowRangeDisablingError)
                            alert(  scwRangeDisablingError[0] +
                                    scwDisabledDates[i] +
                                    scwRangeDisablingError[1]);
                         scwPass = false;
                        }
                     else
                        {for (var j=0;j<scwDisabledDates[i].length;j++)
                            {if (!((typeof scwDisabledDates[i][j]
                                    == 'object') &&
                                   (scwDisabledDates[i][j].constructor
                                    == Date)))
                                {if (scwShowRangeDisablingError)
                                    alert(  scwDateDisablingError[0] +
                                            scwDisabledDates[i][j] +
                                            scwDateDisablingError[1]);
                                 scwPass = false;
                                }
                            }
                        }

                     if (scwPass &&
                         (scwDisabledDates[i][0] > scwDisabledDates[i][1])
                        )
                        {scwDisabledDates[i].reverse();}
                    }
                 else
                    {if (scwShowRangeDisablingError)
                        alert(  scwDateDisablingError[0] +
                                scwDisabledDates[i] +
                                scwDateDisablingError[1]);
                    }
                }
            }

         // Calculate the number of months that the entered (or
         // defaulted) month is after the start of the allowed
         // date range.

         scwMonthSum =  12*(scwSeedDate.getFullYear()-scwBaseYear)+
                            scwSeedDate.getMonth();

         // Set the drop down boxes.

         scwID('scwYears' ).options.selectedIndex = Math.floor(scwMonthSum/12);
         scwID('scwMonths').options.selectedIndex = (scwMonthSum%12);

         // Opera has a bug with this method of setting the selected index.
         // It requires the following work-around to force SELECTs to display
         // correctly.

         if (window.opera)
            {scwID('scwMonths').style.display = 'none';
             scwID('scwMonths').style.display = 'block';
             scwID('scwYears' ).style.display = 'none';
             scwID('scwYears' ).style.display = 'block';
            }

         // The bug is apparently known and "fixed for future versions"
         // but they say they aren't going to put the fix into the 9.x
         // series.

         // Check whether or not dragging is allowed and display drag handle
         // if necessary

         scwID('scwDrag').style.display=
             (scwAllowDrag)
                ?((scwID('scwIFrame'))?'block':'table-row')
                :'none';

         // Display the month

         scwShowMonth(0);

         // Position the calendar box

         // The object sniffing for Opera allows for the fact that Opera
         // is the only major browser that correctly reports the position
         // of an element in a scrollable DIV.  This is because IE and
         // Firefox omit the DIV from the offsetParent tree.

         scwTargetEle=scwEle;

         var offsetTop =parseInt(scwEle.offsetTop ,10) +
                        parseInt(scwEle.offsetHeight,10),
             offsetLeft=parseInt(scwEle.offsetLeft,10);

         if (!window.opera)
             {while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML')
                 {offsetTop -=parseInt(scwEle.scrollTop, 10);
                  offsetLeft-=parseInt(scwEle.scrollLeft,10);
                  scwEle=scwEle.parentNode;
                 }
              scwEle=scwTargetEle;
             }

         do {scwEle=scwEle.offsetParent;
             offsetTop +=parseInt(scwEle.offsetTop, 10);
             offsetLeft+=parseInt(scwEle.offsetLeft,10);
            }
         while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML');

         scwID('scw').style.top =offsetTop +'px';
         scwID('scw').style.left=offsetLeft+'px';

         if (scwID('scwIframe'))
            {scwID('scwIframe').style.top=offsetTop +'px';
             scwID('scwIframe').style.left=offsetLeft+'px';
             scwID('scwIframe').style.width=(scwID('scw').offsetWidth-2)+'px';
             scwID('scwIframe').style.height=(scwID('scw').offsetHeight-2)+'px';
             scwID('scwIframe').style.visibility='visible';
            }

         // Show it on the page

         scwID('scw').style.visibility='visible';

         // Ensure that Opera actually displays the value that is selected!

         scwID('scwYears' ).options.selectedIndex = scwID('scwYears' ).options.selectedIndex;
         scwID('scwMonths').options.selectedIndex = scwID('scwMonths').options.selectedIndex;

         var el = (scwSourceEle.parentNode)
                    ?scwSourceEle.parentNode
                    :scwSourceEle;

         if (typeof event=='undefined')
                {el.addEventListener('click',
                                     scwStopPropagation,
                                     false);
                }
         else   {if (el.attachEvent)
                        {el.attachEvent('onclick',scwStopPropagation);}
                 else   {event.cancelBubble = true;}
                }
        }

    function scwHide()
        {scwID('scw').style.visibility='hidden';
         if (scwID('scwIframe'))
            {scwID('scwIframe').style.visibility='hidden';}

         if (typeof scwNextAction!='undefined' && scwNextAction!=null)
             {scwNextActionReturn = scwNextAction();
              // Explicit null set to prevent closure causing memory leak
              scwNextAction = null;
             }
        }

    function scwCancel(scwEvt)
        {if (scwClickToHide) scwHide();
         scwStopPropagation(scwEvt);
        }

    function scwStopPropagation(scwEvt)
        {if (scwEvt.stopPropagation)
                scwEvt.stopPropagation();     // Capture phase
         else   scwEvt.cancelBubble = true;   // Bubbling phase
        }

    function scwBeginDrag(event)
        {var elementToDrag = scwID('scw');

         var deltaX    = event.clientX,
             deltaY    = event.clientY,
             offsetEle = elementToDrag;

         do {deltaX   -= parseInt(offsetEle.offsetLeft,10);
             deltaY   -= parseInt(offsetEle.offsetTop ,10);
             offsetEle = offsetEle.offsetParent;
            }
         while (offsetEle.tagName!='BODY' &&
                offsetEle.tagName!='HTML');

         if (document.addEventListener)
                {document.addEventListener('mousemove',
                                           moveHandler,
                                           true);        // Capture phase
                 document.addEventListener('mouseup',
                                           upHandler,
                                           true);        // Capture phase
                }
         else   {elementToDrag.attachEvent('onmousemove',
                                           moveHandler); // Bubbling phase
                 elementToDrag.attachEvent('onmouseup',
                                             upHandler); // Bubbling phase
                 elementToDrag.setCapture();
                }

         scwStopPropagation(event);

         function moveHandler(scwEvt)
            {if (!scwEvt) scwEvt = window.event;

             elementToDrag.style.left = (scwEvt.clientX - deltaX) + 'px';
             elementToDrag.style.top  = (scwEvt.clientY - deltaY) + 'px';

             if (scwID('scwIframe'))
                {scwID('scwIframe').style.left =
                    (scwEvt.clientX - deltaX) + 'px';
                 scwID('scwIframe').style.top  =
                    (scwEvt.clientY - deltaY) + 'px';
                }

             scwStopPropagation(scwEvt);
            }

         function upHandler(scwEvt)
            {if (!scwEvt) scwEvt = window.event;

             if (document.removeEventListener)
                    {document.removeEventListener('mousemove',
                                                  moveHandler,
                                                  true);     // Capture phase
                     document.removeEventListener('mouseup',
                                                  upHandler,
                                                  true);     // Capture phase
                    }
             else   {elementToDrag.detachEvent('onmouseup',
                                                 upHandler); // Bubbling phase
                     elementToDrag.detachEvent('onmousemove',
                                               moveHandler); // Bubbling phase
                     elementToDrag.releaseCapture();
                    }

             scwStopPropagation(scwEvt);
            }
        }

    function scwShowMonth(scwBias)
        {// Set the selectable Month and Year
         // May be called: from the left and right arrows
         //                  (shift month -1 and +1 respectively)
         //                from the month selection list
         //                from the year selection list
         //                from the showCal routine
         //                  (which initiates the display).

         var scwShowDate  = new Date(Date.parse(new Date().toDateString())),
             scwStartDate = new Date();

         // Set the time to the middle of the day so that the handful of
         // regions that have daylight saving shifts that change the day
         // of the month (i.e. turn the clock back at midnight or forward
         // at 23:00) do not mess up the date display in the calendar.

         scwShowDate.setHours(12);

         scwSelYears  = scwID('scwYears');
         scwSelMonths = scwID('scwMonths');

         if (scwSelYears.options.selectedIndex>-1)
            {scwMonthSum=12*(scwSelYears.options.selectedIndex)+scwBias;
             if (scwSelMonths.options.selectedIndex>-1)
                {scwMonthSum+=scwSelMonths.options.selectedIndex;}
            }
         else
            {if (scwSelMonths.options.selectedIndex>-1)
                {scwMonthSum+=scwSelMonths.options.selectedIndex;}
            }

         scwShowDate.setFullYear(scwBaseYear + Math.floor(scwMonthSum/12),
                                 (scwMonthSum%12),
                                 1);

         // If the Week numbers are displayed, shift the week day names
         // to the right.
         scwID('scwWeek_').style.display=
             (scwWeekNumberDisplay)
                ?((scwID('scwIFrame'))?'block':'table-cell')
                :'none';

         if ((12*parseInt((scwShowDate.getFullYear()-scwBaseYear),10)) +
             parseInt(scwShowDate.getMonth(),10) < (12*scwDropDownYears)  &&
             (12*parseInt((scwShowDate.getFullYear()-scwBaseYear),10)) +
             parseInt(scwShowDate.getMonth(),10) > -1)
            {scwSelYears.options.selectedIndex=Math.floor(scwMonthSum/12);
             scwSelMonths.options.selectedIndex=(scwMonthSum%12);

             scwCurMonth = scwShowDate.getMonth();

             scwShowDate.setDate((((scwShowDate.
                                    getDay()-scwWeekStart)<0)?-6:1)+
                                 scwWeekStart-scwShowDate.getDay());

             // This statement moved by Michael Cerveny to make version 3.55
             var scwCompareDateValue = new Date(scwShowDate.getFullYear(),
                                                scwShowDate.getMonth(),
                                                scwShowDate.getDate()).valueOf();

             scwStartDate = new Date(scwShowDate);

             var scwFoot = scwID('scwFoot');

             function scwFootOutput() {scwSetOutput(scwDateNow);}

             if (scwDisabledDates.length==0)
                {if (scwActiveToday && scwParmActiveToday)
                    {scwFoot.onclick     = scwFootOutput;
                     scwFoot.className   = 'scwFoot';

                     if (scwID('scwIFrame'))
                        {scwFoot.onmouseover  = scwChangeClass;
                         scwFoot.onmouseout   = scwChangeClass;
                        }

                    }
                 else
                    {scwFoot.onclick     = null;
                     scwFoot.className   = 'scwFootDisabled';

                     if (scwID('scwIFrame'))
                        {scwFoot.onmouseover  = null;
                         scwFoot.onmouseout   = null;
                        }

                     if (document.addEventListener)
                            {scwFoot.addEventListener('click',
                                                      scwStopPropagation,
                                                      false);
                            }
                     else   {scwFoot.attachEvent('onclick',
                                                 scwStopPropagation);}
                    }
                }
             else
                {for (var k=0;k<scwDisabledDates.length;k++)
                    {if (!scwActiveToday || !scwParmActiveToday ||
                         ((typeof scwDisabledDates[k] == 'object')            &&
                             (((scwDisabledDates[k].constructor == Date)      &&
                               scwDateNow.valueOf() == scwDisabledDates[k].
                                                        valueOf()
                              ) ||
                              ((scwDisabledDates[k].constructor == Array)     &&
                               scwDateNow.valueOf() >= scwDisabledDates[k][0].
                                                        valueOf()             &&
                               scwDateNow.valueOf() <= scwDisabledDates[k][1].
                                                        valueOf()
                              )
                             )
                         )
                        )
                        {scwFoot.onclick     = null;
                         scwFoot.className   = 'scwFootDisabled';

                         if (scwID('scwIFrame'))
                            {scwFoot.onmouseover  = null;
                             scwFoot.onmouseout   = null;
                            }

                         if (document.addEventListener)
                                {scwFoot.addEventListener('click',
                                                          scwStopPropagation,
                                                          false);
                                }
                         else   {scwFoot.attachEvent('onclick',
                                                     scwStopPropagation);
                                }
                         break;
                        }
                     else
                        {scwFoot.onclick=scwFootOutput;
                         scwFoot.className='scwFoot';

                         if (scwID('scwIFrame'))
                            {scwFoot.onmouseover  = scwChangeClass;
                             scwFoot.onmouseout   = scwChangeClass;
                            }
                        }
                    }
                }

             function scwSetOutput(scwOutputDate)
                {if (typeof scwTargetEle.value == 'undefined')
                    {scwTriggerEle.scwTextNode.
                        replaceData(0,scwTriggerEle.scwLength,
                                    scwOutputDate.scwFormat(scwDateOutputFormat));
                    }
                 else
                    {scwTargetEle.value =
                        scwOutputDate.scwFormat(scwDateOutputFormat);
                    }
                 scwHide();
                }

             function scwCellOutput(scwEvt)
                {var scwEle = scwEventTrigger(scwEvt),
                     scwOutputDate = new Date(scwStartDate);

                 if (scwEle.nodeType==3) scwEle=scwEle.parentNode;

                 scwOutputDate.setDate(scwStartDate.getDate() +
                                         parseInt(scwEle.id.substr(8),10));

                 scwSetOutput(scwOutputDate);
                }

             function scwChangeClass(scwEvt)
                {var scwEle = scwEventTrigger(scwEvt);

                 if (scwEle.nodeType==3) scwEle=scwEle.parentNode;

                 switch (scwEle.className)
                    {case 'scwCells':
                        scwEle.className = 'scwCellsHover';
                        break;
                     case 'scwCellsHover':
                        scwEle.className = 'scwCells';
                        break;
                     case 'scwCellsExMonth':
                        scwEle.className = 'scwCellsExMonthHover';
                        break;
                     case 'scwCellsExMonthHover':
                        scwEle.className = 'scwCellsExMonth';
                        break;
                     case 'scwCellsWeekend':
                        scwEle.className = 'scwCellsWeekendHover';
                        break;
                     case 'scwCellsWeekendHover':
                        scwEle.className = 'scwCellsWeekend';
                        break;
                     case 'scwFoot':
                        scwEle.className = 'scwFootHover';
                        break;
                     case 'scwFootHover':
                        scwEle.className = 'scwFoot';
                        break;
                     case 'scwInputDate':
                        scwEle.className = 'scwInputDateHover';
                        break;
                     case 'scwInputDateHover':
                        scwEle.className = 'scwInputDate';
                    }

                 return true;
                }

             function scwEventTrigger(scwEvt)
                {if (!scwEvt) scwEvt = event;
                 return scwEvt.target||scwEvt.srcElement;
                }

             function scwWeekNumber(scwInDate)
                {// The base day in the week of the input date
                 var scwInDateWeekBase = new Date(scwInDate);

                 scwInDateWeekBase.setDate(scwInDateWeekBase.getDate()
                                            - scwInDateWeekBase.getDay()
                                            + scwWeekNumberBaseDay
                                            + ((scwInDate.getDay()>
                                                scwWeekNumberBaseDay)?7:0));

                 // The first Base Day in the year
                 var scwFirstBaseDay =
                        new Date(scwInDateWeekBase.getFullYear(),0,1)

                 scwFirstBaseDay.setDate(scwFirstBaseDay.getDate()
                                            - scwFirstBaseDay.getDay()
                                            + scwWeekNumberBaseDay
                                        );

                 if (scwFirstBaseDay <
                        new Date(scwInDateWeekBase.getFullYear(),0,1))
                    {scwFirstBaseDay.setDate(scwFirstBaseDay.getDate()+7);}

                 // Start of Week 01
                 var scwStartWeekOne = new Date(scwFirstBaseDay
                                                - scwWeekNumberBaseDay
                                                + scwInDate.getDay());

                 if (scwStartWeekOne > scwFirstBaseDay)
                    {scwStartWeekOne.setDate(scwStartWeekOne.getDate()-7);}

                 // Subtract the date of the current week from the date of the
                 // first week of the year to get the number of weeks in
                 // milliseconds.  Divide by the number of milliseconds
                 // in a week then round to no decimals in order to remove
                 // the effect of daylight saving.  Add one to make the first
                 // week, week 1.  Place a string zero on the front so that
                 // week numbers are zero filled.

                 var scwWeekNo =
                     '0' + (Math.round((scwInDateWeekBase -
                                        scwFirstBaseDay)/604800000,0) + 1);

                 // Return the last two characters in the week number string

                 return scwWeekNo.substring(scwWeekNo.length-2,
                                            scwWeekNo.length);
                }

             // Treewalk to display the dates.
             // I tried to use getElementsByName but IE refused to cooperate
             // so I resorted to this method which works for all tested
             // browsers.

             var scwCells = scwID('scwCells');

             for (i=0;i<scwCells.childNodes.length;i++)
                {var scwRows = scwCells.childNodes[i];
                 if (scwRows.nodeType==1 && scwRows.tagName=='TR')
                    {if (scwWeekNumberDisplay)
                        {//Calculate the week number using scwShowDate
                         scwRows.childNodes[0].innerHTML =
                             scwWeekNumber(scwShowDate);
                         scwRows.childNodes[0].style.display=
                            (scwID('scwIFrame'))
                                ?'block'
                                :'table-cell';
                        }
                     else
                        {scwRows.childNodes[0].style.display='none';}

                     for (j=1;j<scwRows.childNodes.length;j++)
                        {var scwCols = scwRows.childNodes[j];
                         if (scwCols.nodeType==1 && scwCols.tagName=='TD')
                            {scwRows.childNodes[j].innerHTML=
                                scwShowDate.getDate();
                             var scwCell=scwRows.childNodes[j],
                                 scwDisabled =
                                    ((scwOutOfRangeDisable &&
                                        (scwShowDate <
                                            (new Date(scwBaseYear,0,1,
                                                      scwShowDate.getHours()))
                                         ||
                                         scwShowDate >
                                            (new Date(scwBaseYear+
                                                      scwDropDownYears,0,0,
                                                      scwShowDate.getHours()))
                                        )
                                     ) ||
                                     (scwOutOfMonthDisable &&
                                        (scwShowDate <
                                            (new Date(scwShowDate.getFullYear(),
                                                      scwCurMonth,1,
                                                      scwShowDate.getHours()))
                                         ||
                                         scwShowDate >
                                            (new Date(scwShowDate.getFullYear(),
                                                      scwCurMonth+1,0,
                                                      scwShowDate.getHours()))
                                        )
                                     )
                                    )?true:false;

                             scwCell.style.visibility =
                                (scwOutOfMonthHide &&
                                    (scwShowDate <
                                        (new Date(scwShowDate.getFullYear(),
                                                  scwCurMonth,1,
                                                  scwShowDate.getHours()))
                                     ||
                                     scwShowDate >
                                        (new Date(scwShowDate.getFullYear(),
                                                  scwCurMonth+1,0,
                                                  scwShowDate.getHours()))
                                    )
                                )?'hidden':'';

                             for (var k=0;k<scwDisabledDates.length;k++)
                                {if ((typeof scwDisabledDates[k]=='object')
                                     &&
                                     (scwDisabledDates[k].constructor ==
                                      Date
                                     )
                                     &&
                                     scwCompareDateValue ==
                                        scwDisabledDates[k].valueOf()
                                    )
                                    {scwDisabled = true;}
                                 else
                                    {if ((typeof scwDisabledDates[k]=='object')
                                         &&
                                         (scwDisabledDates[k].constructor ==
                                          Array
                                         )
                                         &&
                                         scwCompareDateValue >=
                                            scwDisabledDates[k][0].valueOf()
                                         &&
                                         scwCompareDateValue <=
                                            scwDisabledDates[k][1].valueOf()
                                        )
                                        {scwDisabled = true;}
                                    }
                                }

                             if (scwDisabled ||
                                 !scwEnabledDay[j-1+(7*((i*scwCells.
                                                          childNodes.
                                                          length)/6))] ||
                                 !scwPassEnabledDay[(j-1+(7*(i*scwCells.
                                                               childNodes.
                                                               length/6)))%7]
                                )
                                {scwRows.childNodes[j].onclick     = null;

                                 if (scwID('scwIFrame'))
                                    {scwRows.childNodes[j].onmouseover  = null;
                                     scwRows.childNodes[j].onmouseout   = null;
                                    }

                                 scwCell.className=
                                    (scwShowDate.getMonth()!=scwCurMonth)
                                        ?'scwCellsExMonthDisabled'
                                        :(scwBlnFullInputDate &&
                                          scwShowDate.toDateString()==
                                          scwSeedDate.toDateString())
                                            ?'scwInputDateDisabled'
                                            :(scwShowDate.getDay()%6==0)
                                                ?'scwCellsWeekendDisabled'
                                                :'scwCellsDisabled';
                                }
                             else
                                {scwRows.childNodes[j].onclick=scwCellOutput;

                                 if (scwID('scwIFrame'))
                                    {scwRows.childNodes[j].onmouseover  =
                                        scwChangeClass;
                                     scwRows.childNodes[j].onmouseout   =
                                        scwChangeClass;
                                    }

                                 scwCell.className=
                                     (scwShowDate.getMonth()!=scwCurMonth)
                                        ?'scwCellsExMonth'
                                        :(scwBlnFullInputDate &&
                                          scwShowDate.toDateString()==
                                          scwSeedDate.toDateString())
                                            ?'scwInputDate'
                                            :(scwShowDate.getDay()%6==0)
                                                ?'scwCellsWeekend'
                                                :'scwCells';

                               }

                             scwShowDate.setDate(scwShowDate.getDate()+1);
                             scwCompareDateValue = new Date(scwShowDate.getFullYear(),
                                                            scwShowDate.getMonth(),
                                                            scwShowDate.getDate()).valueOf();
                            }
                        }
                    }
                }
            }
         // Force a re-draw to prevent Opera's poor dynamic rendering
         // from leaving garbage in the calendar when the displayed
         // month is changed.
         scwID('scw').style.visibility='hidden';
         scwID('scw').style.visibility='visible';
        }

// *************************
//  End of Function Library
// *************************
// ***************************
// Start of Calendar structure
// ***************************

    document.write(
     "<!--[if IE]>" +
        "<iframe class='scw' src='/opo/static/scwblank.html' " +
                "id='scwIframe' name='scwIframe' " +
                "frameborder='0'>" +
        "</iframe>" +
     "<![endif]-->" +
     "<table id='scw' class='scw'>" +
       "<tr class='scw'>" +
         "<td class='scw'>" +
           "<table class='scwHead' id='scwHead' width='100%' " +
                    "cellspacing='0' cellpadding='0'>" +
            "<tr id='scwDrag' style='display:none;'>" +
                "<td colspan='4' class='scwDrag' " +
                    "onmousedown='scwBeginDrag(event);'>" +
                    "<div id='scwDragText'></div>" +
                "</td>" +
            "</tr>" +
            "<tr class='scwHead' >" +
                 "<td class='scwHead'>" +
                    "<input class='scwHead' id='scwHeadLeft' type='button' value='<' " +
                            "onclick='scwShowMonth(-1);'  /></td>" +
                 "<td class='scwHead'>" +
                    "<select id='scwMonths' class='scwHead' " +
                            "onchange='scwShowMonth(0);'>" +
                    "</select>" +
                 "</td>" +
                 "<td class='scwHead'>" +
                    "<select id='scwYears' class='scwHead' " +
                            "onchange='scwShowMonth(0);'>" +
                    "</select>" +
                 "</td>" +
                 "<td class='scwHead'>" +
                    "<input class='scwHead' id='scwHeadRight' type='button' value='>' " +
                            "onclick='scwShowMonth(1);' /></td>" +
                "</tr>" +
              "</table>" +
            "</td>" +
          "</tr>" +
          "<tr class='scw'>" +
            "<td class='scw'>" +
              "<table class='scwCells' align='center'>" +
                "<thead>" +
                  "<tr><td class='scwWeekNumberHead' id='scwWeek_' ></td>");

    for (i=0;i<7;i++)
        document.write( "<td class='scwWeek' id='scwWeekInit" + i + "'></td>");

    document.write("</tr>" +
                "</thead>" +
                "<tbody id='scwCells' " +
                        "onClick='scwStopPropagation(event);'>");

    for (i=0;i<6;i++)
        {document.write(
                    "<tr>" +
                      "<td class='scwWeekNo' id='scwWeek_" + i + "'></td>");
         for (j=0;j<7;j++)
            {document.write(
                        "<td class='scwCells' id='scwCell_" + (j+(i*7)) +
                        "'></td>");
            }

         document.write(
                    "</tr>");
        }

    document.write(
                "</tbody>");

    if ((new Date(scwBaseYear + scwDropDownYears, 11, 32)) > scwDateNow &&
        (new Date(scwBaseYear, 0, 0))                      < scwDateNow)
        {document.write(
                  "<tfoot class='scwFoot'>" +
                    "<tr class='scwFoot'>" +
                      "<td class='scwFoot' id='scwFoot' colspan='8'>" +
                      "</td>" +
                    "</tr>" +
                  "</tfoot>");
        }

    document.write(
              "</table>" +
            "</td>" +
          "</tr>" +
        "</table>");

    if (document.addEventListener)
            {scwID('scw'         ).addEventListener('click',scwCancel,false);
             scwID('scwHeadLeft' ).addEventListener('click',scwStopPropagation,false);
             scwID('scwMonths'   ).addEventListener('click',scwStopPropagation,false);
             scwID('scwMonths'   ).addEventListener('change',scwStopPropagation,false);
             scwID('scwYears'    ).addEventListener('click',scwStopPropagation,false);
             scwID('scwYears'    ).addEventListener('change',scwStopPropagation,false);
             scwID('scwHeadRight').addEventListener('click',scwStopPropagation,false);
            }
    else    {scwID('scw'         ).attachEvent('onclick',scwCancel);
             scwID('scwHeadLeft' ).attachEvent('onclick',scwStopPropagation);
             scwID('scwMonths'   ).attachEvent('onclick',scwStopPropagation);
             scwID('scwMonths'   ).attachEvent('onchange',scwStopPropagation);
             scwID('scwYears'    ).attachEvent('onclick',scwStopPropagation);
             scwID('scwYears'    ).attachEvent('onchange',scwStopPropagation);
             scwID('scwHeadRight').attachEvent('onclick',scwStopPropagation);
            }

// ***************************
//  End of Calendar structure
// ***************************
// ****************************************
// Start of document level event definition
// ****************************************

    if (document.addEventListener)
            {document.addEventListener('click',scwHide, false);}
    else    {document.attachEvent('onclick',scwHide);}

// ****************************************
//  End of document level event definition
// ****************************************
// ************************************
//  End of Simple Calendar Widget Code
// ************************************/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/Slider.class.js */
/**
 * Fader to support fade in / out effects to elements.
 *
 * @author tam
 */ 

Slider.MODE_TOP_BOTTOM = 1;
Slider.MODE_LEFT_RIGHT = 2;
 
function Slider(mode)
{
	var element = null;
	var innerElement = null;
	var opacity = null;
	var numSteps = null;
	var intervalId = null;
	this.mode = (mode == null ? Slider.MODE_TOP_BOTTOM : mode);
	
	var slideHeight = 0;
	var height = 0;
	var slideWidth = 0;
	var width = 0;
	
	var lastHeightDiff = 0;
	var lastWidthDiff = 0;
}

Slider.prototype.slideOutElementById = function(_elementId)
{
	var element = getElement(_elementId);
	this.slideOut(element);
}

Slider.prototype.slideOut = function(_element, _innerElement)
{
	this.element = _element;
	this.innerElement = _innerElement;
	// determine the slide height / slide width;
	
	// TODO: implement sliding horizontally
	// TODO: implement default behaviour if "clientHeight" property is
	// not supported by the useragent
	
	this.slideHeight = this.element.clientHeight;
	this.slideWidth = this.element.clientWidth;
	this.height = this.slideHeight;
	this.width = this.slideWidth;
	this.lastHeightDiff = 0;
	this.lastWidthDiff = 0;
	
	// set initial height
	this.innerElement.style.position = "relative";
	if(this.mode & Slider.MODE_TOP_BOTTOM)
	{
		this.innerElement.style.top = "0px";
	}
	if(this.mode & Slider.MODE_LEFT_RIGHT)
	{
		this.innerElement.style.left = "0px";
	}

	var _this = this;
	var sliderFunction = function() { _this.internalSlideOut() };	

	this.intervalId = window.setInterval(sliderFunction, 20);
}

Slider.prototype.slideInElementById = function(_elementId)
{
	var element = getElement(_elementId);
	this.slideId(element);
}

/**
 * Slide in an element (using mode set). To slide in an element, the element
 * is assumed to have the visibility set to "hidden" and default value of
 * display (i.e. not "none"). The width and height attributes should have a
 * value of "auto".
 */
Slider.prototype.slideIn = function(_element, _innerElement)
{
	this.element = _element;
	this.innerElement = _innerElement;
	
	// determine the slide height / slide width;
	
	// TODO: implement sliding horizontally
	// TODO: implement default behaviour if "clientHeight" property is
	// not supported by the useragent
	
	this.slideHeight = this.element.clientHeight;
	this.slideWidth = this.element.clientWidth;
	this.height = 0;
	this.width = 0;
	this.lastHeightDiff = 0;
	this.lastWidthDiff = 0;
	
	// set initial height
	/* this.element.style.height = "0px"; */
	// this.element.style.clip = "rect(auto, auto, " + this.slideHeight + "px, auto)";
	this.innerElement.style.position = "relative";
	if(this.mode & Slider.MODE_TOP_BOTTOM)
	{
		this.innerElement.style.top = "-" + this.slideHeight + "px";
	}
	if(this.mode & Slider.MODE_LEFT_RIGHT)
	{
		this.innerElement.style.left = "-" + this.slideWidth + "px";
	}
	
	this.element.style.visibility = "visible";

	var _this = this;
	var sliderFunction = function() { _this.internalSlideIn() };	

	this.intervalId = window.setInterval(sliderFunction, 20);
}
			
Slider.prototype.internalSlideOut = function()
{
	this.internalSlide(-1);
}

Slider.prototype.internalSlideIn = function()
{
	this.internalSlide(1);
}
	
Slider.prototype.internalSlide = function(inOut)
{
	// calculate new height to be set
	var heightDiff = 0;
	var widthDiff = 0;
	if(this.lastHeightDiff == 0)
	{
		heightDiff = 1;
	}
	else
	{
		heightDiff = this.lastHeightDiff + 1;
	}
	this.lastHeightDiff = heightDiff;
	this.height += (inOut) * heightDiff;
	
	// calculate new width to be set
	if(this.lastWidthDiff == 0)
	{
		widthDiff = 1;
	}
	else
	{
		widthDiff = this.lastWidthDiff + 1;
	}
	this.lastWidthDiff = widthDiff;
	this.width += (inOut) * widthDiff;
	
	if((this.height <= 0))
	{
		window.clearInterval(this.intervalId);
		this.height = 0;
		this.width = 0;
		this.element.style.visibility = "hidden";
		this.innerElement.style.top = "0px";
	}
	else if(this.height >= this.slideHeight)
	{
		window.clearInterval(this.intervalId);
		this.height = this.slideHeight;
		this.width = this.slideWidth;
		//this.element.style.clip = "auto";
		this.innerElement.style.top = "0px";
		this.innerElement.style.left = "0px";
	}
	else
	{
		if(this.mode & Slider.MODE_TOP_BOTTOM)
		{
			var innerTop = this.slideHeight - this.height;
			this.innerElement.style.top = "-" + innerTop + "px";
		}
		if(this.mode & Slider.MODE_LEFT_RIGHT)
		{
			//alert("InnerLeft: " + innerLeft + "; slideWidth: " + this.slideWidth + "; width: " + this.width);
			var innerLeft = this.slideWidth - this.width;
			this.innerElement.style.left = "-" + innerLeft + "px";
		}
	}
	
}/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/XMLRPCPost.class.js */
/**
 */

/**
 * Constructor
 */
function XMLRPCPost() 
{
	this.log = LogFactory.getLog("XMLRPCPost");

	this.form = null;
	this.elements = new Array();
	this.eventSourceElement = null;
	
	this.url = null;
	
	this.responseText = null;
	this.responseXML = null;
	this.xmlrpc = null;
}

/**
 * Add an element whose data should be included in post body
 */
XMLRPCPost.prototype.addElement = function(_element)
{
	this.log.debug("adding element " + _element);
	this.elements.push(_element);
}

/**
 * Submit a form; the event source element may be specified to "simulate"
 * normal form post (if specified, other form submit buttons, etc. will be
 * excluded).
 */
XMLRPCPost.prototype.submit = function(_form, _sourceElement)
{
	this.form = _form;
	this.log.debug("form is " + this.form);
	if(!this.url)
	{
		this.url = this.form.action;
		this.log.debug("using form url: " + this.url);
	}
	this.eventSourceElement = _sourceElement;
	
	var _this = this;
	
	this.xmlrpc = new XMLRPCProvider();
	//this.xmlrpc.async = false;
	this.xmlrpc.onComplete = function(_responseText, _responseXML) { _this.internalCallback(_responseText, _responseXML); };
	
	var body = this.internalCreateBody();
	this.log.debug("body to post: " + body);
	
	this.xmlrpc.post(this.url, body);
}



/**
 * Creates the http post body using all form elements, and / or additionally 
 * defined elements.
 */
XMLRPCPost.prototype.internalCreateBody = function()
{
	// create array of all elements to include
	var includeElements = new Array();
	
	// if form is present, add all form elements
	if(this.form != null)
	{
		frmElements = this.form.elements;
		for(var i = 0; i < frmElements.length; i++)
		{
			includeElements.push(frmElements[i]);
		}
		this.log.debug("adding " + frmElements.length + " form elements to encode; now contains " + includeElements.length + " elements");
		
	}
	
	// add array of elements
	if(this.elements != null && this.elements instanceof Array && this.elements.length > 0)
	{
		this.log.debug("adding " + this.elements.length + " form elements to the array");
		includeElements = includeElements.concat(this.elements);
	}
	
	// add event source element (some form elements are not present in the
	// array of elements, e.g. image submit; thus the event source element
	// has to be added to the elements)
	if(this.eventSourceElement != null)
	{
		this.log.debug("adding event source form element to the array");
		includeElements.push(this.eventSourceElement);
	}
	
	// create http post body
	var body = "";
	var elemCount = includeElements.length;
	this.log.info("Number of elements: " + elemCount);
	
	for(var i = 0; i < elemCount; i++)
	{
		var curElement = includeElements[i];
		var curType = curElement.type;
		// if event source element specified all other submit buttons should 
		// be excluded
		if(curType == "button" || curType == "submit" || curType == "image"
			|| curType == "reset")
		{
			// exclude if not event source element
			if(this.eventSourceElement != null 
				&& this.eventSourceElement != curElement)
			{
				continue;
			}
		}
		var encodedElement = this.internalEncodeElement(curElement);
		if(encodedElement != "")
		{
			this.log.debug("adding encoded element to body: " + encodedElement);
			if(body != "")
			{
				body += "&";
			}
			body += encodedElement;
		}
	}
	return body;
}

/**
 * Creates an URI encoded string representation of an element.
 */
XMLRPCPost.prototype.internalEncodeElement = function(_element)
{
	// encode element name and value
	var encodedName = encodeURIComponent(_element.name);
	var encodedValue = encodeURIComponent(_element.value);
	
	// do not create part for elements without name
	if(encodedName == "")
	{
		return "";
	}
	
	// handle hidden
	if(_element.type == "hidden")
	{
		return encodedName + "=" + encodedValue;
	}
	
	// handle checkboxes
	if(_element.type == "checkbox")
	{
		if(_element.checked)
		{
			return encodedName + "=" + encodedValue;
		}
		return "";
	}
	
	// handle radio button
	if(_element.type == "radio")
	{
		if(_element.checked)
		{
			return encodedName + "=" + encodedValue;
		}
		return "";
	}
	
	// handle select boxes
	if(_element.options)
	{
		var uriPart = "";
		var optionCount = _element.options.length;
		for(var i = 0; i < optionCount; i++)
		{
			var option = _element.options[i];
			if(option.selected)
			{
				if(uriPart != "")
				{
					uriPart += "&";
				}
				uriPart += encodedName + "=" + encodeURIComponent(option.value);
			}
		}
		return uriPart;
	}

	// handle image (coordinates submitted are always 0 / 0)
	if(_element.type == "image")
	{
		var uriPart = "";
		uriPart += encodedName + ".x=0&";
		uriPart += encodedName + ".y=0&";
		uriPart += encodedName + "=" + encodedValue;
		return uriPart;
	}
	
	// handle button
	if(_element.type == "button" || _element.type == "submit")
	{
		return encodedName + "=" + encodedValue;
	}
	
	// text fields
	if(_element.type == "text" || _element.type == "textarea")
	{
		return encodedName + "=" + encodedValue;
	}
}

/**
 *
 */
XMLRPCPost.prototype.internalCallback = function(_responseText, _responseXML)
{
	this.log.info("internalCallback: request is complete");
	this.log.debug("responseText length: " + _responseText);
	this.log.debug("responseXML: " + _responseXML);
	this.responseText = _responseText;
	this.responseXML = _responseXML;
	this.onComplete(_responseText,_responseXML);
}

XMLRPCPost.prototype.onComplete = function()
{
}

/* generated from file :/home/gto/workspace-git/ishop-opo/ishop-opo-data/htdocs/common/js/XMLRPCProvider.class.js */
/**
 * (C) 2006 IMIS group AG, Zurich, Switzerland. 
 * 
 * XMLRPCProvider class, based on code from:
 * 
 * ------------------------------------------------------
 * JavaScript Refactoring for safer, faster, better AJAX.
 *
 * Copyright 2005, Pavel Simakov, 
 * http://www.softwaresecretweapons.com
 * ------------------------------------------------------
 * 
 * @author tam
 */
 

// http method constants
XMLRPCProvider.METHOD_GET = "GET";
XMLRPCProvider.METHOD_POST = "POST";

// constructor
function XMLRPCProvider() {	

	this.log = LogFactory.getLog("XMLRPCProvider");
	
	this.status = null;
	this.async = true;
	
	var method = XMLRPCProvider.METHOD_GET;
	var url = null;	
	var body = null;
	var req = null;
	var inProgress = false;
	var isComplete = false;
}

	
// tells us whether we are busy waiting for the response to another request
XMLRPCProvider.prototype.internalIsBusy = function(){
	return this.inProgress && !this.isComplete;
}	
	
// internal callback function for the browser; it is called when a state of a request object changes
XMLRPCProvider.prototype.internalRequestComplete = function() {
				
	var STATE_COMPLETED = 4;
	var STATUS_200 = 200;

	if (!this.internalIsBusy()) {
		this.log.error("internalRequestComplete: error - no request submitted");
	}
	
	this.onProgress(this.req.readyState);
	
	this.log.debug("internalRequestComplete: readyState " + this.req.readyState);

	if (this.req.readyState == STATE_COMPLETED) {
		this.status = this.req.status;
		this.inProgress = false;
		this.isComplete = true;
		
		this.log.debug("internalRequestComplete: status " + status);
		
		if (this.status == STATUS_200) {
			this.log.debug("internalRequestComplete: calling callback on content with length " + this.req.responseText.length + " chars");
			this.log.debug("internalRequestComplete: response headers = " + this.req.getAllResponseHeaders());
			this.log.debug("internalRequestComplete: xml document: " + this.req.responseXML);
			if(this.onComplete) {
				this.onComplete(this.req.responseText, this.req.responseXML);
			}
			this.log.info("internalRequestComplete: complete on " + new Date());
		} else {
			this.log.warn("internalRequestComplete: error - bad status while fetching " + this.url + " - status: " + this.status);
		}
	} else {
		// do nothing in particular
	}
}	
	
// call this function to figure out version of this class
XMLRPCProvider.prototype.getVersion = function(){
	return "1.0.0";
}
	
// call this function to figure out if current browser supports XML HTTP Requests
XMLRPCProvider.prototype.isSupported = function(){
	var nonEI = window.XMLHttpRequest;
	var onIE = window.ActiveXObject;
		
	if (onIE) {	    		
		onIE = new ActiveXObject("Microsoft.XMLHTTP") != null;
	}
		
	return window.XMLHttpRequest || onIE;
}

// internally called to create new instance of XMLHttpRequest
XMLRPCProvider.prototype.internalNewRequest = function()
{
  	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  this.log.debug("Trying to use Msxml2.XMLHTTP ActiveX Object...");
	  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   this.log.debug("Trying to use Microsoft.XMLHTTP ActiveX Object...");
	   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   this.log.error("failed to create xml http request (MSIE)");
	   xmlhttp = false;
	  }
	 }
	 if(xmlhttp)
	 {
	   this.log.debug("created xml http request successfully (MSIE)");
	 }
	 this.log.debug("cache request headers set (MSIE)");
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	  xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}
	
// call this function to find out if more calls are possible and if request has been completely received 
XMLRPCProvider.prototype.isBusy = function(){
	return this.internalIsBusy();
}		

/**
 * Submit POST request
 */
XMLRPCProvider.prototype.post = function(_url, _body)
{
	this.submit(XMLRPCProvider.METHOD_POST, _url, _body);
}

/**
 * Submit GET request
 */
XMLRPCProvider.prototype.get = function(_url)
{
	this.submit(XMLRPCProvider.METHOD_GET, _url, null);
}

/**
 * Submit called by post / get methods.
 *
 * Todo: Add support for sync requests???
 */
XMLRPCProvider.prototype.submit = function(_method, _url, _body){
	if (this.internalIsBusy()) {
		this.log.error("submit: error - busy processing another request " + _url);			
	}
	
	this.msgCount = 0;
	this.log.info("submit: started on " + new Date() + " for " + _url);
	
	this.method = _method;
	this.url = _url;
	this.body = _body;
	this.status = null;
	this.inProgress = true;
	this.isComplete = false;
	
    this.log.debug("creating new XMLHttpRequest");
	// create new request
	this.req = this.internalNewRequest();
	
	this.log.info("created new request: " + this.req);
	
	this.log.debug("using method " + this.method + " to submit request");
	
	this.log.debug("initiating call (set callback and open); async = " + this.async);
	if(this.async)
	{
		var _this = this;
		this.req.onreadystatechange = function() { _this.internalRequestComplete(); };
	}
    this.req.open(this.method, this.url, this.async);
	
	// set headers necessary for post requests
	if(this.method == XMLRPCProvider.METHOD_POST)
	{
		this.log.debug("setting request header: Content-type");
		this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.log.debug("setting request header: Content-length");
		this.req.setRequestHeader("Content-length", this.body.length);
		
		/*
		if(window.asyncstyle != 'html')
		{
			//alert("dojo-ajax-request");
			this.req.setRequestHeader("dojo-ajax-request", "true");	
		}
		window.asyncstyle = null;
		*/
		
		//this.log.debug("setting request header: Connection");
		//this.req.setRequestHeader("Connection", "close");
		this.log.debug("request headers for POST request set");
	}
	
	// branch for IE/Windows ActiveX version
	/*if (window.ActiveXObject) {
		this.log.debug("setting request headers for Internet Explorer (disable caching)");
		this.req.setrequestheader("Pragma","no-cache");
		this.req.setrequestheader("Cache-control","no-cache");
	}*/
	
    this.req.send(this.body);
    this.log.info("submit complete");
    
    // if not async call request must be complete here
    if(!this.async)
    {
    	this.log.info("syncronous call complete");
    	this.log.debug("response headers: " + this.req.getAllResponseHeaders());
    	if(this.onComplete)
    	{
    		this.log.info("calling onComplete callback method");
    		this.onComplete(this.req.responseText, this.req.responseXML);
    	}
    }
    
}
	
// call this function to abort current request
XMLRPCProvider.prototype.abort = function(){
	this.log.info("abort: " + this.url);
		
	if (!this.internalIsBusy()) {
		this.log.error("abort: error - no request submitted");			
	}
	
	this.onComplete = null;		
	this.req.abort();
}	

// call this function to find out current url
XMLRPCProvider.prototype.getUrl = function(){
	return this.url;
}
	
// call this function to find out HTTP status code after response completes
XMLRPCProvider.prototype.getStatus = function(){
	return this.status;
}

// user can overrise this; this function is called when ready state of request changes
XMLRPCProvider.prototype.onProgress = function(progressState)
{

}
	
// user can override this;  this function is called when response is received without errors
XMLRPCProvider.prototype.onComplete = function(responseText, responseXML){

}



