// JavaScript Document
	function getNewOrders(){
		var url = Address.dynamic("/AJAXSupport/orders/");
		var response = HTTPRequest.get(url);
		return parseInt(response.text);
	}
	function changeUserStatus(uid){
		var url = Address.dynamic("/users/?action=status&id="+uid+"&status=#userStatus"+uid+"#");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
		}
		return false;
	}
	
	function handleCommentStatusChange(id){
		var url = Address.dynamic("/comments/?action=status&id="+id+"&status=#statusCombo"+id+"#");
		//alert(url);
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
		}
		return false;
	}
	
	function handleVote(id, rating){
		var url = Address.dynamic("/AJAXSupport/vote/?id=" + id + "&rating="+rating);
		//alert(url);
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		alert(root.firstChild.nodeValue);
		return false;
	}
	
	function changeOrderStatus(oid){
		var url = Address.dynamic("/orders/?action=status&id="+oid+"&status=#orderStatus"+oid+"#");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false
		}
		return true;
	}
	
	function submitFeedback(form){
		var url = Address.dynamic("/contact/?step=save&name=#nume#&mail=#mail#&message=#mesaj#&spam=#feedbackCaptcha#");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
		}else{
			alert(root.firstChild.nodeValue);
			HTMLForm.clearForm(form)
		}
		return false;
	}

	String.prototype.amp = function(){
		return this.replace("&", "&amp;");
	}
	String.prototype.unamp = function(){
		return this.replace("&amp;", "&");
	}
	
	function WCryptoText(text){
	}
	WCryptoText.initAll = function(){
		WUtility.traverse(
			document.body,
			function(node){
					if(node.nodeType == 1 && node.className == "WCryptoText"){
						node.innerHTML = Base64.decode(node.innerHTML);
						Show(node);
					}
			}
		);
	}
	
	var Base64 = {
	 
		// private property
		_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	 
		// public method for encoding
		encode : function (input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
	 
			input = Base64._utf8_encode(input);
	 
			while (i < input.length) {
	 
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
	 
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
	 
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
	 
				output = output +
				this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
				this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
	 
			}
	 
			return output;
		},
	 
		// public method for decoding
		decode : function (input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
	 
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	 
			while (i < input.length) {
	 
				enc1 = this._keyStr.indexOf(input.charAt(i++));
				enc2 = this._keyStr.indexOf(input.charAt(i++));
				enc3 = this._keyStr.indexOf(input.charAt(i++));
				enc4 = this._keyStr.indexOf(input.charAt(i++));
	 
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
	 
				output = output + String.fromCharCode(chr1);
	 
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
	 
			}
	 
			output = Base64._utf8_decode(output);
	 
			return output;
	 
		},
	 
		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		},
	 
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
	 
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
	 
			}
	 
			return string;
		}
	 
	}

	/** Opens a window of given w/h */
	function openWindow(url, width, height){
		var newWindow=window.open(url,"URL","toolbar=0,status=0,menubar=0,fullscreen=no,width=" + width + ",height=" + height + ",resizable=1");
		newWindow.focus();
		return newWindow;
	}

/** Utility function, gets element by ID */
	$ = function(id){
		return typeof(id) == "string" ? document.getElementById(id) : id;
	}
	
	/** Toggles visibility of an object. If you want cookie based visibility handling, see Visibility class */
	function tgl(target){
		if(Validator.isArray(target)){
			for(var i = 0; i<target.length; i++){
				//var target_obj = $(target[i]);
				//target_obj.style.display = ( target_obj.style.display == "none") ? "" : "none";
				Toggle(target[i]);
			}
		}else if(target!=null && target!=undefined){
			var target_obj = $(target);
			if(target_obj)
				target_obj.style.display = ( target_obj.style.display == "none") ? "" : "none";
		}
	}
		
	/** URL manipulation class. Static. */
	function Address(){
		throw 'RuntimeException: URL is a static utility class and may not be instantiated';
	}
	
	/** Replace current location */
	Address.replace = function(lnk, conf){
		conf = conf || false;
		if(conf !==false){
			if(confirm(conf))
				location.replace(Address.dynamic(lnk));
		}else{
			location.replace(Address.dynamic(lnk));
		}
		return false;
	}
	
	/** Matches all #field# like patterns and replaces them with field's value */
	Address.dynamic = function(lnk){
		var patt = /#(\w+)#/g, elementId, element, elementValue, i, result = lnk;
		while((fld = patt.exec(lnk))){
			elementId = fld[1];
			try{
				element = $(elementId);
				switch(element.type.toUpperCase()){
					case "CHECKBOX":
						elementValue = element.checked ? element.value : "";
					break;
					default:
						elementValue = escape(element.value);
					break;
				}
			}catch(e){
				elementValue = "";
			}
				result = result.replace(eval("/#"+elementId+"#/g"), elementValue);
		}
		return result;
	}
	
	/** Utility class for managing DOM elements*/
	function Element(){
		throw 'RuntimeException: Element is a static utility class and may not be instantiated';
	}
	
	/** Focus on an element */
	Element.focus = function(element){
		element = $(element);
		try{
			var readonly_orig = element.readOnly;
			var disabled_orig = element.disabled;
			element.readOnly = element.disabled = false;
			element.focus();
			element.readOnly = readonly_orig;
			element.disabled = disabled_orig;
		}catch(e){
		}
	}
	
	/** Calculate top-left offset and dimensions of an element */
	Element.getOffset = function(element, borders){
		var offsetObj = null;
		element = offsetObj = $(element);
		var offsetTop = 0, offsetLeft = 0
		while(offsetObj != null){ // we need to climb the DOM tree till we reach the root
			//Debug("Object: " + offsetObj.nodeName + ", top: " + offsetObj.offsetTop + ", left: " + offsetObj.offsetLeft)
			offsetTop += ((BrowserDetect.browser == "Explorer" && offsetObj.style.position=="RELATIVE") ? (offsetObj.offsetTop/2) : offsetObj.offsetTop); // add the offsets, except if IE, then add half to all relatively positioned
			offsetLeft += offsetObj.offsetLeft;
			if(borders){
				// IE has some problems if a node has a border and a padding set in the stylesheet
				// If both are set, only padding is taken into consideration, so compensate for that
				if(topBorder = parseInt(Element.getStyleAttribute(offsetObj, "borderTopWidth")))
					offsetTop += topBorder;
				if(leftBorder = parseInt(Element.getStyleAttribute(offsetObj, "borderLeftWidth")))
					offsetLeft += leftBorder;
			}
			offsetObj = offsetObj.offsetParent;
		};
		var scrollX = window.pageXOffset ? window.pageXOffset : (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		var scrollY = window.pageYOffset ? window.pageYOffset : (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
		return {top:offsetTop, left:offsetLeft, right:offsetLeft + element.offsetWidth, bottom:offsetTop + element.offsetHeight, width:element.offsetWidth, height:element.offsetHeight, scrollX:scrollX, scrollY:scrollY};
	}
	
	/** Pops up an element by another */
	Element.moveAt = function(element, at, position){
		var pos = Element.getOffset(at);
		WUtility.applyStyle(element, {"top":(pos.bottom + 10)+"px", "left":(pos.left)+"px"});
	}
	
	/** Checks whether element node is childnode of a node whose class is parentClass */
	Element.parentOfClass = function(element, parentClass){
		element = $(element);
		while(element != null){
			if(element.className == parentClass)
				return element
			element = element.parentNode;
		}
		return null;
	}
	/** effectively removes an element from the DOM. */
	Element.remove = function(element) {
		element.parentNode.removeChild(element);
	}
	/** Insert a new DOM node before node */
	
	Element.insertBefore = function(node, newNode){
		//document.body.insertBefore(newNode, node);
		node.parentNode.insertBefore(newNode, node);
		return newNode;
	}
	
	/** Insert a new DOM node after node */
	Element.insertAfter = function(node, newNode){
		document.body.insertBefore(newNode, node.nextSibling);
		return newNode;
	}
	
	/** Get computed/current style of an element */
	Element.getStyle = function(sender){
		var style = (sender.currentStyle) ? sender.currentStyle : (window.getComputedStyle ? window.getComputedStyle(sender, null) : false);
		return style;
	}
	
	/** Gets an attribute of computed/current style of the element */
	Element.getStyleAttribute = function(source, attributeName){
		var style = Element.getStyle(source);
		return style[attributeName];
	}
	
	/** Gets an attribute of the stylesheet of an element */
	Element.getCurrentStyleAttribute = function(source, attributeName){
		return source.style[attributeName];
	}
	
	/** Static class for handling cookies */
	function Cookie(){
		throw 'RuntimeException: Cookie is a static utility class and may not be instantiated';
	}
	/** Set a cookie */
	Cookie.set = function(cookieName, cookieValue, expires, path, domain, secure){
		var cookie = 	escape(cookieName) + '=' + escape(cookieValue)+
						(expires ? '; expires=' + expires.toGMTString() : '')+
						(path ? '; path=' + path : '')+
						(domain ? '; domain=' + domain : '')+
						(secure ? '; secure' : '');
		document.cookie = cookie;
	};
	/** Unset a cookie */
	Cookie.unset = function(cookieName){
		var now = new Date();
		var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
		Cookie.set(cookieName, '', yesterday);
	};
	/** Get cookie value */
	Cookie.get = function(cookieName){
		var cookieValue = '';
		var posName = document.cookie.indexOf(escape(cookieName) + '=');
		if (posName != -1){
			var posValue = posName + (escape(cookieName) + '=').length;
			var endPos = document.cookie.indexOf(';', posValue);
			if (endPos != -1) 
				cookieValue = unescape(document.cookie.substring(posValue, endPos));
			else 
				cookieValue = unescape(document.cookie.substring(posValue));
		}
		return (cookieValue);
	};
	
	/** Class to handle cookie-based visibility of elements */
	function Visibility(){
		throw 'RuntimeException: Visibility is a static utility class and may not be instantiated';
	}
	
	/**
	* Init the visibility, that is depending on cookie toggle element and element2's visibility
	* If cookie is true, element is visible and element2 is not, and vice versa
	* element and element2 can be arrays of elements
	*/
	Visibility.init = function(cookie, element, element2){
		if(Cookie.get(cookie)=="true"){
			Show(element);
			Hide(element2);
		}else{
			Hide(element);
			Show(element2);
		}
	}
	
	/** Set cookie and show element */
	Visibility.show = function(cookie, element){
		Cookie.set(cookie, true);
		Show(element);
	}
	
	/** Set cookie and hide element */
	Visibility.hide = function(cookie, element){
		Cookie.set(cookie, false);
		Hide(element);
	}
	
	/** Toggle element and negate cookie */
	Visibility.toggle = function(cookie, element){
		Toggle(element);
		Cookie.set(cookie, (Cookie.get(cookie)=="true"?"false":"true"));
	}
	
	
	/** Creates a functions wrapper for the original function so that it runs in the provided context. */
	function Delegate(f){
		this.func = f;
		createDelegate = function(obj){
			// Creates a functions wrapper for the original function so that it runs in the provided context.
			// obj: Context in which to run the function.
			return Delegate.create(obj, this.func);
		}	
	}
	Delegate.prototype = new Object();
	Delegate.create = function(scope, func){
		var f = function(){
			var target = arguments.callee.target;
			var func  = arguments.callee.func;
			return func.apply(target, arguments);
		};
		f.target = scope;
		f.func  = func;
		return f;
	}
	
	/** Toggles visibility of an object. If you want cookie based visibility handling, see Visibility class */
	function Toggle(target){
		if(Validator.isArray(target)){
			for(var i = 0; i<target.length; i++){
				//var target_obj = $(target[i]);
				//target_obj.style.display = ( target_obj.style.display == "none") ? "" : "none";
				Toggle(target[i]);
			}
		}else if(target!=null && target!=undefined){
			var target_obj = $(target);
			if(target_obj)
				target_obj.style.display = ( target_obj.style.display == "none") ? "" : "none";
		}
	}
	
	/** Hides an object. If you want cookie based visibility handling, see Visibility class */
	function Hide(target){
		if(Validator.isArray(target)){
			for(var i = 0; i<target.length; i++){
				//var target_obj = typeof(target[i]) == "string" ? $(target[i]) : target[i];
				//target_obj.style.display = "none";
				Hide(target[i]);
			}
		}else if(target!=null && target!=undefined){
			var target_obj = $(target);
			if(target_obj)
				target_obj.style.display = "none";
		}
	}
	
	/**  Shows an object. If you want cookie based visibility handling, see Visibility class */
	function Show(target){
		if(Validator.isArray(target)){
			for(var i = 0; i<target.length; i++){
				//var target_obj = typeof(target[i]) == "string" ? $(target[i]) : target[i];
				//target_obj.style.display = "";
				Show(target[i]);
			}
		}else if(target!=null && target!=undefined){
			var target_obj = $(target);
			if(target_obj)
				target_obj.style.display = "";
		}
	}
	
	function Validator(){}
	Validator.isArray = function(obj) {
	   try{
		   if (obj.constructor.toString().indexOf("Array") == -1)
			  return false;
		   else
			  return true;
	   }catch(e){
		   return false;
	   }
	}
	Validator.empty = function(value){
		if(typeof(value) == "number")
			return false;
		else
			return (value == null || value.match(/^s+$/) || value == "" || value == undefined);
	}
	Validator.range = function(value, min, max){
		var result = true;
		switch(typeof(value)){
			case "string":
				if((min && value.length<min) || (max && value.length>max)){
					result = false;
				}
			break;
			case "number":
				if(value<parseFloat(min) || value>parseFloat(max))
					result = false;
			break;
			default:
				if(value.toDateString){ // date object
					if((min && value<min) || (max && value>max)){
						result = false;
					}else{
						result = true;
					}
				}else{
					result = false;
				}
			break;
		}
		return result;
	}
	Validator.validate = function(value, against){
		if(against && !value.match(against)){
			return false;
		}else{
			return true;
		}
	}
	Validator.PATTERN_ALPHABETIC = /^[a-zA-Z]*$/;
	Validator.PATTERN_HASH = /^[a-zA-Z0-9]{32}$/;
	Validator.PATTERN_ALPHANUMERIC = /^[a-zA-Z0-9]*$/;
	Validator.PATTERN_NUMERIC = /^[0-9]*$/;
	Validator.PATTERN_TEXT = /^[^\$]*$/;
	Validator.PATTERN_MAIL = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	Validator.PATTERN_PHONE = /^\+?[0-9]{4,}-?[0-9]{6,}$/;
	Validator.PATTERN_DATE = /^([0-9]{4})\-([0-9]{2})\-([0-9]{2})( ([0-9]{2}):([0-9]{2}):([0-9]{2}))?$/;
	Validator.PATTERN_COORDINATE = /^-?[0-9]{1,3}\.[0-9]*$/;
	Validator.PATTERN_TAG = /(<([^>]+)>)/ig;
	
	/** Class to handle dynamic combos */
	function Combo(){
		throw 'RuntimeException: Combo is a static utility class and may not be instantiated';
	}
	
	/** Insert a combo item before another one */
	Combo.insertBefore = function(combo, num, newOpt){
		if(typeof(newOpt)!="object")
			return false;
		var combo = $(combo);
		if (num >= 0) {
			var oldOpt = combo.options[num];  
			try{
				combo.add(newOpt, oldOpt); // standards compliant; doesn't work in IE
			}catch(e){
			  combo.add(newOpt, num); // IE only
			}
		}
	}
	
	/** Insert a combo item after another one */
	Combo.insertAfter = function(combo, num, newOpt){
		if(typeof(newOpt)!="object")
			return false;
		var combo = $(combo);
		if (num >= 0) {
			var oldOpt = combo.options[num+1] || combo.options[num];  
			try{
				combo.add(newOpt, oldOpt); // standards compliant; doesn't work in IE
			}catch(e){
			  	combo.add(newOpt, num+1); // IE only
			}
		}
	}
	
	/** Removes a combo item */
	Combo.removeSelected = function(combo){
		var combo = $(combo);
		for(var i=combo.length-1; i>=0; i--)
			if (combo.options[i].selected)
				combo.remove(i);
	}
	
	/** Append a combo item */
	Combo.append = function(combo, newOpt){
		var combo = $(combo);
		try{
			combo.add(newOpt, null); // standards compliant; doesn't work in IE
		}catch(ex) {
			combo.add(newOpt); // IE only
		}
	}
	
	/** Unshift a combo item */
	Combo.removeLast = function(combo){
		var combo = $(combo);
		if (combo.length > 0)
			combo.remove(combo.length - 1);
	}
	
	/** Executes an async request to the server and notifies listeners on any change */
	function HTTPRequest(){
		EventDispatcher.call(this);
		try{
			this.__requestObject = new XMLHttpRequest(); // MOZ
		}catch(e){
			try{
				this.__requestObject = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
				alert("Your browser has no AJAX support.");
				return null;
			}
		}
		
		/** Internal, no need to be called */
		this.stateHandler = function(){
			switch(this.__requestObject.readyState){
				case 0:
					this.Dispatch(HTTPRequest.EVENT_UNINITIALIZE);
				break;
				case 1:
					this.Dispatch(HTTPRequest.EVENT_LOADING);
				break;
									   
				case 2:
					this.Dispatch(HTTPRequest.EVENT_LOADED);
				break;
							   
				case 3:
					this.Dispatch(HTTPRequest.EVENT_INTERACTIVE);
				break;
				case 4:
					try{
						var status = this.__requestObject.status;
					}catch(e){
						var status = 400;
					}
					var response = {xml:this.__requestObject.responseXML, text:this.__requestObject.responseText, status:status};
					if (status == 200){
						//this.response = response;
						//alert("Got response.");
						this.Dispatch(HTTPRequest.EVENT_SUCCESS, response);
					}else{
						this.Dispatch(HTTPRequest.EVENT_FAILURE, response);
					}
				break;
			}	
		}
		
		/** Initializes the request */
		this.InitializeRequest = function(method, uri){
			switch (arguments.length){
				case 2:
					this.__requestObject.open(method, uri);
				break;
				case 3:
					this.__requestObject.open(method, uri, arguments[2]);
				break;
			}
			if (arguments.length >= 4) 
				this.__requestObject.open(method, uri, arguments[2], arguments[3]);
			this.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		}
		
		/** Sets a header for the request */
		this.SetRequestHeader = function(field, value){
			this.__requestObject.setRequestHeader(field, value);
		}
		
		/** Commits the request */
		this.Commit = function(data){
			this.__requestObject.send(data)
		}
		
		/** Aborts the request */
		this.Abort = function(){
			this.__requestObject.abort();
		}
		this.getResponse = function(){
			return {xml:this.__requestObject.responseXML, text:this.__requestObject.responseText, status:this.__requestObject.status}
		}
		this.__requestObject.onreadystatechange = Delegate.create(this, this.stateHandler);
	}
	HTTPRequest.prototype = new EventDispatcher;
	HTTPRequest.DOM = function(url, element){
		var request = new HTTPRequest(); // create a request object
		request.InitializeRequest('POST', url); // initialize the request
		request.addEventObserver(this, HTTPRequest.EVENT_SUCCESS, function(response){	try{ $(element).innerHTML = response.text;}catch(e){}}); // listen to when the request finished
		request.addEventObserver(this, HTTPRequest.EVENT_FAILURE, function(response){	try{ $(element).innerHTML = "Request failed: " + response.status;}catch(e){}}); // listen to when the request finished
		request.Commit(null); // execute the request
	}
	HTTPRequest.get = function(url){
		var request = new HTTPRequest(); // create a request object
		request.InitializeRequest('POST', url, false); // initialize the request
		request.Commit(null); // execute the request
		return request.getResponse();
	}
	HTTPRequest.alert = function(url){
		if(url==undefined)
			return false;
		handleServerResponse = function(response){
			try{
				var root = response.xml.getElementsByTagName("response")[0];
				alert(root.firstChild.nodeValue);
			}catch(e){
				//alert("Serviciu indisponibil. Te rugam incearca mai tarziu.");
			}
		}
		var r = new HTTPRequest();
		r.InitializeRequest("GET", url);
		r.addEventObserver(this, HTTPRequest.EVENT_SUCCESS, handleServerResponse);
		r.Commit();
	}
	HTTPRequest.EVENT_SUCCESS = "ajaxEventSuccess";
	HTTPRequest.EVENT_FAILURE = "ajaxEventFailure";
	HTTPRequest.EVENT_UNINITIALIZE = "ajaxEventUninitialize";
	HTTPRequest.EVENT_LOADING = "ajaxEventLoading";
	HTTPRequest.EVENT_LOADED = "ajaxEventLoaded";
	HTTPRequest.EVENT_INTERACTIVE = "ajaxEventInteractive";

	
	
	/** Utility class for westend applications */
	function WUtility(){};

	/** Generates a random string using alphabet */
	WUtility.randomId = function(length, alphabet){
		// Generates a string of random characters made of elements of alphabet
		length = typeof(length) != 'undefined' ? length : 32;
		alphabet = typeof(alphabet) != 'undefined' ? alphabet : "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789";
		var result = "";
		for(var i=0; i<length; i++){
			result += alphabet.charAt(Math.round((alphabet.length-1)*Math.random()));
		}
		return result;
	}

	/** Traverse a subtree and call a function for each node */
	WUtility.traverse = function(node, callback, direction) {  
		node = $(node);
		direction = direction || -1;
		if(typeof(callback) != "function" || node == null)
			return;
		if(node.childNodes){
			if(direction==-1){ // traverse from last child to first, useful when deleting nodes
				for(var i = node.childNodes.length; i>0; i--){
					WUtility.traverse(node.childNodes[i-1], callback, direction); 
				}
			}else{
				for(var i = 0; i<node.childNodes.length; i++){ // traverse from first to last child, not working when deleting nodes
					WUtility.traverse(node.childNodes[i], callback, direction); 
				}
			}
		}
		callback(node);
	}
	
	/** Traverse a subtree and remove all empty text nodes */
	WUtility.cleanEmptyTextNodes = function(node){
		node = (typeof(node) == "object") ? node : $(node);
		WUtility.traverse(
			node,
			function(node){
				//try{
					//Debug("Node value = " + (node.nodeValue == null))
					if(node.nodeType == 3 && (/^[\n\r\t ]*$/.test(node.nodeValue) || (node.nodeValue==null))){
						//Debug("Empty node: " + (/^[\n\r\t ]*$/.test(node.nodeValue)) + ", value = " + node.nodeValue);
						Element.remove(node);
					}
					//else{
						//Debug("Skipping. type = " + node.nodeType);
					//}
				//}catch(e){
					//Debug("exception");
				//}
			}
		);
	}
	
	WUtility.createElement = function(type, attributes, style){
		// Creates an element and applies attributes and style to it
		var element = document.createElement(type);
		/*if(type.toUpperCase() == "IMG" && BrowserDetect.browser == "Explorer" && BrowserDetect.version<7){ // if user agent is IE uses alphaimageloader filter to load the image
			element.onload = function(){
				if(this.src.match(/\.png/i)){ // if it's a png
					this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='')"; // overlay a filtered image
					this.src = "/imagini/sleeper.gif"; // and replace original image with a blank
				}
				this.onload = function(){}; // clear onload
			}
		}*/
		WUtility.applyAttributes(element, attributes);
		WUtility.applyStyle(element, style);
		return element;
	}
	
	/** Apply a set of attributes to an element. */
	WUtility.applyAttributes = function(element, attributes){
		// Apply a set of attributes to an element. This function is browser-aware.
		if(typeof(attributes) != "object" || !element.setAttribute)
			return false;
		for(var i in attributes){
			if(element[i]){
				element.setAttribute(i, attributes[i]);
			}else{
				var a = document.createAttribute(i);
				a.nodeValue = attributes[i];
				element.setAttributeNode(a);
			}
		}
	}
	
	/** Apply a set of styles to an element */
	WUtility.applyStyle = function(element, style){
		// apply a set of CSS styles to an element.
		element = $(element);
		if(typeof(style) != "object" || typeof(element)!="object")
			return false;
		for(var i in style){
			element.style[i] = style[i];
		}
	}


/** class that manages browser events */
	function Event(){
		throw 'RuntimeException: Event is a static utility class and may not be instantiated';
	};
	
	/** Add observer for event. Captures = ?? */
	Event.observe = function(target, type, callback, captures) {
		// add an event handler to a target DOM element
		var result = true;
		if (target.addEventListener) { // if gecko
			target.addEventListener(type, callback, captures);
		} else if (target.attachEvent) { // if ie
			result = target.attachEvent('on' + type, callback, captures);
		} else { // IE 5 Mac and some others
			target['on'+type] = callback;
		}
		return result;
	}
	
	/**
	* Try to get the target of the event
	* from: the element the mouse left, to: the element the mouse moved over
	*/
	Event.target = function(e){
		return {from:(e.target || e.fromElement || null), to:(e.currentTarget || e.toElement || null)};
	}
	
	/** Get the mouse coordinates in the moment the event was triggered */
	Event.mouse = function(e){
		if (e.pageX || e.pageY){ // gecko
			var x = e.pageX || 0;
			var y = e.pageY || 0;
			ret = new Point(x, y);
		}else if (e.clientX || e.clientY){ // ie
			var x = e.clientX || 0;
			var y = e.clientY || 0;
			//Debug("Client: " + e.clientX + ", " + e.clientY + ", scroll: " + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft) + ", " + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) );
			// add the amount the page is scrolled in eighter direction (IE)
			ret = new Point(
					(x - 1 + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)) || 0,
					(y - 1 + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)) || 0
			)
		}else{
			ret = new Point(0, 0);
		}
		ret.x = (ret.x<0) ? 0 : ret.x; // correct coordinates in case the mouse moved out of the window area
		ret.y = (ret.y<0) ? 0 : ret.y;
		return ret;
	}

/* end of class */

	/** A basic object */
	function CoreObject() {
		var instanceDescription = "";
		this.setClassDescription = function(description){
			this.instanceDescription = description;
		}
		this.setClassDescription('Westend.CoreObject');
		CoreObject.prototype.toString = function(){
			return '[' + this.instanceDescription + ']';
		}
	}
	CoreObject.className = "CoreObject";
	
	/** Base class capable of dispatching custom events */
	function EventDispatcher(){
		CoreObject.call(this);
		this.eventMap = new Array();
		this.setClassDescription('Westend.EventDispatcher');
		
		/** Add an observer for an event */
		this.addEventObserver = function(scope, eventName, eventHandler){
			//alert(eventName);
			if(typeof(eventHandler) != 'function' && typeof(scope[eventHandler]) != 'function')
				return false;
			var eventList = this.eventMap[eventName];
			if (eventList == undefined)
				this.eventMap[eventName] = new Array();
			else{
				var len = eventList.length;
				while (len--)
					if (eventList[len].scope == scope && eventList[len].funct == eventHandler)
						return false;
			}
			var event = new Object();
			event.scope      = scope;
			event.funct      = typeof(eventHandler) == "function" ? eventHandler : scope[eventHandler];
			this.eventMap[eventName].push(event);
			return true;
		}
		
		/** Dispatch a custom event */
		this.Dispatch = function(eventName){
			//alert("EventDispatcher(" + eventName + ")");
			var args = arguments;
			var eventList = this.eventMap[eventName];
			//alert(eventName.length);
			if (eventList == undefined)
				return false;
			var i = -1;
			while (++i < eventList.length){
				eventList[i].funct.apply(eventList[i].scope, Array.prototype.slice.call(arguments, 1));
			}
			return true;
		}
		
		/** Remove an observer identified with scope, name and handler */
		this.removeEventObserver = function(scope, eventName, eventHandler){
			var funct    	= (eventHandler == undefined) ? eventName : eventHandler;
			var eventList 	= this.eventMap[eventName];
			var len			= eventList.length;
			
			while (len--) {
				if (eventList[len].scope == scope && eventList[len].funct == funct) {
					eventList.splice(len, 1);
					
					if (eventList.length == 0)
						delete this.eventMap[eventName];
					return true;
				}
			}
			return false;
		}
		
		/** Remove all observers */
		this.removeAllEventObservers = function(){
			for (var i in this.eventMap) {
				this.eventMap[i].splice(0);
				delete this.eventMap[i];
			}
			
			this.eventMap = new Object();
			return true;
		}
		
		/** Remove all observers for a given event */
		this.removeEventObserversForEvent = function(eventName){
			if (this.eventMap[eventName] == undefined)
				return false;
			delete this.eventMap[eventName];
			return true;
		}
		
		/** Remove all observers for a given scope */
		this.removeEventObserversForScope = function(scope){
			var removed = false;
			for (var i in this.eventMap) {
				var eventList	= this.eventMap[i];
				var len			= eventList.length;
				while (len--) {
					if (eventList[len].scope == scope) {
						this.$eventMap[i].splice(len, 1);
						if (eventList.length == 0)
							delete this.$eventMap[i];
						removed = true;
					}
				}
			}
			return removed;
		}
	}
	EventDispatcher.prototype = new CoreObject;



function WTree(id, options){
	this.element = id;
	options = options == undefined ? {} : options;
	this.options = options;
	this.options.prefix = options.prefix || "";
	if(options.fskin)
		this.options.skin = options.fskin;
	else
		this.options.skin = this.options.prefix + "/img/wtree/" + (this.options.skin || "city") + "/";
	this.options.cookie = "wtree_"+id;
	WTree.INSTANCES.push(this);
}
WTree.prototype.init = function(){
	if((this.element = $(this.element))==undefined) return false;
	WUtility.cleanEmptyTextNodes(this.element);
	//alert("Nodes cleaned");
	WUtility.traverse(this.element, Delegate.create(this, WTree.initNode));
	if(this.options.cookie){
		var map =  Cookie.get(this.options.cookie);
		WTree.setMap(this.element, map);
	}
	Show(this.element);
}
WTree.prototype.hasSubMenus = function(element){
	var has = false;
	for(var i=0; i<element.childNodes.length; i++){
		if(element.childNodes[i].nodeName == "DIV"){
			has = true;
			break;
		}
	}
	return has;
}
WTree.prototype.toggle = function(element){
	element.className = (element.className == WTree.CLASS_CLOSED) ? WTree.CLASS_OPEN : WTree.CLASS_CLOSED;
	element.firstChild.firstChild.src = element.backingObject.options.skin + (element.firstChild.firstChild.src.search(WTree.IMAGE_CLOSED)>-1 ? WTree.IMAGE_OPEN : WTree.IMAGE_CLOSED);
}
WTree.prototype.collapseAll = function(){
	WUtility.traverse(this.element, Delegate.create(this, WTree.collapse));
}
WTree.getMap = function(root){
	var map = (root.className == WTree.CLASS_OPEN) ? "1" : (root.className == WTree.CLASS_CLOSED ? "0" : "");
	if(root.backingObject.hasSubMenus(root)){
		for(var i=0; i<root.childNodes.length; i++){
			map += WTree.getMap(root.childNodes[i]);
		}
	}
	return map;
}
WTree.mapLength = function(root){
	var length = (root != root.backingObject.element && root.backingObject.hasSubMenus(root)) ? 1 : 0;
	if(root.backingObject.hasSubMenus(root)){
		for(var i=0; i<root.childNodes.length; i++){
			length += WTree.mapLength(root.childNodes[i]);
		}
	}
	return length;
}
WTree.setMap = function(root, map){
	var mapL = WTree.mapLength(root);
	if(map.length == mapL){
		function setMapRecursive(root, map){
			if(root != root.backingObject.element && root.backingObject.hasSubMenus(root)){
				var flag = parseInt(map.slice(0, 1));
				map = map.slice(1, map.length);
				switch(flag){
					case 0:
						if(root.className != WTree.CLASS_CLOSED)
							root.backingObject.toggle(root);
					break;
					case 1:
						if(root.className == WTree.CLASS_CLOSED)
							root.backingObject.toggle(root);
						else if(root.className == "")
							root.className = WTree.CLASS_OPEN;
					break;
				}
				root.className = parseInt(flag) ? WTree.CLASS_OPEN : WTree.CLASS_CLOSED;
			}
			if(root.backingObject.hasSubMenus(root)){
				for(var i=0; i<root.childNodes.length; i++){
					map = setMapRecursive(root.childNodes[i], map);
				}
			}
			return map;
		}
		setMapRecursive(root, map);
		return true;
	}else{
		Cookie.unset(root.backingObject.options.cookie);
		root.backingObject.collapseAll(root);
		return false;
	}
}
WTree.initNode = function(node){
	try{ node.backingObject = this;	}catch(e){}
	if(node.nodeName == "DIV" && node!=this.element){
		if(this.hasSubMenus(node)){
			var trigger = WUtility.createElement("A", {"class":WTree.CLASS_BULLET}, {"textDecoration":"none"});
			trigger.appendChild(WUtility.createElement("IMG", {"src":this.options.skin+(node.className==WTree.CLASS_CLOSED ? WTree.IMAGE_CLOSED : WTree.IMAGE_OPEN)}, {}));
			trigger.appendChild(document.createTextNode(" "));
			//trigger.appendChild(node.firstChild);
			Element.insertBefore(node.firstChild, trigger);
			//node.firstChild.appendChild
			//var n = Element.insertBefore(node.firstChild, WUtility.createElement("IMG", {"class":WTree.CLASS_BULLET, "src":this.options.skin+(node.className==WTree.CLASS_CLOSED ? WTree.IMAGE_CLOSED : WTree.IMAGE_OPEN)}, {})); // = "<img src='/director/imagini/directory/nolines_plus.gif' class='bullet' onclick='alert(this.backingObject)'>" + node.innerHTML;
			//n.backingObject = this;
			//n.onclick = function(){
			trigger.backingObject = this;
			trigger.onclick = function(){
				this.backingObject.toggle(this.parentNode);
				if(this.backingObject.options.cookie){
					var map = WTree.getMap(this.backingObject.element);
					Cookie.set(this.backingObject.options.cookie, map, null, "/", "");
				}

				//this.firstChild.src = this.backingObject.options.skin + (this.firstChild.src.search(WTree.IMAGE_CLOSED)>-1 ? WTree.IMAGE_OPEN : WTree.IMAGE_CLOSED);
			}
		}/*else{
			var n = Element.insertBefore(node.firstChild, WUtility.createElement("IMG", {"class":WTree.CLASS_BULLET, "src":this.options.skin+WTree.IMAGE_BLANK}, {})); // = "<img src='/director/imagini/directory/nolines_plus.gif' class='bullet' onclick='alert(this.backingObject)'>" + node.innerHTML;
		}*/
	}
}
WTree.collapse = function(node){
	if(this.hasSubMenus(node) && node != this.element){
		node.firstChild.onclick();
	}
}
WTree.INSTANCES = [];
WTree.CLASS_OPEN = "WTreeNodeOpen";
WTree.CLASS_CLOSED = "WTreeNodeClosed";
WTree.CLASS_BULLET = "WTreeBullet";
WTree.IMAGE_OPEN = "nolines_minus.gif";
WTree.IMAGE_CLOSED = "nolines_plus.gif";
WTree.IMAGE_BLANK = "empty.gif";
WTree.initAll = function(){
	for(var i=0; i<WTree.INSTANCES.length; i++){
		WTree.INSTANCES[i].init();
	}
}


	/*
	Create a link between two combos so that the child listens and acts on the events of the parent
	Combo chains can be created
	Multiple combos can be linked to the same parent
	*/
	function WLink(){
		throw 'RuntimeException: WLink is a static utility class and may not be instantiated';
	}
	WLink.create = function(child, parent, options){
		if(typeof(parent) == "number"){
			parent = {value:parent}
			if(!parent.addEventObserver)
				parent.prototype = EventDispatcher.call(parent);
			window.addOnLoadListener(parent, parent.Dispatch, WLink.EVENT_CHANGED, parent.value);
		}else{
			parent = $(parent);
			if(!parent.addEventObserver)
				parent.prototype = EventDispatcher.call(parent);
		}
		child = $(child);
		child.WLinkOptions = options;
		child.WLinkParent = parent;
		child.WLinkGet = function(id){
			//Debug("Add value to " + this.getAttribute("id"));
			this.WLinkClear();
			if(id !== "" && id !== "adauga"){
				if(child.WLinkOptions.get != undefined){
					get = sprintf(child.WLinkOptions.get, id) + "&r=" + Math.random();
					get = get.unamp();
					WLink.fill(this, HTTPRequest.get(get));
					this.WLinkEnable(this.WLinkOptions.sel);
					delete this.WLinkOptions.sel;
				}
			}else{
				this.WLinkDisable();
			}
			try{
				this.Dispatch(WLink.EVENT_CHANGED, this.value);
			}catch(e){}
		}
		child.WLinkClear = function(){ // clears all the options but the default and the one that facilitates new option additons
			var i = 0;
			while(i < this.options.length){
				if(this.options[i].value!="" && this.options[i].value!="adauga" && this.options[i].value!="modifica" && this.options[i].value!="sterge"){
					this.remove(i);
				}else{
					i++;
				}
			}
		}
		child.WLinkEnable = function(selected){ // enables the combo
			this.disabled=false;
			this.value= selected || "";
			//Debug("Selecting " + this.getAttribute("id") + "." + selected);
		}
		child.WLinkDisable = function(){ // disables the combo
			this.disabled=true;
			this.value="";
			//this.Clear();
		}
		child.onchange = function(){
			//Debug("Child onchange " + this.value );
			if(this.value === "adauga"){
				if(this.WLinkOptions.add != undefined){
					this.value = "";
					try{
						url = sprintf(this.WLinkOptions.add, this.WLinkParent.value);
						//alert("url = " + url);
						url = url.unamp();
						var newWnd = openWindow(url, 350, 350);
						var interval = setInterval(Delegate.create(this, function(){ // detect window closure, on close refresh the combo
							if(newWnd.closed){
								clearInterval(interval);
								this.WLinkGet(this.WLinkParent.value);
								this.value = "";
								//alert("refresh");
							}
						}), 10);
					}catch(e){
						alert("Unable to access interface.\nMake sure popups are allowed on this site.");
					}
				}
			}else if(this.value === "modifica"){
				if(this.WLinkOptions.edit != undefined){
					this.value = "";
					try{
						url = this.WLinkOptions.edit;
						//alert("url = " + url);
						url = url.unamp();
						var newWnd = openWindow(url, 350, 350);
						var interval = setInterval(Delegate.create(this, function(){ // detect window closure, on close refresh the combo
							if(newWnd.closed){
								clearInterval(interval);
								this.WLinkGet(this.WLinkParent.value);
								this.value = "";
								//alert("refresh");
							}
						}), 10);
					}catch(e){
						alert("Unable to access interface.\nMake sure popups are allowed on this site.");
					}
				}
			}else if(this.value === "sterge"){
				if(this.WLinkOptions.del != undefined){
					this.value = "";
					try{
						url = this.WLinkOptions.del;
						//alert("url = " + url);
						url = url.unamp();
						var newWnd = openWindow(url, 350, 350);
						var interval = setInterval(Delegate.create(this, function(){ // detect window closure, on close refresh the combo
							if(newWnd.closed){
								clearInterval(interval);
								this.WLinkGet(this.WLinkParent.value);
								this.value = "";
								//alert("refresh");
							}
						}), 10);
					}catch(e){
						alert("Unable to access interface.\nMake sure popups are allowed on this site.");
					}
				}
			}
			try{
				this.Dispatch(WLink.EVENT_CHANGED, this.value);
			}catch(e){}
		}
		parent.addEventObserver(child, WLink.EVENT_CHANGED, child.WLinkGet);
	}
	
	WLink.fill = function(combo, data){
		var root = data.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
		}else{
			var elements = root.getElementsByTagName("option"); //
			for(var i=0;i<elements.length;i++){ // fill the combo
				var new_option = new Option(elements[i].firstChild.nodeValue, elements[i].getAttribute("id")) // create the new element
				if(combo.options.length>0 && (combo.options[0].value=="")) // if there is an option for adding new values to the combo, it needs to be the last option
					if(combo.options.length==1)
						Combo.append(combo, new_option);
					else
						Combo.insertAfter(combo, 0, new_option); // so we insert the new value before it
				else // otherwise
					Combo.insertBefore(combo, 0, new_option); // just append to the end
			}
		}
		//alert(this.value)
	}
	WLink.EVENT_CHANGED = "WLink parent changed";
	
	
	/* Form related stuff */
	function HTMLForm(){
		throw 'RuntimeException: Form is a static utility class and may not be instantiated';
	}
	/* submit a form */
	HTMLForm.send = function(name){
		HTMLForm.get(name).submit();
	}
	/* Find and return a form identified by its name */
	HTMLForm.get = function(name){
		//alert(document.forms[name]);
		return (typeof(name)=="string") ? document.forms[name] : name;
	}

	/**
	* Validates a form's elements.
	* 	Parameters:
	*		form 		- the form to be validated
	*		callback	- the function to be called on completion. 
	*		submitOnComplete - submits on success
	*	The validation data for a form is stored in the formfields' "v" attribute in form of:
	*		REQUIRED,LABEL,TYPE,MIN,MAX where
	*		REQUIRED 	= Y|N - if required, an empty value will generate an error, if not required, only an invalid value will generate an error
	*		LABEL		= the label of the form element, used for error reporting
	*		TYPE		= NUMERIC|ALPHABETIC|ALPHANUMERIC|TEXT|MAIL|DATE - determines the method of validation
	*		MIN			= the minimum value or length of the field (value if numeric, length if string type. Optional.
	*		MAX			= the maximum value or length of the field. Optional.
	*	Usage:
	*		<input type="button" ... onclick="Form.validate(this, callback)" /> - use it like this on a button as a submit button
	*		<input type="text" name="field1" v="Y;The first field;NUMERIC;2;10" /> - this field will pass validation if value is a numeric value between 2 and 10.
	*	Note:
	*		Client side validation is not enough, server side validation is always required. Client side validation is only good for providing instant feedback in style for the user without wasting any time to send the data and get an error message afterwards.
	*	
	*	Created:
	*		2007-10-21 Deezahke weezahke
	*/
	HTMLForm.validate = function(frm, callback, submitOnComplete){
		frm = HTMLForm.get(frm);
		submitOnComplete = submitOnComplete || true;
		//var frm = document.forms[frm];
		var errors = [], radios = [];
		//var th = new templateHandler("<b>{ELEMENT}</b>: {STATUS}");
		for(var i=0; i<frm.elements.length; i++){
			var element = frm.elements[i], range = "", empty = false, status = "", eFocus = "", eFocusRel = "";
			if(element.type.toUpperCase()=="HIDDEN" && element.relatedField){
				//var relm = rel.match(/^([a-zA-Z0-9_]+)\[([a-zA-Z0-9_]+)\]/);
				eFocusRel = ".relatedField";
				element = element.relatedField//HTMLForm.get(relm[1]).elements[relm[2]];
			}
			try{
				var v = element.getAttribute("v").split(";");
				//alert(v);
				v[0] = v[0].toUpperCase();
				v[3] = v[3];
				v[4] = v[4];
				//alert(element.name + ", " + element.type.toUpperCase() + ", " + v[2]);
				switch(element.type.toUpperCase()){
					case "HIDDEN":
						/*if(element.getAttribute && (rel = element.getAttribute("rel"))){
							alert("hidden[" + element.name + "]");
							var relm = rel.match(/^([a-zA-Z0-9_]+)\[([a-zA-Z0-9_]+)\]/);
							element = HTMLForm.get(relm[1]).elements[relm[2]];
							var v = element.getAttribute("v").split(";");
							v[0] = v[0].toUpperCase();
							v[3] = v[3];
							v[4] = v[4];
						}*/
					case "PASSWORD":
					case "TEXT": // textbox
					case "TEXTAREA":
						try{
							var oEditor = FCKeditorAPI.GetInstance(element.name) ;
							//alert(oEditor.Focus);
							var oDOM = oEditor.EditorDocument ;
							var iText;
							if ( document.all ){ // If Internet Explorer.
								iText = oDOM.body.innerText;
							}else{					// If Gecko.
								var r = oDOM.createRange() ;
								r.selectNodeContents( oDOM.body ) ;
								iText = r.toString();
							}
							eFocus = "<a onclick=\"FCKeditorAPI.GetInstance('"+element.name+"').Focus()\">"+v[1]+"</a>";
						}catch(e){
							iText = element.value;
							eFocus = "<a onclick=\"Element.focus(HTMLForm.get('"+frm.name+"').elements["+i+"]"+eFocusRel+")\">"+v[1]+"</a>";
						}
						empty = (iText.length == 0);
						//alert("empty = " + empty + ", name = " + element.name);
						//alert("hidden " + element.name);
						if(empty){
							if(v[0]=="Y"){
								status = "necompletat(a).";
							}
						}else{
							//alert("not empty, " + v + ", name = " + element.name);
							switch(v[2].toUpperCase()){
								case "NUMERIC":
									if(isNaN(iText)){
										status = "numar invalid."
									}else if(!Validator.range(parseFloat(iText), v[3], v[4])){
										if(v[3] && v[4]){
											if(v[3]==v[4]){
												status += ("Numarul trebuie sa fie exact " + v[3] + ".");
											}else{
												status += ("Numarul trebuie sa fie intre " + v[3] + " si " + v[4] + ".");
											}
										}else{
											if(v[3]){
												status += "Numarul trebuie sa fie mai mare de " + v[3] + ".";
											}else if(v[4]){
												status += "Numarul trebuie sa fie mai mic de " + v[4] + ".";
											}
											
										}
									}
								break;
								case "ALPHABETIC":
									if(!Validator.validate(iText, Validator.PATTERN_ALPHABETIC)){
										status = "text invalid. Caractere acceptate a-z, A-Z.";
									}else if(!Validator.range(iText, v[3], v[4])){
										if(v[3] && v[4]){
											if(v[3]==v[4]){
												status += ("lungimea textului trebuie sa fie exact " + v[3] + ".");
											}else{
												status += ("lungimea textului trebuie sa fie intre " + v[3] + " si " + v[4] + ".");
											}
										}else{
											if(v[3]){
												status += "textul trebuie sa fie mai lung de " + v[3] + ".";
											}else if(v[4]){
												status += "textul trebuie sa fie mai scurt de " + v[4] + ".";
											}
											
										}
									}
								break;
								case "ALPHANUMERIC":
									if(!Validator.validate(iText, Validator.PATTERN_ALPHANUMERIC)){
										status = "text invalid. Caractere acceptate a-z, A-Z, 0-9.";
									}else if(!Validator.range(iText, v[3], v[4])){
										if(v[3] && v[4]){
											if(v[3]==v[4]){
												status += ("lungimea textului trebuie sa fie exact " + v[3] + ".");
											}else{
												status += ("lungimea textului trebuie sa fie intre " + v[3] + " si " + v[4] + ".");
											}
										}else{
											if(v[3]){
												status += "textul trebuie sa fie mai lung de " + v[3] + ".";
											}else if(v[4]){
												status += "textul trebuie sa fie mai scurt de " + v[4] + ".";
											}
											
										}
									}
								break;
								default:
								case "TEXT":
									if(!Validator.validate(iText, Validator.PATTERN_TEXT)){
										status = "text invalid. Caractere neacceptate $.";
									}else if(!Validator.range(iText, v[3], v[4])){
										if(v[3] && v[4]){
											if(v[3]==v[4]){
												status += ("lungimea textului trebuie sa fie exact " + v[3] + ".");
											}else{
												status += ("lungimea textului trebuie sa fie intre " + v[3] + " si " + v[4] + ".");
											}
										}else{
											if(v[3]){
												status += "textul trebuie sa fie mai lung de " + v[3] + ".";
											}else if(v[4]){
												status += "textul trebuie sa fie mai scurt de " + v[4] + ".";
											}
											
										}
									}
								break;
								case "MAIL":
									if(!Validator.validate(iText, Validator.PATTERN_MAIL)){
										status = "adresa e-mail invalida.";
									}
								break;
								case "HASH":
									if(!Validator.validate(iText, Validator.PATTERN_HASH)){
										status = "invalid.";
									}
								break;
								case "PHONE":
									if(!Validator.validate(iText, Validator.PATTERN_PHONE)){
										status = "numar telefon invalid. Exemple: +40745-123456, 0040745-123456, 0745-123456, 0745123456.";
									}
								break;
								case "DATE":
									if(!DateTime.parse(iText)){
										status = "data invalida. Exemple: " + DateTime.format("{DATE}") + " sau " + DateTime.format("{DATETIME}") + ".";
									}else if(!Validator.range(DateTime.parse(iText), DateTime.parse(v[3]), DateTime.parse(v[4]))){
										if(v[3] && v[4]){
											if(v[3]==v[4]){
												status += ("Data trebuie sa fie exact " + v[3] + ".");
											}else{
												status += ("Data trebuie sa fie intre " + v[3] + " si " + v[4] + ".");
											}
										}else{
											if(v[3]){
												status += "Data trebuie sa fie pe sau dupa " + v[3] + ".";
											}else if(v[4]){
												status += "Data trebuie sa fie inainte sau pe " + v[4] + ".";
											}
										}
									}
								break;
							}
						}
					break;
					case "SELECT-ONE":
						if(v[0]=="Y" && Validator.empty(element.value)){
							status = "necompletat(a)."
						}
						eFocus = "<a onclick=\"Element.focus(HTMLForm.get('"+frm.name+"').elements["+i+"])\">"+v[1]+"</a>";
					break;
					case "RADIO": // leave radios out for now
						if(radios.seqSearch(element.name)==-1){
							radios.push(element.name);
							r = false;
							if(frm[element.name].length == undefined){
								r = frm[element.name].checked;
							}else{
								for(var j=0; j<frm[element.name].length; j++){
									if(frm[element.name][j].checked){
										r = true;
										break;
									}
								}
							}
						}else{
							r = true;
						}
						if(v[0]=="Y" && !r){
							status = "neselectat(a).";
						}
						eFocus = "<a onclick=\"Element.focus(HTMLForm.get('"+frm.name+"').elements["+i+"])\">"+v[1]+"</a>";
					break;
					case "CHECKBOX":
						if(v[0]=="Y" && !element.checked){
							status = "nebifat(a).";
						}
						eFocus = "<a onclick=\"Element.focus(HTMLForm.get('"+frm.name+"').elements["+i+"])\">"+v[1]+"</a>";
					break;
					default: // skip any other
						status = "";
					break;
				}
				if(status!=""){
					errors.push(
						"<b>"+eFocus+"</b>: "+status
						/*templateHandler.cleanup(th.evaluate({
							ELEMENT:	eFocus, 
							STATUS:		status
						}))*/
					);
				}
			}catch(e){}
		}
		if(errors.length){
			//errors.push("<br />* Click pentru a merge la campul respectiv.");
			if(typeof(callback)=="function")
				callback(errors.join("<br />"));
			else
				alert(errors.join("\n").replace(Validator.PATTERN_TAG, ""));
			return false;
		}else{
			if(submitOnComplete)
				frm.submit();
			return true;
		}
	}
	
	/** Clear a form element */
	HTMLForm.clearElement = function(element, def){
		def = def == undefined ? "" : def;
		element = $(element);
		if(element.type){
			switch(element.type.toUpperCase()){
				case "HIDDEN": // special case, FCK editors fall in this category
					if(window.FCKeditorAPI){
						var oEditor = FCKeditorAPI.GetInstance(element.name) ;
						if(oEditor!=undefined){// try for FCK editor
							if ( document.all ){ // If Internet Explorer.
								oEditor.EditorDocument.body.innerText = "";
							}else{				// If Gecko.
								oEditor.EditorDocument.body.innerHTML = "";
							}
						}
					}
					// do nothing if it is a standard hidden field
				break;
				case "CHECKBOX":
					element.checked = false;
				break;
				case "PASSWORD":
				case "TEXT": // textbox
				case "TEXTAREA":
				case "SELECT-ONE":
					element.value = def;
					if(element.onchange){
						element.onchange();
					}
				break;
			}
		}
	}
	/** Traverses a form and clears it's elements */
	HTMLForm.clearForm = function(formIdent) { 
		var form, elements, i, elm; 
		form = typeof(formIdent) == "object" ? formIdent : document.forms[formIdent];
		elements = form.elements;
		for(i=0, elm; elm=elements[i++]; ){
			HTMLForm.clearElement(elm);
		}
	}
	
	
	/** Sends a form asynchronously via a dinamically created iframe and calls a callback function on completion. Methods are all static. */
	function asyncUpload(){
		throw 'RuntimeException: asyncUpload is a static utility class and may not be instantiated';
	}
	/* Submit upload */
	asyncUpload.submit = function(form, onComplete){
		var name = WUtility.randomId(8); // generate a random id for the frame
		var div = WUtility.createElement('DIV', {}, {position:"absolute", top:"-9999px", left:"-9999px"}); // create a container for the frame, this whole operation works in IE only if div and iframe are created like this
		//div.innerHTML = '<iframe style="display:none" src="about:blank" id="'+name+'" name="'+name+'" onload="asyncUpload.loaded(\''+name+'\')"></iframe>' // create the frame
		div.innerHTML = '<iframe style="display:none" src="about:blank" id="'+name+'" name="'+name+'" onload="asyncUpload.loaded(this)"></iframe>' // create the frame
		document.body.appendChild(div); // append the container to the document
		var frame = $(name);
		if(typeof(onComplete) == 'function')
			frame.onComplete = onComplete;
		frame.form = form;
		form.setAttribute("target", name);
		return true;
	}
	
	/* Handle response */
	asyncUpload.loaded = function(frame){
		if(frame.contentDocument) {
			var d = frame.contentDocument; // get the frame's document to read out the response
		}else if(frame.contentWindow) {
			var d = frame.contentWindow.document;
		}else{
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") // onload is triggered when the frame is created, so do nothing on creation
			return;
		if(typeof(frame.onComplete) == 'function')
			frame.onComplete(d, frame.form);
		else
			alert("Response: " + d.body.innerHTML);
	}
	
	/**
	* Interface for async uploads
	* To use this class you need the upload.tpl PHP template
	* options must contain an id parameter, which is the upload session id.
	* In php, simpy call asyncUpload::getHTML() to get an interface
	*/
	function uploadInterface(options){
		EventDispatcher.call(this);
		this.options = options;
		uploadInterface.INSTANCES.push(this);
	}
	uploadInterface.prototype = new EventDispatcher;
	
	/** Init the interface */
	uploadInterface.prototype.init = function(){
		this.container = $("attachments_"+this.options.id);
		WUtility.traverse(this.container, Delegate.create(this, function(node){
			if(node.className == uploadInterface.CLASS_BASKET)
				this.basket = node;
			else if(node.className == uploadInterface.CLASS_FORM)
				this.form = node;
			else if(node.className == uploadInterface.CLASS_CONSOLE)
				this.console = node;
		}));
		this.form.appendChild(WUtility.createElement("INPUT", {type:"hidden", name:"v", value:this.options.id}))
		if(!this.options.debug)
			this.form.onsubmit = uploadInterface.submit;
		this.form.backingObject = this.container.backingObject = this;
		this.populate();
	}
	/** Populate the interface with a server call */
	uploadInterface.prototype.populate = function(){
		var updateBasket = function(response){
			response = response.xml.getElementsByTagName("response")[0];
			this.basket.innerHTML = response.text || response.textContent;
			/*if(BrowserDetect.browser == "Explorer" && BrowserDetect.version<7){
				pngfix(this.basket);
			}*/
			for(var node = this.basket.firstChild; node; node = node.nextSibling){
				node.backingObject = this;
				node.removeAttachment = function(){
					var file = this.getAttribute("attachmentname");
					var request = new HTTPRequest();
					request.InitializeRequest("GET", "/AJAXSupport/upload.php?v="+this.backingObject.options.id+"&a=remove&file=" + file);
					var remove = function(response){
						var root = response.xml.getElementsByTagName("response")[0];
						if(root.getAttribute("result").toUpperCase()=="SUCCESS"){
							this.backingObject.populate();
						}else{
							alert("Operatiune esuata. [" + response.text + "]");
						}
					}
					request.addEventObserver(this, HTTPRequest.EVENT_SUCCESS, remove);
					request.Commit();
					//alert(this.getAttribute("attachmentName"));
				}
			}
		}
		var request = new HTTPRequest();
		request.InitializeRequest("GET", "/AJAXSupport/upload.php?v="+this.options.id+"&a=queue");
		request.addEventObserver(this, HTTPRequest.EVENT_SUCCESS, updateBasket);
		request.addEventObserver(this, HTTPRequest.EVENT_SUCCESS, updateBasket);
		request.Commit();
	}
	/** Verify uploaded files with a server call */
	uploadInterface.prototype.queue = function(){
		var showQueue = function(response){
			response = response.xml.getElementsByTagName("response")[0];
			alert(response.firstChild.nodeValue);
		}
		var request = new HTTPRequest();
		request.InitializeRequest("GET", "/AJAXSupport/upload.php?v="+this.options.id+"&a=queue&m=plain");
		request.addEventObserver(this, HTTPRequest.EVENT_SUCCESS, showQueue);
		request.Commit();
	}
	/** submit the upload */
	uploadInterface.submit = function(){
		asyncUpload.submit(this, uploadInterface.handleResponse)
	}
	/** Handle server response */
	uploadInterface.handleResponse = function(response){
		response = response.XMLDocument ? response.XMLDocument : response // IE needs some special attention
		try{
			var root = response.getElementsByTagName("response")[0];
			if(root.getAttribute("result").toUpperCase()=="FAILURE"){
				alert(root.firstChild.nodeValue);
			}else{
				this.form.backingObject.populate();
			}
		}catch(e){
			alert("Operatiune esuata.\nTe rugam incearca mai tarziu sau daca problema persista, contacteaza Admin.")
		}
	}
	uploadInterface.INSTANCES = [];
	uploadInterface.CLASS_BASKET = "uploadBasket";
	uploadInterface.CLASS_FORM = "uploadForm";
	uploadInterface.CLASS_CONSOLE = "uploadConsole";
	uploadInterface.CLASS_EMPTY_BASKET = "basketEmptyMessage";
	uploadInterface.CLASS_BASKET_ELEMENT = "basketElement";


	/**
	* Execute a tween on a property of an object
	* Motion types are defined below
	* This class gives out events, depending on the state of the motion
	*/
	function Tween(obj, prop, func, begin, finish, duration, suffixe){
		EventDispatcher.call(this);
		if (!arguments.length)
			return;
		this.suffixe = suffixe;
		this.obj = $(obj);
		this.prop = prop;
		this.begin = this._pos = begin;
		//this.setDuration(duration);
		this._duration = (duration == null || duration <= 0) ? 100000 : duration;
		this.change = 0;
		this.prevTime = 0;
		this.prevPos = 0;
		this.looping = false;
		this._time = 0;
		//this._pos = 0;
		this._position = 0;
		this._startTime = 0;
		//this.name = '';
		this.func = (typeof(func)=='function') ? func : Tween.easeNone;
		//this.setFinish(finish);
		this.change = finish - this.begin;
	}
	Tween.prototype = new EventDispatcher;
	Tween.prototype.setTime = function(t){
		this.prevTime = this._time;
		if (t > this.getDuration()) {
			if (this.looping) {
				this.rewind (t - this._duration);
				this.update();
				this.Dispatch(Tween.EVENT_LOOPED,{tween:this,target:this.obj,type:Tween.EVENT_LOOPED});
			} else {
				this._time = this._duration;
				this.update();
				this.stop();
				this.Dispatch(Tween.EVENT_FINISHED,{tween:this,target:this.obj,type:Tween.EVENT_FINISHED});
			}
		} else if (t < 0) {
			this.rewind();
			this.update();
		} else {
			this._time = t;
			this.update();
		}
	}
	Tween.prototype.getTime = function(){
		return this._time;
	}
	Tween.prototype.setDuration = function(d){
		this._duration = (d == null || d <= 0) ? 100000 : d;
	}
	Tween.prototype.getDuration = function(){
		return this._duration;
	}
	Tween.prototype.setPosition = function(p){
		//Debug(p);
		this.prevPos = this._pos;
		if(typeof this.prop == "function"){
			this.prop(this.obj, p);
		}else{
			try{ // ie throws an error when some style elements are out of range, ie. width and height
				this.obj.style[this.prop] = p + this.suffixe;
			}catch(e){}
		}
		this._pos = p;
		this.Dispatch(Tween.EVENT_CHANGED,{tween:this,target:this.obj,type:Tween.EVENT_CHANGED, position:p});
	}
	Tween.prototype.getPosition = function(t){
		if (t == undefined) t = this._time;
		return this.func(t, this.begin, this.change, this._duration);
	};
	Tween.prototype.setFinish = function(f){
		this.change = f - this.begin;
	};
	Tween.prototype.getFinish = function(){
		return this.begin + this.change;
	}
	Tween.prototype.start = function(){
		this.rewind();
		this.startEnterFrame();
		this.Dispatch(Tween.EVENT_STARTED,{tween:this,target:this.obj,type:Tween.EVENT_STARTED});
	}
	Tween.prototype.rewind = function(t){
		this.stop();
		this._time = (t == undefined) ? 0 : t;
		this.fixTime();
		this.update();
	}
	Tween.prototype.fforward = function(){
		this._time = this._duration;
		this.fixTime();
		this.update();
	}
	Tween.prototype.update = function(){
		this.setPosition(this.getPosition(this._time));
	}
	Tween.prototype.startEnterFrame = function(){
		this.stopEnterFrame();
		this.isPlaying = true;
		this.onEnterFrame();
	}
	Tween.prototype.onEnterFrame = function(){
		if(this.isPlaying) {
			this.nextFrame();
			setTimeout(Delegate.create(this, this.onEnterFrame), 0);
		}
	}
	Tween.prototype.nextFrame = function(){
		this.setTime((this.getTimer() - this._startTime) / 1000);
	}
	Tween.prototype.stop = function(){
		this.stopEnterFrame();
		this.Dispatch(Tween.EVENT_STOPPED,{tween:this,target:this.obj,type:Tween.EVENT_STOPPED});
	}
	Tween.prototype.stopEnterFrame = function(){
		this.isPlaying = false;
	}
	
	Tween.prototype.continueTo = function(finish, duration){
		this.begin = this._pos;
		this.setFinish(finish);
		if (this._duration != undefined)
			this.setDuration(duration);
		this.start();
	}
	Tween.prototype.resume = function(){
		this.fixTime();
		this.startEnterFrame();
		this.Dispatch(Tween.EVENT_RESUMED,{tween:this,target:this.obj,type:Tween.EVENT_RESUMED});
	}
	Tween.prototype.yoyo = function (){
		this.continueTo(this.begin,this._time);
	}
	Tween.prototype.fixTime = function(){
		this._startTime = this.getTimer() - this._time * 1000;
	}
	Tween.prototype.getTimer = function(){
		return new Date().getTime() - this._time;
	}
	
	Tween.easeNone = function(t, b, c, d){
		return c*t/d + b; 
	};
	Tween.backEaseIn = function(t,b,c,d,a,p){
		if (s == undefined) var s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	}
	Tween.backEaseOut = function(t,b,c,d,a,p){
		if (s == undefined) var s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	}
	Tween.backEaseInOut = function(t,b,c,d,a,p){
		if (s == undefined) var s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	}
	Tween.elasticEaseIn = function(t,b,c,d,a,p){
		if (t==0) 
			return b;  
		if ((t/=d)==1) 
			return b+c;  
		if (!p) 
			p=d*.3;
		if (!a || a < Math.abs(c)) {
			a=c; 
			var s=p/4;
		}else 
			var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	}
	Tween.elasticEaseOut = function (t,b,c,d,a,p){
		if (t==0) 
			return b;
		if ((t/=d)==1) 
			return b+c;  
		if (!p) 
			p=d*.3;
		if (!a || a < Math.abs(c)) {
			a=c; 
			var s=p/4; 
		}else 
		var s = p/(2*Math.PI) * Math.asin (c/a);
		return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
	}
	Tween.elasticEaseInOut = function (t,b,c,d,a,p){
		if (t==0) 
			return b;  
		if ((t/=d/2)==2) 
			return b+c;  
		if (!p) 
			var p=d*(.3*1.5);
		if (!a || a < Math.abs(c)){
			var a=c; 
			var s=p/4;
		}else 
			var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) 
			return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	}
	Tween.bounceEaseOut = function(t,b,c,d){
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	}
	Tween.bounceEaseIn = function(t,b,c,d){
		return c - Tween.bounceEaseOut (d-t, 0, c, d) + b;
	}
	Tween.bounceEaseInOut = function(t,b,c,d){
		if (t < d/2) 
			return Tween.bounceEaseIn(t*2, 0, c, d) * .5 + b;
		else 
			return Tween.bounceEaseOut(t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
	Tween.strongEaseInOut = function(t,b,c,d){
		return c*(t/=d)*t*t*t*t + b;
	}
	Tween.regularEaseIn = function(t,b,c,d){
		return c*(t/=d)*t + b;
	}
	Tween.regularEaseOut = function(t,b,c,d){
		return -c *(t/=d)*(t-2) + b;
	}
	Tween.regularEaseInOut = function(t,b,c,d){
		if ((t/=d/2) < 1) return c/2*t*t + b;
			return -c/2 * ((--t)*(t-2) - 1) + b;
	}
	Tween.strongEaseIn = function(t,b,c,d){
		return c*(t/=d)*t*t*t*t + b;
	}
	Tween.strongEaseOut = function(t,b,c,d){
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	}
	Tween.strongEaseInOut = function(t,b,c,d){
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
			return c/2*((t-=2)*t*t*t*t + 2) + b;
	}
	Tween.alphaHandler = function(element, p){
		WUtility.applyStyle(element, {"opacity":p/100, "filter":"progid:DXImageTransform.Microsoft.Alpha(opacity=" + p + ")"});
	}
	Tween.EVENT_LOOPED = "onMotionLooped";
	Tween.EVENT_CHANGED = "onMotionChanged";
	Tween.EVENT_FINISHED = "onMotionFinished";
	Tween.EVENT_STARTED = "onMotionStarted";
	Tween.EVENT_STOPPED = "onMotionStopped";
	Tween.EVENT_RESUMED = "onMotionResumed";

	function WCarousel(id, options){
		this.element = $(id);
		this.items = [];
		this.maxH = 0;
		this.tweening = false;
		this.sInt = 0;
		this.options = options;
		this.options.tween = this.options.tween || 1;
		WCarousel.INSTANCES.push(this);
	}
	WCarousel.initAll = function(){
		//alert("initing wtabs")
		for(var i=0; i<WCarousel.INSTANCES.length; i++)
			WCarousel.INSTANCES[i].init();
	}
	WCarousel.prototype.init = function(){
		//alert("itt");
		WUtility.applyStyle(this.element, {"overflow":"hidden", "position":"relative"});
		//var c=0;
		WUtility.traverse(this.element, Delegate.create(this, function(node){
			if(node.className == "wcUp"){
				this.up = node;
				WUtility.applyStyle(this.up, {"position":"absolute", "top":"0px", "left":"0px", "zIndex":10, "cursor":"pointer"});
			}else if(node.className == "wcDown"){
				this.down = node;
				WUtility.applyStyle(node, {"position":"absolute", "bottom":"0px", "left":"0px", "zIndex":20, "cursor":"pointer"});
			}else if(node.className == "wcItem"){
				this.items.push(node);
				WUtility.applyStyle(node, {"position":"relative"});
				/*if(c%2)
					WUtility.applyStyle(node, {"backgroundColor":"#999999"});
				else
					WUtility.applyStyle(node, {"backgroundColor":"#CCCCCC"});
				c++;*/
				if(node.offsetHeight>this.maxH)
					this.maxH = node.offsetHeight;
			}else if(node.className == "wcItems"){
				this.container = node;
				WUtility.applyStyle(node, {"position":"relative", "top":"0px", "left":"0px", "zIndex":0});
			}
		}), 1);
		if(this.items.length<1)
			alert("Warning: no items in carousel.");
		this.up.onclick = Delegate.create(this, function(){
			this.pan(1);
			clearInterval(this.sInt);
		});
		this.down.onclick = Delegate.create(this, function(){
			this.pan(-1);
			clearInterval(this.sInt);
		});
		WUtility.applyStyle(this.element, {"height":Math.max(this.maxH+this.up.offsetHeight+this.down.offsetHeight, this.element.offsetHeight)+"px"}); // set carousel's height to the tallest item's height so it fits
		WUtility.applyStyle(this.container, {"top":"0px"});
		this.goTo(0);
		if(this.options.auto && this.container.offsetHeight > this.element.offsetHeight - this.up.offsetHeight - this.down.offsetHeight){
			this.sInt = setInterval(Delegate.create(this, this.pan), this.options.auto, -1);
		}
		
	}
	WCarousel.prototype.pan = function(direction){
		var topEl = this.topElement();
		if(direction>0){// lefele megy a cucc
			if(this.container.offsetTop<this.up.offsetHeight)
				this.goTo(topEl-1);
				
			else
				this.goBottom();
		}else{ //felfele megy a cucc
						if(this.container.offsetHeight + this.container.offsetTop>this.down.offsetTop)
				this.goTo(topEl+1);
			else
				this.goTop();
		}
	}
	WCarousel.prototype.topElement = function(){
		for(var i=0; i<this.items.length; i++){
			if(this.container.offsetTop == this.up.offsetHeight - this.items[i].offsetTop)
				return i;
		}
	}
	WCarousel.prototype.autoScrollDown = function(){
		this.pan(1);
	}
	WCarousel.prototype.goTo = function(index){
		if(!this.tweening){
			
			/*if(this.container.offsetHeight>this.element.offsetHeight - this.down.offsetHeight)*/
			
			//alert(sprintf("up.height=%d, index=%d, item[index].top=%d", this.up.offsetHeight, index, this.items[index].offsetTop));
			
			this.tweening = true;
			var t = new Tween(this.container, "top", Tween.strongEaseOut, this.container.offsetTop, this.up.offsetHeight-this.items[index].offsetTop, this.options.tween, "px");
			//alert(sprintf("Tween from %d to %d.",this.container.offsetTop, this.up.offsetHeight-this.items[index].offsetTop ));
			unlock = Delegate.create(this, function(){
				//alert("finished");
				this.tweening = false;
			});
			t.addEventObserver(this, Tween.EVENT_FINISHED, unlock);
			t.start();
		}
		//WUtility.applyStyle(this.container, {"top":(this.up.offsetHeight-this.items[index].offsetTop)+"px"});
	}
	WCarousel.prototype.goTop = function(){
		this.goTo(0);
	}
	WCarousel.prototype.goBottom = function(){
		var h = 0;
		for(var i=this.items.length-1; i>=0; i--){
			h += this.items[i].offsetHeight;
			if(h>this.element.offsetHeight){
				this.goTo(i+1);
				break;
			}
		}
	}
	WCarousel.INSTANCES = [];
	
	function WCart(id, options){
		options = options || {};
		options.currency = options.currency || WCart.messageDefaultCurrency;
		options.mode = options.mode || null;
		options.statusMessage = options.statusMessage || WCart.messageDefaultStatus;
		options.language_suffix = options.language_suffix || "";
		options.backendURL = options.backendURL || WCart.backendURL;
		options.emptyMessage = options.emptyMessage || WCart.messageDefaultEmpty;
		options.checkoutURL = options.checkoutURL || WCart.checkoutURL;
		options.showFooter = options.showFooter === false ? false : true;
		options.emptyURL = options.emptyURL;
		this.options = options;
		document.write(
			"<div id='"+id+"'>\
				" + (options.title ? "<h3 id='"+id+"Title'>"+ options.title +"</h3>" : "") + "\
				<p id='"+id+"Content' align='center'>"+(options.emptyMessage || "Cosul tau este gol")+"</p>\
				<p id='"+id+"Status' align='center'>&nbsp;</p>\
				" + (this.options.showFooter ? "<div id='"+id+"Footer' align='center'><a class='nowrap' onclick='this.backingObject.clearAll()'><img alt='New cart' src='/img/buttons/newcart"+options.languageSuffix+".png'></a> <a class='nowrap' onclick='this.backingObject.checkout()'><img alt='Checkout' src='/img/buttons/checkout"+options.languageSuffix+".png'></a></div>" : "") + "\
			</div>\
			"
		);
		this.element = $(id);
		this.content = $(id+"Content");
		this.status = $(id+"Status");
		this.options = options;
		this.cartStatus = {count:0, value:0};
		this.inited = false;
		this.setBackingObject();
		WCart.INSTANCES.push(this);
		return this;
	}
	WCart.initAll = function(){
		//alert("initing wtabs")
		for(var i=0; i<WCart.INSTANCES.length; i++)
			WCart.INSTANCES[i].init();
	}
	WCart.prototype.setBackingObject = function(){
		WUtility.traverse(this.element, Delegate.create(this, function(node){
			try{
				node.backingObject = this;
			}catch(e){}
		}));
	}
	WCart.prototype.init = function(){
		this.inited = true;
		this.refresh();
	}
	WCart.prototype.add = function(id){
		if(!this.inited) return false;
		var url = Address.dynamic(this.options.backendURL + "?action=add&id="+id+"&qty=#foodItemQty"+id+"#");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		//alert(root.firstChild.nodeValue);
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			this.refresh();
			return true;
		}
		//return true;*/
	}
	WCart.prototype.modify = function(id){
		if(!this.inited) return false;
		var url = Address.dynamic(this.options.backendURL + "?action=modify&id="+id+"&qty=#countQty"+id+"#");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		//alert(root.firstChild.nodeValue);
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			this.refresh();
			return true;
		}
		//return true;*/
	}
	WCart.prototype.refresh = function(){
		if(!this.inited) return false;
		var url = this.options.backendURL + "?action=queue"+(this.options.mode ? "&mode="+this.options.mode : "");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		//this.content.innerHTML = root.firstChild.nodeValue;
		//alert(root.getElementsByTagName("content")[0].text);
		var content = root.getElementsByTagName("content")[0];
		var value = root.getElementsByTagName("value")[0];
		var count = root.getElementsByTagName("count")[0];
		this.content.innerHTML = unescape(content.textContent || content.text);
		//if(BrowserDetect.browser=="Explorer"&&BrowserDetect.version<7){pngfix(this.content)}
		this.cartStatus.value = parseFloat(value.textContent || value.text);
		this.cartStatus.count = parseFloat(count.textContent || count.text);
		this.status.innerHTML = sprintf(this.options.statusMessage, this.cartStatus.count, this.cartStatus.value, this.options.currency);
		this.setBackingObject();
		if(this.cartStatus.count==0 && this.options.emptyURL){ // if cart becomes empty, jump to this url
			location.replace(this.options.emptyURL);
		}
	}
	WCart.prototype.remove = function(id, removeAll){
		if(!this.inited) return false;
		removeAll = (removeAll == true) ? "&all" : "";
		var url = this.options.backendURL + "?action=remove&id="+id+removeAll;
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			this.refresh();
			return true;
		}
	}
	WCart.prototype.clearAll = function(){
		if(!this.inited) return false;
		if(this.cartStatus.count>0){
			if(confirm("Sigur golesti cosul?")){
				var url = Address.dynamic(this.options.backendURL + "?action=init");
				var response = HTTPRequest.get(url);
				var root = response.xml.getElementsByTagName("response")[0]; // process the XML
				//alert(root.firstChild.nodeValue);
				if(root.getAttribute("result").toUpperCase()=="FAILURE"){
					alert(root.firstChild.nodeValue);
					return false;
				}else{
					this.refresh();
					return true;
				}
			}
		}/*else{
			alert("Cosul este gol.");
		}*/
	}
	/*WCart.prototype.count = function(id){
		if(!this.inited) return false;
		var url = Address.dynamic(this.options.backendURL + "?action=status");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		//alert(root.firstChild.nodeValue);
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			return parseInt(root.firstChild.nodeValue);
		}
		//return true;*
	}
	WCart.prototype.isAuthorized = function(){
		if(!this.inited) return false;
		var url = Address.dynamic(this.options.backendURL + "?action=auth");
		var response = HTTPRequest.get(url);
		var root = response.xml.getElementsByTagName("response")[0]; // process the XML
		//alert(root.firstChild.nodeValue);
		if(root.getAttribute("result").toUpperCase()=="FAILURE"){
			alert(root.firstChild.nodeValue);
			return false;
		}else{
			return true;
		}
		//return true;*
	}*/
	
	WCart.prototype.checkout = function(){
		if(!this.inited) return false;
		if(this.cartStatus.count>0){
			//if(confirm(sprintf("Total %d preparate, %.2f %s. Confirma?", this.cartStatus.count, this.cartStatus.value, this.options.currency)))
			Address.replace(this.options.checkoutURL);
		}/*else{
			alert("Cosul este gol.");
		}*/
	}
	WCart.INSTANCES = [];
	WCart.messagePageInit = "Va rugam asteptati pana se initializeaza pagina!";
	WCart.backendURL = "/cart/";
	WCart.checkoutURL = "/orders/";
	WCart.messageDefaultStatus = "Total <strong>%d</strong> preparate<br/><strong>%8.2f %s</strong>.";
	WCart.messageDefaultCurrency = "RON";
	WCart.messageDefaultEmpty = "Cosul tau este gol."
	
	

// -- sprint functionality

function printf() {
  document.write(va_sprintf(printf.arguments));
}

// str = sprintf(format, ...);
function sprintf() {
  return sprintf(sprintf.arguments);
}

// printf(format, ...);
String.prototype.printf = function() {
  document.write(sprintf(Array.prototype.concat.apply(this, arguments)));
}

// str = sprintf(format, ...);
String.prototype.sprintf = function() {
  return sprintf(Array.prototype.concat.apply(this, arguments));
}


sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;

		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }
 
		var code = null;
		var match = null;
		var i = null;
 
		for (i=0; i<matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
 
sprintf = sprintfWrapper.init;

	/** Point class */
	function Point(x, y){
		this.x = x;
		this.y = y;
		this.toString = function(){
			return "(" + this.x + "," + this.y + ")";
		}
	}

	/** Class for handling mouse events. Static. */
	function Mouse(){
		throw 'RuntimeException: Mouse is a static utility class and may not be instantiated';
	}
	Mouse.prototype = new EventDispatcher;
	
	/** Updates two globals that hold the current mouse position. Internal, no need to be called. */
	Mouse.capture = function(e){
		e = e ? e : window.event;
		var mouse = Event.mouse(e);
		//Debug("Mouse.capture: " + mouse);
		Mouse.x = mouse.x;
		Mouse.y = mouse.y;
		for(var i=0; i<Mouse.OBSERVERS.length; i++){
			Mouse.OBSERVERS[i].funct.apply(Mouse.OBSERVERS[i].scope, [{x:Mouse.x, y:Mouse.y}]);
		}
	}
	
	Mouse.observe = function(scope, eventHandler){
		if(typeof(eventHandler) != 'function' && typeof(scope[eventHandler]) != 'function')
			return false;
		Mouse.OBSERVERS.push({scope:scope, funct:typeof(eventHandler) == "function" ? eventHandler : scope[eventHandler]});
	}
	
	/** Checks if mouse is over an element */
	Mouse.over = function(element){
		var offset = Element.getOffset(element);
		var result = false;
		if(offset.top < Mouse.y && Mouse.y < offset.bottom && offset.left < Mouse.x && Mouse.x < offset.right)
			result = true;
		//Debug("Event: x=" + mouse.x + ", y=" + mouse.y + "offset: t=" + offset.top + ", l=" + offset.left + ", b=" + offset.bottom + ", r=" + offset.right + ", over = " + result);
		return result;
	}
	
	/** Start capturing mouse events. */
	Mouse.init = function(){
		if (document.layers) { // Netscape
			document.captureEvents(Event.MOUSEMOVE);
			document.onmousemove = Mouse.capture;
		} else if (document.all) { // Internet Explorer
			document.onmousemove = Mouse.capture;
		} else if (document.getElementById) { // Netcsape 6 && Firefox
			document.onmousemove = Mouse.capture;
		}
	}
	Mouse.x = 0; // Horizontal position of the mouse on the screen
	Mouse.y = 0; // Vertical position of the mouse on the screen
	Mouse.OBSERVERS = [];

// MULTIPLE ONLOAD EVENTS START---------------------------------------------------------------------------------
window.onloadListeners=new Array();
window.onUnloadListeners=new Array();
window.addOnLoadListener = function (scope, listener) {
	//Makes a function run on page load
	//alert("adding listener" + listener);
	window.onloadListeners[window.onloadListeners.length]={f:listener, s:scope, a:Array.prototype.slice.call(arguments, 2)};
}
window.addOnUnloadListener = function (scope, listener) {
	//Makes a function run on page load
	//alert("adding listener");
	window.onUnloadListeners[window.onUnloadListeners.length]={f:listener, s:scope, a:Array.prototype.slice.call(arguments, 2)};
}
window.triggerOnLoadEvent = function(){
	// Trigger the listener functions in the specified scope
	//alert("Page loaded, triggering " + window.onloadListeners.length + " listeners.");
	for(var i=0;i<window.onloadListeners.length;i++){
		//alert(i+"-t) " + window.onloadListeners[i].f);
		var listener = window.onloadListeners[i];
		listener.f.apply(listener.s, listener.a);
	}
}
window.triggerOnUnloadEvent = function(){
	// Trigger the listener functions in the specified scope
	//alert("Page loaded, triggering " + window.onloadListeners.length + " listeners.");
	for(var i=0;i<window.onUnloadListeners.length;i++){
		var listener = window.onUnloadListeners[i];
		listener.f.apply(listener.s, listener.a);
	}
}
Event.observe(window, "load", triggerOnLoadEvent, false);
Event.observe(window, "unload", triggerOnUnloadEvent, false);
// MULTIPLE ONLOAD EVENTS END---------------------------------------------------------------------------------

window.addOnLoadListener(window, Mouse.init); // make browser capture mouse coordinates and store them in Mouse.x,Mouse.y
window.addOnLoadListener(window, WCart.initAll); // initialize shopping cart
window.addOnLoadListener(window, WCryptoText.initAll);