var simpleTreeCollection;

$(document).ready(function(){
	$("a.fancybox").fancybox();
	$("a.fancybox img")//.animate({opacity: 0.5}, 1000);
	$("a.fancybox img")//.hover(function(){$(this).animate({opacity: 1.0},300)}, function(){$(this).animate({opacity: 0.5},300)});
	$("#admin_top_but a img")//.animate({opacity: 0.5}, 300);
	$("#admin_top_but a img").hover(function(){$(this).animate({opacity: 1.0},300)}, function(){$(this).animate({opacity: 0.5},300)});
	
	$("table.tablesorter").tablesorter();
	
	simpleTreeCollection = $('.simpleTree').simpleTree({
		autoclose: false,
		afterClick:function(node){
			//alert("text-"+$('span:first',node).text());
		},
		afterDblClick:function(node){
			//alert("text-"+$('span:first',node).text());
		},
		afterMove:function(destination, source, pos){
			//alert("destination-"+destination.attr('id')+" source-"+source.attr('id')+" pos-"+pos);
			$('#'+destination.attr('id')+' ul').animate({opacity: 0.1}, 200);
			$.post('/index.php', {mod:'menus', type:'AJAX', s:'SetParent', id:source.attr('id'), parent: destination.attr('id'), pos:pos}, function(rez){
				//alert(pos+rez);
				$('#'+destination.attr('id')+' ul').html(rez);
				simpleTreeCollection.get(0).setTreeNodes($('#'+destination.attr('id')+' ul'), true);
				},'text');
			$('#'+destination.attr('id')+' ul').animate({opacity: 1.0}, 200);
		},
		afterAjax:function(){
			//alert('Loaded');
		},
		animate:true,
		docToFolderConvert:true
	});
});
/*----- Для AJAX -----*/
function ShowIndicator(objID){
	document.getElementById(objID).innerHTML='<center><img alt="идет загрузка..." src="/images/admin/indicator_medium.gif" border=0 style="border: none 0px red"></center>';
	}
	
function scrollObj(id,step) {
	document.getElementById(id).scrollLeft+=step;
}

function inquirerAct(formObj){
	var formEl = formObj.elements;
	var count  = formEl.length;
	var flag = false;
	for(var i=0; i<count; i++) {
	    if(typeof(formEl[i].name) != 'undefined') {
			if (formEl[i].name=='item')
				if (formEl[i].checked)
					flag=true;
		}
	}
	if (flag)
		SendGetAJAX('type=AJAX&mod=inquirer&s=Add'+GetFromForm(formObj.id),'opros');
		else alert('Надо выбрать вариант ответа!');
}

function getRequestObject(){
		var req = null;
		if (typeof XMLHttpRequest != "undefined")
			req = new XMLHttpRequest();
		if (!req && typeof ActiveXObject != "undefined"){
			try
			{req=new ActiveXObject("Msxml2.XMLHTTP");}
			catch (e){
				try
				{req=new ActiveXObject("Microsoft.XMLHTTP");}
				catch (e2){
					try 
					{req=new ActiveXObject("Msxml2.XMLHTTP.4.0");}
					catch (e3)
					{req=null;}
				}
			}
		}
		if(!req && window.createRequest)
			req = window.createRequest();
		return req;
	}

function SendAJAX(arg){
		//alert(arg);
		var xmlHttp = getRequestObject();
		var addrSave=window.top.location.protocol+"//"+window.top.location.host;
		xmlHttp.open('POST', addrSave, true);
	  	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	  	xmlHttp.setRequestHeader("Content-Length", arg.length);
	  	xmlHttp.send(arg);
	}
	
function SendGetAJAX(arg,objID){
		ShowIndicator(objID);
		//alert(arg);
		var xmlHttp = getRequestObject();
		var addrSave=window.top.location.protocol+"//"+window.top.location.host;
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
			//alert(xmlHttp.responseText);
			document.getElementById(objID).innerHTML=unescape(xmlHttp.responseText);
			
					var dragObjects = getElementsByClassName('menusItem');
				    for(var i=0; i<dragObjects.length; i++) {
				        new DragObject(dragObjects[i])
				    }   

					//var DropTargets = document.getElementById('dragObjects').getElementsByTagName('span')
					var DropTargets = getElementsByClassName('menusItem');
				    for(var i=0; i<DropTargets.length; i++) {
				        new DropTarget(DropTargets[i])
				    } 
			}
		}		
		xmlHttp.open('POST', addrSave, true);
	  	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	  	xmlHttp.setRequestHeader("Content-Length", arg.length);
	  	xmlHttp.send(arg); 
	}

/*----- Общие -----*/
function sDisp(obj){obj.style.display="block";}
function sDispN(obj){obj.style.display="none";} 
function pause(ms){
		var date = new Date();
		var curDate = null;
		do { curDate = new Date(); }
		while(curDate-date < ms);
	}
	
function OpenEditor(type,id){
	window.open("/admin/includes/editor.php?type="+type+"&id="+id,"Edit","height=600, width=800");
	//window.open("http://domino.artena.ru/admin/includes/editor.php?type="+type+"&id="+id,"Edit","height=600, width=800");
	}
	
function OpenEditor2(type,id){
	window.open("/admin/archedit/editor.php?type="+type+"&id="+id,"Edit","height=600, width=800");
	}

function ChangeField(table,field,id,objID){
	var nameData = document.getElementById(objID).innerHTML;
	nameData = prompt ("Введите новое значение:", nameData );		
	if (nameData != null)
			SendGetAJAX("mod=edit&type=AJAX&table="+table+"&field="+field+"&id="+id+"&new="+encodeURIComponent((nameData)),objID);
	}
	
function EditorField(table,field,id){
	window.open("/admin/includes/editor2.php?table="+table+"&field="+field+"&id="+id,"Edit","height=600, width=800");
	}
	
function Refresh(module,id){
	SendGetAJAX("mod="+module+"&type=AJAX&s=Refresh&id=" + id, module+id);
	}

function GetFromForm(formID){
	var form   = document.getElementById(formID);
	var formEl = form.elements;
	var count  = formEl.length;
	var str = '';
	for(var i=0; i<count; i++) {
	    if(typeof(formEl[i].name) != 'undefined') {
	        switch(formEl[i].type) {
	            case 'radio':
	                if (formEl[i].checked) {str += '&' + formEl[i].name + '=' + encodeURIComponent((formEl[i].value));}
	            break;
	            case 'checkbox':
	                if (formEl[i].checked) {str += '&' + formEl[i].name + '=' + encodeURIComponent((formEl[i].value));}
	            break;
				case 'select-multiple':
					for (var j=0; j < (formEl[i].options.length); j++)
						if (formEl[i].options[j].selected) 
							str += '&' + formEl[i].name +'['+j+']'+'='+ encodeURIComponent((formEl[i].options[j].value));
	            break;
	            default:
	                str += '&' + formEl[i].name + '=' + encodeURIComponent((formEl[i].value));
	            break;
		        }            
		    }
		}
	return str;
	}	
/*----- PartModul -----*/

function Move(modul,who,id,direct){
	ShowIndicator(modul + who + id);
	if (direct==1) arg = "mod="+modul+"&type=AJAX&s="+who+"Up&id="+id;
	if (direct==0) arg = "mod="+modul+"&type=AJAX&s="+who+"Down&id="+id;
	var xmlHttp = getRequestObject();
	var addrSave=window.top.location.protocol+"//"+window.top.location.host;
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4) {
		var newid= xmlHttp.responseText;
		//alert(newid);
		if (newid == id){
			if (direct==1) alert("Выше нельзя!");
			if (direct==0) alert("Ниже нельзя!");
			SendGetAJAX("mod="+modul+"&type=AJAX&s=Show"+who+"&id="+id, modul+who+id);
			}
		else{
			try {
				document.getElementById(modul+who+newid).id = "temp";
				document.getElementById(modul+who+id).id = modul+who+newid;
				document.getElementById("temp").id = modul+who+id;
				SendGetAJAX("mod="+modul+"&type=AJAX&s=Show"+who+"&id="+id, modul+who+id);
				SendGetAJAX("mod="+modul+"&type=AJAX&s=Show"+who+"&id="+newid, modul+who+newid);
				}
			catch (error) {
				document.getElementById(modul+who+id).id = modul+who+newid;
				SendGetAJAX("mod="+modul+"&type=AJAX&s=Show"+who+"&id="+newid, modul+who+newid);
				}
			}
		} 
	}		
	xmlHttp.open('POST', addrSave, true);
	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	xmlHttp.setRequestHeader("Content-Length", arg.length);
	xmlHttp.send(arg);
	}

function Hide(modul,who,id){
	SendGetAJAX("mod="+modul+"&type=AJAX&s="+who+"Hide&id="+id, modul+who+id);
	}

function Show(modul,who,id){
	SendGetAJAX("mod="+modul+"&type=AJAX&s="+who+"Show&id="+id, modul+who+id);
	}	
	
function ItemDel(modul,id){
		if (confirm("Вы действительно хотите удалить элемент?"))
			{SendGetAJAX("mod="+modul+"&type=AJAX&s=ItemDel&id="+id, modul+"Item"+id)}
	}
	
function PartDel(modul,id){
		if (confirm("Вы действительно хотите удалить раздел?")) 
			{SendGetAJAX("mod="+modul+"&type=AJAX&s=PartDel&id="+id, modul+"Part"+id)}
	}
function lotteryArchDel(modul,id){
		if (confirm("Вы действительно хотите удалить информацию?")) 
			{SendGetAJAX("mod="+modul+"&type=AJAX&s=ArchiveDel&id="+id, "archive")}
}
function lotteryCodeDel(modul,id){
		if (confirm("Вы действительно хотите удалить код?")) 
			{SendGetAJAX("mod="+modul+"&type=AJAX&s=CodeDel&id="+id, "codes")}
}
function lotteryCodeAdd(descript){
	var desc=document.getElementById(descript).value;
	SendGetAJAX("mod=lottery&type=AJAX&s=CodeAdd&description="+desc, "codes");
}
function lotteryPrizeDel(modul,id){
		if (confirm("Вы действительно хотите удалить приз?")) 
			{SendGetAJAX("mod="+modul+"&type=AJAX&s=PrizeDel&id="+id, "prizes")}
}
function lotteryPrizeAdd(descript){
	var desc=document.getElementById(descript).value;
	SendGetAJAX("mod=lottery&type=AJAX&s=PrizeAdd&description="+desc, "prizes");
}
function lotterySetPriorPrize(id,obj){
	SendGetAJAX("mod=lottery&type=AJAX&s=PriorShow&id="+id, "dialog-form");
	$( "#dialog-form" ).dialog( "option", "title", 'Выберете приоритетный приз' );
	$( "#dialog-form" ).bind( "dialogclose", function(event, ui) {
		SendGetAJAX("mod=lottery&type=AJAX&s=GetPrior&id="+id, obj);
		$( "#dialog-form" ).unbind("dialogclose");
	});

	$( "#dialog-form" ).dialog( "open" );
}
function lotterySetPrior(codeid,id){
	SendGetAJAX("mod=lottery&type=AJAX&s=PriorSet&codeid="+codeid+"&id="+id, "dialog-form");
	//$( "#dialog-form" ).dialog( "option", "title", 'Выберете приоритетный приз' );
	//$( "#dialog-form" ).dialog( "open" );
}
function ItemAdd(modul,part){
		SendAJAX("mod="+modul+"&type=AJAX&s=ItemAdd&part="+part);
		SendGetAJAX("mod="+modul+"&type=AJAX&s=ShowList&part="+part, modul+"List");
	}
	
function ClearAll(modul){
		SendGetAJAX("mod="+modul+"&type=AJAX&s=ClearAll", modul+"PartList");
	}

function PartAdd(modul){
		var arg = "mod="+modul+"&type=AJAX&s=PartAdd";
		var xmlHttp = getRequestObject();
		var addrSave=window.top.location.protocol+"//"+window.top.location.host;
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
			var id= xmlHttp.responseText;
			document.getElementById(modul+"PartList").innerHTML += "<div id='temp"+id+"'><div>";
			var arg2 = "mod="+modul+"&type=AJAX&s=ShowPart&id=" + id;
			var xmlHttp2 = getRequestObject();
			xmlHttp2.onreadystatechange = function() {
				if (xmlHttp2.readyState == 4) {
					document.getElementById("temp"+id).innerHTML=unescape(xmlHttp2.responseText);
					document.getElementById("temp"+id).id=modul+"Part"+id;
					} 
				}		
			xmlHttp2.open('POST', addrSave, true);
			xmlHttp2.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			xmlHttp2.setRequestHeader("Content-Length", arg2.length);
			xmlHttp2.send(arg2);
			}
		} 	
		xmlHttp.open('POST', addrSave, true);
	  	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	  	xmlHttp.setRequestHeader("Content-Length", arg.length);
	  	xmlHttp.send(arg);
	}
	
function SetToAllPart(modul,field){
	var nameData = "";
	nameData = prompt ("Введите новое значение:", nameData );		
	if (nameData != null)
			SendAJAX("mod="+modul+"&type=AJAX&s=SetToAll"+"&field="+field+"&new="+encodeURIComponent((nameData)));
	}

/*----- menus -----*/
function MenusChangeType(id,oldtype,type){
	//alert(id+"\n"+type);
	if (confirm("Вы действительно хотите изменить тип пункт меню?")){
		SendGetAJAX("mod=menus&type=AJAX&s=ItemSetType&id="+id+"&txt="+encodeURIComponent(type),"menusItem"+id);
		}else{
		document.getElementById("menusSelect"+id).value=oldtype;
		}
	}
	
function MenusChangeTypeP(id,oldtype,type){
	//alert(id+"\n"+type);
	if (confirm("Вы действительно хотите изменить тип пункт меню?")){
		SendGetAJAX("mod=menus&type=AJAX&s=ItemSetType&id="+id+"&txt="+encodeURIComponent(type),"menusItem"+id);
		}else{
		document.getElementById("menusSelectP"+id).value=oldtype;
		}
	}
	
function MenusItemAdd(part){
		SendAJAX("mod=menus&type=AJAX&s=ItemAdd&part="+part);
		SendGetAJAX("mod=menus&type=AJAX&s=ShowSubList&id="+part,"menusSubMenu"+part);
	}
	
function ShowSubLevel(id){
	document.getElementById("menusItemSubLink"+id).style.display="none";
	document.getElementById("menusItemSubLink_"+id).style.display="";
	document.getElementById("menusSubMenu"+id).style.display="";
	SendGetAJAX("mod=menus&type=AJAX&s=ShowSubList&id="+id,"menusSubMenu"+id);
	}

function HideSubLevel(id){
	document.getElementById("menusItemSubLink_"+id).style.display="none";
	document.getElementById("menusItemSubLink"+id).style.display="";
	document.getElementById("menusSubMenu"+id).style.display="none";
	}
	
/*----- Seo -----*/
	
function SeoWordAdd(type){
		var Word = encodeURIComponent((document.getElementById("SeoWordWord").value));
		var Desc = encodeURIComponent((document.getElementById("SeoWordDesc").value));
		var Link = encodeURIComponent((document.getElementById("SeoWordLink").value));
		var Title = encodeURIComponent((document.getElementById("SeoWordTitle").value));
		//alert(Word+"\n"+Desc+"\n"+Link+"\n"+Title);
		SendGetAJAX("mod=seo&type=AJAX&s=Add&link="+Link+"&word="+Word+"&desc="+Desc+"&title="+Title,"SeoWord");
	}

function Login(){
		var login = encodeURIComponent((document.getElementById("admin_login").value));
		var pass = encodeURIComponent((document.getElementById("admin_pass").value));
		var arg = "mod=login&type=AJAX&login="+login+"&pass="+pass;
		
		var xmlHttp = getRequestObject();
		var addrSave=window.top.location.protocol+"//"+window.top.location.host;
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				//alert(xmlHttp.responseText);
				if (xmlHttp.responseText == 1){
					document.getElementById("loginDiv").innerHTML="<h1>Авторизация прошла успешно</h1><h2>Автоматическое перенаправление через <span style='color: red;' id='countdown'></span>&nbsp; секунд</h2>";
					document.getElementById("countdown").innerHTML=4
					countredirect();
					}else{
					document.getElementById("loginDiv").innerHTML+="Неправильный логин или пароль<br>";
					}
			}
		}		
		xmlHttp.open('POST', addrSave, true);
	  	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
	  	xmlHttp.setRequestHeader("Content-Length", arg.length);
	  	xmlHttp.send(arg);
	}
	
function countredirect(){
		var currentsecond=document.getElementById("countdown").innerHTML;
		currentsecond-=1;
		document.getElementById("countdown").innerHTML=currentsecond;
		if (currentsecond==1)
			window.location="/menus/";
			else setTimeout("countredirect()",1000);
	}
	
function FaqAct(id){
   OB = document.getElementById("o_block" + id);
   TB = document.getElementById("t_block" + id);
   if ( TB.style.display == 'none'){
    TB.style.display = ''
    OB.style.display = 'none'
    }
   else{
    TB.style.display = 'none';
    OB.style.display = ''
    }
   }
   
function GaleryOpenWindow(img, txt){
		newImg = new Image(); 
		newImg.src = img; 
		win = window.open('','new','height=600, width=800, resizable=1, scrollbars=1, top=100, left=100');
		//win.document.write("<html><head><title>" + txt + "</title></head><body style='margin: 0; padding: 0;'><table width=100% height=100%><tr><td align=center valign=middle>");
		//win.document.write("<center><img id='img777' alt='идет загрузка...' src='/images/admin/indicator_medium.gif'></center>");
		win.document.write("<center><img id='img777' alt='"+txt+"' src='"+img+"'></center>");
		//win.document.write("</td></tr></table></body></html>");	
		//while (!newImg.complete)
		//	pause(100);
		//win.close();
		//win2 = window.open('','new2','height='+(newImg.height+20)+', width='+(newImg.width+20) + ', resize=0');
		//win.document.write("<html><head><title>" + txt + "</title></head><body style='margin: 0; padding: 0;'><table width=100% height=100%><tr><td align=center valign=middle>");
		//win2.document.write("<img alt='"+txt+"' src='"+ newImg.src +"'>");
		//win.document.getElementById("img777").src = newImg.src;
		//win.resizeTo(newImg.width+24,newImg.height+72);
	}
	
function getElementsByClassName(searchClass,node,tag) {
   var classElements = new Array();

   if ( node == null )
      node = document;
   if ( tag == null )
      tag = '*';
   var elements = node.getElementsByTagName(tag);
   var elemLength = elements.length;
   var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
   for (var i = 0, j = 0; i < elemLength; i++) {
      if ( pattern.test(elements[i].className) ) {
         classElements[j] = elements[i];
         j++;
      }
   }
   return classElements;
}	
	
function ShowHide(className,id){
	elems=getElementsByClassName(className);
	for(i=0;i<elems.length;i++)
		if (elems[i].getAttribute('id')!=(className+id))
			elems[i].style.display="none";
			
	elems=getElementsByClassName("TabPanelCaption");
	for(i=0;i<elems.length;i++)
		if (elems[i].getAttribute('id')!=("TabPanelCaption"+id))
			elems[i].style.background="LightSkyBlue";
			
	//if (document.getElementById("TabPanel"+id).innerHTML=="")
	if (document.getElementById(className+id).style.display==""){
		document.getElementById(className+id).style.display="none";
		}
		else {
			document.getElementById(className+id).style.display="";
			document.getElementById("TabPanelCaption"+id).style.background="orangered";
			SendGetAJAX("type=cms&mod="+id+"&command=Show",className+id);
			}
	}
