function Util(){}

Util.toArray = function(obj){
	if(obj.length) return obj;
	return new Array(obj);
}
Util.isIe  = (document.all && !navigator.pluginsEnabled );
Util.isIe8  = Util.isIe && navigator.userAgent.indexOf("MSIE 8.") != -1;
Util.isMac = (navigator.appVersion.toLowerCase().indexOf('macin')>-1);

Util.log = function(obj){
	var h='';
	for(i in obj){
		try{h += i+ ' : ' + obj[i] + '<br>'}catch(e){}
	}
	document.body.innerHTML += '<hr>'+h+'<hr>';
}

function WooDhtml(){
}
//Util.log(navigator)

//select action
WooDhtml.SelectOpened = null;

WooDhtml.SelectOpen = function(ev,obj){
	var select = obj.previousSibling.firstChild;
//	alert(obj.innerHTML.replace(/></g,'>\r\n<'))
	var doIt = (this.SelectOpened != select);
	WooDhtml.SelectClose();
	if(obj.previousSibling.lastChild.disabled) return;
	if(doIt){
		select.style.display='block';
		select.style.visibility='visible';
		WooDhtml.SelectOpen.currentSelect = select;
		obj.style.zIndex = 15;
		select.style.zIndex = 14;
		this.SelectOpened = select;

		WooDhtml.replaceDivByFrame(select);
	}
	// Next time that I have few hour try to remove this setTimeout
	setTimeout("document.onclick=function(){WooDhtml.SelectClose()};",20);
}
//function created to work around the IE bug of z-Index of <select>
//document.all to avoid netscape, !navigator.pluginsEnabled to avoid Opera

WooDhtml.frameCounter = 0;
WooDhtml.replaceDivByFrame = function(select){
	if(select.firstChild && select.firstChild.nodeName!='IFRAME'){
		WooDhtml.frameCounter++;
		var widthRef = select.clientWidth +20;
		var heightRef = select.clientHeight+2;

		var content = "<div class='WooDhtmlSelectMenu' style='display:block;visibility:visible;top:0px;width:100%;height:100%;'>"+select.innerHTML+"</div>";
		select.style.border='0px';
		var theHtml = '<iframe src="../blank.html" frameborder=0 scrolling="no" width="'+widthRef+'" height="'+heightRef+'" border="no" name="WooDhtmlFrame'+WooDhtml.frameCounter+'" style="margin:0px;padding:0px;border:0px; width:'+widthRef+'px; height:'+heightRef+'px border:none";"></iframe>';

		select.innerHTML = theHtml;
		select.style.padding=0;
		select.style.height = heightRef+"px";
		select.style.overflowY="hidden";
		//select.style.display='none';

		var myFrame = window.frames['WooDhtmlFrame'+WooDhtml.frameCounter];

		with(myFrame.document){
			//body.style.display='none';
			write('<html style=""><head>\r\n');
			write('<base href="'+window.location+'" target="_parent">\r\n');
			for(var i=0;i<document.styleSheets.length;i++){
				if(document.styleSheets.item(i).href){
					write('<link rel="stylesheet" type="text/css" href="'+document.styleSheets.item(i).href+'">\r\n');
				}else{
					write('<style type="text/css">'+document.styleSheets.item(i).cssText+'</style>');
				}
			}
			write('</head>\r\n<body topMargin="0" bottomMargin="0" style="margin:0px;padding:0px;">');
			write(content);
			write('</body></html>');

			// Firefox need some time for CSS interpretation
			if (Prototype.Browser.Gecko) {
				body.style.display='none';
				WooDhtml.currentFrameBody = body;
				setTimeout("WooDhtml.currentFrameBody.style.display='block'",200);
			}
		}
		myFrame.WooDhtml = WooDhtml;
	}
}

WooDhtml.SelectClose = function(){
	if(this.SelectOpened){
		this.SelectOpened.style.zIndex = 0;
		this.SelectOpened.parentNode.nextSibling.style.zIndex = 0;
		this.SelectOpened.style.display='none';
		this.SelectOpened = null;
	}
	document.onclick=function(){return true};
}
WooDhtml.SelectRefresh = function (ev,obj){
	var currentMenuLabel = obj.parentNode.nextSibling.lastChild.lastChild.firstChild.nextSibling;
	var dhtmlDisplayedTable = obj.parentNode.nextSibling;

	var aLabel = obj.options[obj.selectedIndex].text;
	if(aLabel.trim().length==0){
		aLabel = "&nbsp;";
	}

	currentMenuLabel.innerHTML = aLabel;
	WooDhtml.refreshDisabled (obj);
}
WooDhtml.SelectRefreshOptions = function (ev,obj){
	var select = obj.previousSibling.lastChild;
	var div = obj.previousSibling.firstChild;
	if(select.disabled) {
		div.innerHTML = "";
		return;
	}
	var html = '';
	var optidx = 0;
	var first = true;
	var isMenu = select.getAttribute('type')=='menu' || select.getAttribute('type')=='menu2';
	for(var i=0;i<select.childNodes.length;i++){
		var item = select.childNodes[i];
		if(item.nodeName=='OPTION'){
			if(isMenu){optidx++;isMenu=false;continue;}
			var opt = item;
			html+='<a confirm="false" class="'+(!first?'WooDhtmlSelectNotFirstItem ':'')+opt.className+'" href="javascript:if(true){}" onclick="WooDhtml.OptionClick(event,this,'+(optidx++)+');" value="'+opt.value+'">'+opt.text+'</a>';
		}else{
			html+='<div class="WooDhtmlOptGroup '+(!first?'WooDhtmlSelectNotFirstItem ':'')+'">';
			html+='<div class="WooDhtmlOptGroupLabel '+item.className+'">'+item.label+'</div>';
			html+='<div class="WooDhtmlOptGroupOptionContainer">';
			var firstingroup = true;
			for(var j=0;j<item.childNodes.length;j++){
				if(isMenu){optidx++;isMenu=false;continue;}
				var opt = item.childNodes[j];
				html+='<a confirm="false" class="'+(!firstingroup?'WooDhtmlSelectNotFirstItem ':'')+opt.className+'" href="javascript:if(true){}" onclick="WooDhtml.OptionClick(event,this,'+(optidx++)+');" value="'+opt.value+'">'+opt.text+'</a>';
				firstingroup = false;
			}
			html+='</div></div>';
		}
		first=false;
	}
	div.innerHTML = html;
	div.removeAttribute('style');
}
WooDhtml.OptionClick = function (ev,obj,i){
	var select = WooDhtml.SelectOpened.nextSibling;
	if(select.disabled) {
		return;
	}

	if(i!=select.selectedIndex){
		select.selectedIndex = i;
		try {
			if (select.onchange)
				select.onchange();
		}
		catch (err) {

		};
		WooDhtml.SelectRefresh(null,select);

		select.options[select.selectedIndex].removeAttribute("selected");
		select.options[i].setAttribute ("selected", "selected");
		select.options[select.selectedIndex].selected=false;
		select.options[i].selected=true;
	}
	WooDhtml.SelectClose();
}


//checkbox and radio action
WooDhtml.LabelClick = function(ev,obj){
	//document.getElementById(obj.htmlFor).onclick();
}

WooDhtml.Click = function(ev,obj){
	obj.nextSibling.click();
}
WooDhtml.Refresh = function(ev,obj){
	WooDhtml.refreshDisabled (obj);
	if(obj.type=='checkbox'){
		obj.previousSibling.className = (obj.checked==true)?'WooDhtmlChecked':'';
	}else{
		var list = Util.toArray(obj.form[obj.name]);
		for(var i=0;i<list.length;i++){
			list[i].previousSibling.className = (list[i].checked==true)?'WooDhtmlChecked':'';
		}
	}
}

WooDhtml.refreshDisabled = function (obj) {
	var uiItem = obj.parentNode.nextSibling;
	if (uiItem.className != undefined) {
		var isDisabledDisplay = uiItem.className.indexOf('disabled') != -1;
		if(!isDisabledDisplay && obj.disabled) {
			obj.parentNode.nextSibling.className=obj.parentNode.nextSibling.className+' disabled';

		} else if(isDisabledDisplay && !obj.disabled) {
			obj.parentNode.nextSibling.className=obj.parentNode.nextSibling.className.replace(' disabled', '');
		}
	} else {
		uiItem = obj.parentNode;
		var isDisabledDisplay = uiItem.className.indexOf('disabled') != -1;

		if(!isDisabledDisplay && obj.disabled) {
			obj.parentNode.className=obj.parentNode.className+' disabled';

		} else if(isDisabledDisplay && !obj.disabled) {
			obj.parentNode.className=obj.parentNode.className.replace(' disabled', '');
		}
	}
}

WooDhtml.RefreshAll = function(){
	if(window.isRefreshingDhtml) {
		return;
	}
	window.isRefreshingDhtml = true;
	try {
		var selects = document.getElementsByClassName('WooDhtmlSelectmenuPositioner');
		for(var i=0; i<selects.length; i++) {
			WooDhtml.SelectRefresh(null, selects[i].lastChild);
		}
		var radios = document.getElementsByClassName('WooDhtmlradio');
		for(var i=0; i<radios.length; i++) {
			WooDhtml.Refresh(null, radios[i].lastChild);
		}
		var checkboxes = document.getElementsByClassName('WooDhtmlcheckbox');
		for(var i=0; i<checkboxes.length; i++) {
			WooDhtml.Refresh(null, checkboxes[i].lastChild);
		}
	} catch(e) {
	}
	window.isRefreshingDhtml = false;
}
WooDhtml.resizeImg = function(){
	var redoItLater = false;
	for(var i=0;i<document.images.length;i++){
		var img = document.images[i];
		if(img.className=='WooDhtmlImageToResize'){
			if(!img.complete || (img.parentNode.clientHeight==0 && img.parentNode.clientWidth==0)){
				redoItLater=true;
			}else{
				expectedHeight = img.parentNode.clientHeight;
				expectedWidth = img.parentNode.clientWidth;
				h = img.height;
				w = img.width;
				if(h<=expectedHeight &&w<=expectedWidth){
					img.style.marginLeft = Math.round((expectedWidth - img.width)/2)+'px';
					img.style.marginTop = Math.round((expectedHeight - img.height)/2)+'px';
				}else if((h / w) > (expectedHeight / expectedWidth)){
					img.height = expectedHeight;
					img.width = w * expectedHeight / h;
					img.style.marginLeft = Math.round((expectedWidth - img.width)/2)+'px';
					img.style.marginRight = Math.round((expectedWidth - img.width)/2)+'px';
				}else{
					img.width = expectedWidth;
					img.height = h * expectedWidth / w;
					img.style.marginTop = Math.round((expectedHeight - img.height)/2)+'px';
				}
				img.className='';
			}
		}
	}
	if(redoItLater){
		window.setTimeout('WooDhtml.resizeImg()',500);
	}
}
function copyStyles(from,to, cssRules){
	if(document.defaultView && document.defaultView.getComputedStyle){
		var currentStyle = document.defaultView.getComputedStyle(from, "");
		for(i in cssRules){
			to.style[i] = currentStyle.getPropertyValue(cssRules[i]);
		}
	}
	else if(from.currentStyle){
		for(i in cssRules){
			to.style[i] = from.currentStyle[i];
		}
	}
}
WooDhtml.editSpanInput = function(span, fct_validation, fct_oncomplete, fct_onsuccess, fct_onfailure){
	var updating = false;
	var onclick = span.onclick;
	span.onclick=null;
	eval('var json = '+span.nextSibling.innerHTML);

	var jsonspan = span.nextSibling;
	var startvalue = jsonspan.title;

	var newInput = document.createElement('input');
	if(typeof(json.classinput) != 'undefined')
		newInput.className = json.classinput;
	if(typeof(json.styleinput) != 'undefined')
		newInput.setStyle(json.styleinput);
	if(typeof(json.maxlength) != 'undefined')
		newInput.maxLength = json.maxlength;
	if(typeof(json.size) != 'undefined')
		newInput.size = json.size;
	if(typeof(startvalue) != 'undefined')
		newInput.value = startvalue.unescapeHTML();

	span.innerHTML = '';
	span.appendChild(newInput);
	var input = newInput;

	if(typeof(json.classinput) == 'undefined')
		copyStyles(span,input,{fontSize:"font-size",fontWeight:"font-weight",fontFamily:"font-family",fontColor:"font-color"});

	var update = function(){
		if(updating) return;
		if(input.value == startvalue) {
			cancel();
			return;
		}

		input.onkeypress = null;
		input.onblur = null;

		updating = true;

		if((typeof(json.validation) != 'undefined') && (fct_validation != null)) {
			var callbackvalid = function(){
				input.focus();
				input.select();
				updating = false;
				input.onkeypress = onkeypressInput;
				input.onblur = onblurInput;
			};
			if(!fct_validation(input.value, callbackvalid)) {
				return false;
			}
		}


		var params = {};

		if(typeof(json.params) != 'undefined')
			params = json.params.unescapeHTML().toQueryParams();

		if((input.value.strip() == "") && (typeof(json.defaultvalue) != "undefined")) { // bug a corriger
			input.value = json.defaultvalue;
		}
		else if(input.value.strip() == "" && json.emptyauth == "false") {
			cancel();
			return;
		}

//		jsonspan.title = input.value;
		params[json.name] = input.value;
		var ajaxRequest = new Ajax.Request(json.href,{
			method:'post',
			encoding:json.encoding,
			parameters:params,
			onComplete:function(transport){
			var func = new Function('callback',transport.responseText);
			var callback = function(){
				input.focus();
				input.select();
				input.onkeypress = onkeypressInput;
				input.onblur = onblurInput;
				updating = false;
			}
			if(func(callback)){
				jsonspan.title = input.value;
				span.removeChild(span.firstChild);
				span.appendChild(document.createTextNode(input.value));
				span.origHTML = input.value;
				Truncator.truncateThis(span);
				span.onclick = onclick;
				updating = false;
				if((typeof(json.oncomplete) != 'undefined') && (fct_oncomplete != null)) {
					fct_oncomplete(input.value,ajaxRequest, transport);
				}
			}
		},
		onSuccess:function(transport){
//			alert('success :\n' + transport.responseText);
			if((typeof(json.onsuccess) != 'undefined') && (fct_onsuccess != null)) {
				fct_onsuccess(input.value,ajaxRequest, transport);
			}
		},
		onFailure:function(transport){
//			alert('failed :\n' + transport.responseText);
			if((typeof(json.onfailure) != 'undefined') && (fct_onfailure != null)) {
				fct_onfailure(input.value,ajaxRequest, transport);
			}
		}
		});
	}

	var onblur = true;

	if(typeof(json.onblur) != 'undefined') {
		onblur = json.onblur == 'true'?true:false;
	}
	else {
		onblur = true;
	}

	var cancel = function(){
		span.removeChild(span.firstChild);
		span.appendChild(document.createTextNode(startvalue));
		span.origHTML = startvalue;
		Truncator.truncateThis(span);
		span.onclick = onclick;
	}
	if(onblur) { // Allow desactivate onblur for debug style,css,...
		input.onblur = update;
	}
	else {
		input.onblur = function(){};
	}
	input.onkeypress = function(ev){
		switch(ev.keyCode){
		case 13:input.blur();return false;
		case 27:cancel();break;
		}
		return true;
	}.bindAsEventListener(this);

	var onkeypressInput = input.onkeypress;
	var onblurInput = input.onblur;

	input.focus();
	input.select();
}


WooDhtml.editSpanTextarea = function(span, fct_validation, fct_oncomplete, fct_onsuccess, fct_onfailure){
	var updating = false;
	var onclick = span.onclick;
	span.onclick=null;
	eval('var json = '+span.nextSibling.innerHTML);

	var startvalue = '';

	if(json.defaultvalue == span.innerHTML)
		startvalue = '';
	else
		startvalue = span.innerHTML;

	var dataBR = startvalue.replaceAll("<br>", "\n").replaceAll("<br/>", "\n").replaceAll("<BR>", "\n").replaceAll("<BR/>", "\n");

	span.innerHTML = ('<textarea class="' + json.classtextarea + '" style="' + json.styletextarea + '" maxlength='+json.maxlength+' size='+json.size+'">' + dataBR + '</textarea>');

//	span.removeClassName('textTroncatured');

	var divButtons = '<div class="t_comment_textarea_buttons"><table class="M_comment_textarea_buttons">';
	divButtons += '<tbody><tr>';
	divButtons += '<td><span>';
	divButtons += '<a id="bt_cancel" class="C_bt" title="' + json.btncanceltitle + '" style="" href="javascript:if(true);">';
	divButtons += '<span class="C_bt_left"><span class="C_bt_right"><span class="C_bt_center">';
	divButtons += '<span style="" class="C_bt_decoration">' + json.btncanceltext + '</span>';
	divButtons += '</span></span></span>';
	divButtons += '</a>';
	divButtons += '</span></td>';
	divButtons += '<td>';
	divButtons += '<span class="C_button2">';
	divButtons += '<a id="bt_valid" class="C_bt" title="' + json.btnvalidtitle + '" style="" href="javascript:if(true);">';
	divButtons += '<span class="C_bt_left"><span class="C_bt_right"><span class="C_bt_center">';
	divButtons += '<span style="" class="C_bt_decoration">' + json.btnvalidtext + '</span>';
	divButtons += '</span></span></span>';
	divButtons += '</a>';
	divButtons += '</span></td>';
	divButtons += '</tr>';
	divButtons += '</tbody></table></div>';


	span.innerHTML = span.innerHTML + divButtons;


	var btValid = $('bt_valid');
	var btCancel = $('bt_cancel');

	var textarea = span.firstChild;

	if(typeof(json.classtextarea) == 'undefined')
		copyStyles(span,textarea,{fontSize:"font-size",fontWeight:"font-weight",fontFamily:"font-family",fontColor:"font-color"});

	var update = function(e){
		if(updating) return;
		if(textarea.value.replaceAll('\n', '<br/>') == startvalue) {
			cancel(e);
			return;
		}


		textarea.onkeypress = null;
		textarea.onblur = null;


		updating = true;

		maxsize();

		if((typeof(json.validation) != 'undefined') && (fct_validation != null)) {
			var callbackvalid = function(){
				textarea.focus();
				textarea.select();
				updating = false;
				textarea.onkeypress = onkeypressInput;
				textarea.onblur = onblurInput;
			};
			if(!fct_validation(textarea.value, callbackvalid)) {
				return false;
			}
		}


		var params = {};
		if(typeof(json.params) != 'undefined')
			params = json.params.unescapeHTML().toQueryParams();

		params[json.name] = textarea.value;
		var ajaxRequest = new Ajax.Request(json.href,{
			method:'post',
			encoding:json.encoding,
			parameters:params,
			onComplete:function(transport){
//			alert('complete :\n' + transport.responseText);
			var func = new Function('callback',transport.responseText);
			var callback = function(){
				textarea.focus();
				textarea.select();
				textarea.onkeypress = onkeypressInput;
				textarea.onblur = onblurInput;
				updating = false;
			}
			if(func(callback)){
				if(textarea.value == '') {
					span.innerHTML = json.defaultvalue;
					if(typeof(json.defaultclass) != 'undefined')
						span.className = json.defaultclass;
				}
				else {
					span.innerHTML = textarea.value.replaceAll('\n', '<br/>');
					if(typeof(json.defaultclass) != 'undefined')
						span.className = json.dataclass;
				}

				span.onclick = onclick;
				updating = false;
//				span.addClassName('textTroncatured');
				if((typeof(json.oncomplete) != 'undefined') && (fct_oncomplete != null)) {
					fct_oncomplete(textarea.value,ajaxRequest, transport);
				}
			}
		},
		onSuccess:function(transport){
//			alert('success :\n' + transport.responseText);
			if((typeof(json.onsuccess) != 'undefined') && (fct_onsuccess != null)) {
				fct_onsuccess(textarea.value, ajaxRequest, transport);
			}
		},
		onFailure:function(transport){
//			alert('failed :\n' + transport.responseText);
			if((typeof(json.onfailure) != 'undefined') && (fct_onfailure != null)) {
				fct_onfailure(textarea.value, ajaxRequest, transport);
			}
		}
		});
	}
	var cancel = function(e){
		if(e != undefined){
			e.cancelBubble = true;
			if (e.stopPropagation) e.stopPropagation();
		}

		if(startvalue == '') {
			span.innerHTML = json.defaultvalue;
			if(typeof(json.defaultclass) != 'undefined')
				span.className = json.defaultclass;
		}
		else {
			span.innerHTML = startvalue;
			if(typeof(json.defaultclass) != 'undefined')
				span.className = json.dataclass;
		}
		span.onclick = onclick;
//		span.addClassName('textTroncatured');
	}

	textarea.onkeypress = function(ev){
		switch(ev.keyCode){
//		case 10:
//		case 13:input.blur();return false; //Enter
		case 27:cancel();break;
//		default:alert(ev.keyCode);
		}
		return true;
	}.bindAsEventListener(this);

	var maxsize = function(){
		if((typeof(json.maxlength) != 'undefined') && (textarea.value.length >= json.maxlength)){
			textarea.value = textarea.value.substring(0, json.maxlength);
		}
	};

	textarea.onkeyup = maxsize;

	textarea.onkeydown = maxsize;


	btValid.onclick = update;
	btCancel.onclick = cancel;

	var onkeypressInput = textarea.onkeypress;
	var onblurInput = textarea.onblur;

	textarea.focus();
	textarea.select();
	return true;
}

window.onloadpassive = EventConcat(window.onloadpassive, function(){WooDhtml.resizeImg();});



