var oldtdobj=false;
var oldlname=false;
var controlCHpath=false;
var controlCHrpath=false;
var name='createControl';


function Qname(val){
	
	if(val.match(new RegExp('^ +$','i'))){
		alert('bad name'); return false;	
	}

	if(val.length <= 0){
		alert('bad name.'); return false; 
	}
	return true;
}


function checkForm(name){

	// TODO: сделать проверку на существование элемента с таким путем и таким именем
	var flag = 0;
	var urlerr   = 'допустимые символы в url - буквы латинского алфавита и цифры';
	var lnameerr = 'Если вы не укажете название нового элемента, по умолчанию он примет значение url';
	var fromerr  = 'Необходимо вырать тип нового элемента';
	var url   = document.forms[name].url.value;
	var lname = document.forms[name].lname.value;
	var lnamereg = new RegExp("^ +$",'i');
	var from = document.getElementById('from');
	if(!from.value.length){alert(fromerr);return false;}
	if(checkUrl(url)==null){alert(urlerr);return false;}
	if(lname.match(lnamereg)||!lname.length){
		if(window.confirm(lnameerr)){
			document.forms[name].submit();
		}else{
			return false;
		}
	}else{
		document.forms[name].submit();
	}
}

function showCreateControl(){
	containerTr = document.getElementById('createControlContainer');
	containerTr.style.visibility=(containerTr.style.visibility=='hidden')?'inherit':'hidden';
}

function checkUrl(url){
	return url.match(new RegExp('[0-9a-z]+','i'));
}

function controlToL(rButton){
	container = document.getElementById('typesORlinks');
	array = (rButton.id=='as1')?optionsTypes:optionsLinks;
	selector = '<select name=from>';
	for(i=0;i<array.length;i++){selector += array[i].getHTML()}
	selector += '</select>';
	container.innerHTML=selector;
}

function timeDateInput(name){
	this.name    = name;
	this.ID      = this.name+'timeDateInput';
//-----------------------------
	this.set     = TDIset;
	this.iniTime = TDIini;
}



function TDIini(dmy,time){
	if(dmy&&time){
	objtime = document.getElementById(this.ID+'time');
	objdate = document.getElementById(this.ID+'date');
	objdate.value=dmy;
	objtime.value=time;
	}else{
	timeUpdate(this.ID);
	dateUpdate(this.ID);
	}
}

function timeUpdate(ID){
	objtime = document.getElementById(ID+'time');
	objtime.value=gettime();
}
function dateUpdate(ID){
	objdate = document.getElementById(ID+'date');
	objdate.value=getdate();
}

function getdate(){
	date = new Date();
	return date.getDate()+'/'+eval(date.getMonth()+1)+'/'+date.getFullYear();
}

function gettime(){
	date = new Date();
	min = date.getMinutes();
	return date.getHours()+':'+(min<10?'0'+min:min);
}

function TDIset(dmy,time){
	document.write('<TABLE align=left border=0 cellpadding=0 cellspacing=1><TR>');
	document.write('<TD><input style="width:62px;text-align:center;" id="'+this.ID+'date" value="'+dmy+'" name="'+this.name+'[date]"></TD>');
	document.write('<TD><A HREF=# onclick="dateUpdate(\''+this.ID+'\');return false;"><img alt="выставить текущую дату" border=0 width=16 height=16 src='+globalPath+'/ico/calendar.gif></A></TD>');
	document.write('<TD><input style="width:40px;text-align:center;" id="'+this.ID+'time" value="'+time+'" name="'+this.name+'[time]"></TD>');
	document.write('<TD><A HREF=# onclick="timeUpdate(\''+this.ID+'\');return false;"><img alt="выставить текущее время" border=0 width=16 height=16 src='+globalPath+'/ico/clock.gif></A></TD>');
	document.write('</TR></TABLE>');
	this.iniTime(dmy,time);
}


function option(value,name,add){
	this.value = value;
	this.name = name;
	try{this.add = add;}catch(e){}
	this.getHTML = getHTML;
}

function getHTML(){
	return '<option style="background-image:url(' + globalPath + '/ico/types/'+ this.value + '" value="' + this.value + '">' + this.name + '</option>';
}


function newNodeSelector(flag){
	divrightmenuTypes = document.getElementById('rightmenuTypes');

	if(flag){
		divrightmenuTypes.style.visibility = 'inherit';
		divrightmenuTypes.style.pixelTop = window.event.y + document.body.scrollTop;
		divrightmenuTypes.style.pixelLeft = window.event.x + document.body.scrollLeft;
		window.event.cancelBubble = true;
		document.body.oncontextmenu=function(){ newNodeSelector(false); };
		document.body.onclick = function(){ newNodeSelector(false); };
		document.body.onkeypress = function(){ if(event.keyCode==27){ newNodeSelector(false);}else{return false;}};
	}else{
		divrightmenuTypes.style.visibility = 'hidden';
		document.body.oncontextmenu = function(){ return true; };
		document.body.onclick       = function(){ return true; };
		document.body.onkeypress    = function(){ return true; };
	}
}


function setTypeNewNode(type,typeName){
	newNodeImg = document.getElementById('newNodeImg');
	newNodeImg.src = globalPath + '/ico/types/'+type+'.gif';
	newNodeImg.alt = "тип нового узла: "+typeName+"\nкликните, чтобы изменить";
	from = document.getElementById('from');
	from.value = type;
	typeComment = document.getElementById('typeComm');
	typeComment.innerHTML = typeName;

}


function controlCH(path,lname,tdobj,rpath){
	divmenu = document.getElementById('rightmenu');
	if(oldtdobj){oldtdobj.style.backgroundColor = "#DFDFDF";}
	if(path){
		controlCHpath  = path;
		controlCHrpath = rpath;
		divmenu.style.visibility = 'inherit';
		divmenu.style.pixelTop = window.event.y + document.body.scrollTop;
		divmenu.style.pixelLeft = window.event.x + document.body.scrollLeft;
		tdobj.style.backgroundColor = "#999999";
		oldtdobj=tdobj;
		oldlname=lname;
		document.body.oncontextmenu=function(){ return false; };
		document.body.onclick = function(){ controlCH(false); };
		document.body.onkeypress = function(){ if(event.keyCode==27){ controlCH(false);}else{return false;}};
	}else{
		divmenu.style.visibility = 'hidden';
		document.body.oncontextmenu = function(){ return true; };
		document.body.onclick       = function(){ return true; };
		document.body.onkeypress    = function(){ return true; };
	}
}

function controlEdit(arg){
	document.location.href = globalPath + '/' + controlCHpath + "?action=edit"+'&'+arg;
}

function controlDelete(arg){
	if(window.confirm('Вы уверены, что хотите удалить "'+oldlname+'" ?')){
	document.location.href = globalPath + '/' + controlCHpath + "?system=delete";
	}
}

function controlHide(controlCHpath){
	document.location.href = globalPath + '/' + controlCHpath + "?system=hide";
}


function controlSort(controlCHpath,direction){
	document.location.href = globalPath + '/' + controlCHpath + "?system=sort"+'&direction='+direction;
}


function controlRename(name){
	controlCH(false);
	divmenu = document.getElementById('rightmenu');
	newname=window.prompt('введите новое имя', oldlname);
	if(newname!=null){
		divmenu.innerHTML='<form method=post name=controlRename action=' + globalPath + '/' + controlCHpath + '?system=rename>'
		+ '<input type=hidden name=newname value=\'' + newname + '\'>'
		+ '</form>';
		document.forms['controlRename'].submit();
	}
}

function checkLinkExists(){

return true;
}

function controlUrl(name){
	controlCH(false);
	divmenu = document.getElementById('rightmenu');
	newname=window.prompt('введите новое значение URL', controlCHrpath);
	if(newname!=null&&checkUrl(newname)!=null){
		if(checkLinkExists(newname)){
			for (i=0;i<optionsLinks.length;i++){
				if(optionsLinks[i].add==newname){
				alert('не могу изменить URL');
				return true;
				}
			}
		}
		divmenu.innerHTML='<form method=post name=controlUrl action=' + globalPath + '/' + controlCHpath + '?system=editurl>'
		+ '<input type=hidden name=newpath value=\'' + newname + '\'>'
		+ '</form>';
		document.forms['controlUrl'].submit();
	}else{
		alert('не могу изменить URL');
	}
}

	var wrImageWindow;
	function rOpenImageWindow(src,width,height){ // открыть окно с изображением
		width = (width)?width:470;
		height = (height)?height:470;
		if(wrImageWindow) wrImageWindow.close();
		wrImageWindow=window.open("","blankImageWindow", 'status=no,scrollbars=no,resizable=1,width='+(width+20)+',height='+(height+20)+'');
		wrImageWindow.document.write("<html><head><title>Изображение</title>");
		wrImageWindow.document.write("<body topmargin=5 marginheight=5 leftmargin=0 marginwidth=0 bgcolor=white text=black link=black alink=black vlink=black>");
		wrImageWindow.document.write("<center>");
		wrImageWindow.document.write("<table border=0 cellspacing=1 cellpadding=1 bgcolor=#333399>");
		wrImageWindow.document.write("<tr><td align=center bgcolor=white>");
		wrImageWindow.document.write("<a href='javascript:self.close();' title='закрыть окно'><img src='"+src+"' width="+width+" height="+height+" border=0></a>");
		wrImageWindow.document.write("</td></tr>");
		wrImageWindow.document.write("</table>");
		wrImageWindow.document.write("</body></html>");
		wrImageWindow.document.close();
		wrImageWindow.focus();
	}

