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
	});
});

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 ChangeField(table,field,id,objID){
	nameData = prompt ("Введите новое значение:", $('#'+objID).html() );		
	if (nameData != null)
		$('#'+objID).load('/index.php',{mod: 'edit', type: 'AJAX', table: table, field: field, id: id, new_value: nameData});
	}
	
function EditorField(table,field,id)
	{window.open("/forms/editor.php?table="+table+"&field="+field+"&id="+id,"Edit","height=600, width=800, toolbar=0, location=1");}

function OpenMedia(table,field,id)
	{window.open("/forms/file_f.php?s=edit&table="+table+"&field="+field+"&id="+id,'',"width=450,height=100");}
	
function Refresh(module,id)
	{$('#'+module+id).animate({opacity: 0.1}, 200).load('/index.php',{mod: module, type: 'AJAX', s: 'Refresh', id: id }).animate({opacity: 1.0}, 200);}

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){
	$('#'+modul+who+id).animate({opacity: 0.1}, 500);
	if (direct==1) arg = who+"Up";
	if (direct==0) arg = who+"Down";
	$.post('/index.php', {mod: modul, type: 'AJAX', s: arg, id: id}, function(newid){
		$('#'+modul+who+newid).animate({opacity: 0.1}, 500);
		if (newid == id){
			if (direct==1) alert("Выше нельзя!");
			if (direct==0) alert("Ниже нельзя!");
			$('#'+modul+who+id).load('/index.php',{mod: modul, type: 'AJAX', s: 'Show'+who, id: id }).animate({opacity: 1.0}, 500);
			}
		else{
			try {
				$('#'+modul+who+newid).attr("id", "temp");
				$('#'+modul+who+id).attr("id", modul+who+newid);
				$('#temp').attr("id", modul+who+id);
				$('#'+modul+who+id).load('/index.php',{mod: modul, type: 'AJAX', s: 'Show'+who, id: id }).animate({opacity: 1.0}, 500);
				$('#'+modul+who+newid).load('/index.php',{mod: modul, type: 'AJAX', s: 'Show'+who, id: newid }).animate({opacity: 1.0}, 500);
				}
			catch (error) {
				$('#'+modul+who+id).attr("id", modul+who+newid);
				$('#'+modul+who+newid).load('/index.php',{mod: modul, type: 'AJAX', s: 'Show'+who, id: newid }).animate({opacity: 1.0}, 500);
				}
			}
		}, 'text');
	}

function Hide(modul,who,id)
	{$('#'+modul+who+id).animate({opacity: 0.1}, 200).load('/index.php',{mod: modul, type: 'AJAX', s: who+'Hide', id: id }).animate({opacity: 1.0}, 200)}

function Show(modul,who,id)
	{$('#'+modul+who+id).animate({opacity: 0.1}, 200).load('/index.php',{mod: modul, type: 'AJAX', s: who+'Show', id: id }).animate({opacity: 1.0}, 200)}
	
function HideM(id)
	{$('#menusItemPanel'+id).animate({opacity: 0.1}, 200).load('/index.php',{mod:'menus', type:'AJAX', s:'ItemHide', id:id}).animate({opacity: 1.0}, 200)}

function ShowM(id)
	{$('#menusItemPanel'+id).animate({opacity: 0.1}, 200).load('/index.php',{mod:'menus', type:'AJAX', s:'ItemShow', id:id}).animate({opacity: 1.0}, 200)}

function RefreshList(modul, part)
	{$('#'+modul+'List').animate({opacity: 0.1}, 200).load('/index.php',{mod: modul, type: 'AJAX', s: 'ShowList', part: part }).animate({opacity: 1.0}, 200);}
	
function ItemCheck(modul,id,block)
	{$('#'+modul+'Item'+id).animate({opacity: 0.1}, 200).load('/index.php',{mod: modul, type: 'AJAX', s: 'ItemSetBlock', id: id, block: block}).animate({opacity: 1.0}, 200)}
	
function ItemDel(modul,id){
	if (confirm("Вы действительно хотите удалить элемент?"))
		$('#'+modul+"Item"+id).animate({opacity: 0.1}, 500, function(){
			$('#'+modul+"Item"+id).load('/index.php',{mod: modul, type: 'AJAX', s: 'ItemDel', id: id }).remove();
			})
	}
	
function PartDel(modul,id){
	if (confirm("Вы действительно хотите удалить раздел?\n(Раздел будет удален вместе со всеми элементами)")) 
		$('#'+modul+"Part"+id).animate({opacity: 0.1}, 500, function(){
			$('#'+modul+"Part"+id).load('/index.php',{mod: modul, type: 'AJAX', s: 'PartDel', id: id }).remove();
			})
	}
	
function ItemAdd(modul,part){
	count = $('#ItemAddCount').attr('value');
	dir = $('#ItemAddDir').attr('value');
	$('#'+modul+'List').animate({opacity: 0.1}, 200).load('/index.php',{mod:modul, type:'AJAX', s:'ItemAdd', part:part, count:count, dir:dir}).animate({opacity: 1.0}, 200);
	}
	
function PartAdd(modul)
	{$('#'+modul+'PartList').animate({opacity: 0.1}, 200).load('/index.php',{mod: modul, type: 'AJAX', s: 'PartAdd' }).animate({opacity: 1.0}, 200);}
	
function ClearAll(modul){
	if (confirm("Вы действительно хотите очисть всю базу данного модуля?")) 
		$('#'+modul+"PartList").load('/index.php',{mod: modul, type: 'AJAX', s: 'ClearAll'});
	}
	
function SetToAllPart(modul,field){
	var nameData = "";
	nameData = prompt ("Введите новое значение:", nameData );		
	if (nameData != null){
		$('#'+modul+"PartList").animate({opacity: 0.1}, 700);
		$('#'+modul+"PartList").load('/index.php',{mod: modul, type: 'AJAX', s: 'SetToAll', field: field, new_value: nameData });
		$('#'+modul+"PartList").animate({opacity: 1.0}, 700);
		}
	}

function FaqAct(id)
	{$('#t_block'+id).slideToggle();$('#o_block'+id).slideToggle();}
   
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){
		qString = $(formObj).formSerialize();
		$.post("/index.php", qString, function(rez){
			//alert(rez);
			$('#opros').fadeOut().html(rez).fadeIn();
			},'text');
		}
		else alert('Надо выбрать вариант ответа!');
}

function galeryAct(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){
		qString = $(formObj).formSerialize();
		$.post("/index.php", qString, function(rez){
			//alert(rez);
			$('#opros1').fadeOut().html(rez).fadeIn();
			},'text');
		}
		else alert('Надо выбрать вариант ответа!');
}
		
/*----- menus -----*/
function MenusClick(id){
	$(".simpleTree div").slideUp();
	$("#menusItemPanel"+id).slideDown();
	}

function MenusChangeType(id,oldtype,type){
	if (confirm("Вы действительно хотите изменить тип пункт меню?"))
		$('#menusItemPanel'+id).animate({opacity: 0.1}, 200).load('/index.php',{mod:'menus', type:'AJAX', s:'ItemSetType', id:id, txt:type}).animate({opacity: 1.0}, 200);
		else document.getElementById("menusSelect"+id).value=oldtype;
	}
	
function MenusChangeTypeP(id,oldtype,type){
	if (confirm("Вы действительно хотите изменить тип пункт меню?"))
		$('#menusItemPanel'+id).animate({opacity: 0.1}, 200).load('/index.php',{mod:'menus', type:'AJAX', s:'ItemSetType', id:id, txt:type}).animate({opacity: 1.0}, 200);
		else document.getElementById("menusSelectP"+id).value=oldtype;
	}
	
function MenusItemAdd(parent){
	$('#menusItem'+parent+' ul').animate({opacity: 0.1}, 200);
	$.post('/index.php', {mod:'menus', type:'AJAX', s:'ItemAdd', id:parent}, function(rez){
		//alert(parent+rez);
		$('#menusItem'+parent+' ul').html(rez);
		simpleTreeCollection.get(0).setTreeNodes($('#menusItem'+parent+ ' ul'), true);
		},'text');
	$('#menusItem'+parent+' ul').animate({opacity: 1.0}, 200);
	}
	
/*----- Seo -----*/
	
function SeoWordAdd(type){
	qString = $("#SeoForm").formSerialize();
	//alert(qString);
	$.post("/index.php", qString, function(rez){
		//alert(rez);
		$('#SeoWord').fadeOut().html(rez).fadeIn();
		},'text');
	}
	
function SeoWordDel(id)
	{$('#SeoWord').fadeOut().load('/index.php',{mod:'seo', type:'AJAX', s:'ItemDel', id:id}).fadeIn();}
	
/*----- Прочее -----*/

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);
	}
